@eyeauras/insight-cli 0.7.0 → 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 (117) hide show
  1. package/.cli-package-build.json +1 -1
  2. package/SKILL.md +1 -1
  3. package/dist/src/activity-audit.d.ts +7 -0
  4. package/dist/src/activity-audit.js +14 -4
  5. package/dist/src/analysis-storage.d.ts +5 -1
  6. package/dist/src/analysis-storage.js +9 -2
  7. package/dist/src/audit-retention.d.ts +8 -2
  8. package/dist/src/audit-retention.js +68 -7
  9. package/dist/src/cli.js +19 -5
  10. package/dist/src/context-diagnostics.d.ts +1 -1
  11. package/dist/src/context-diagnostics.js +10 -2
  12. package/dist/src/contexts.d.ts +118 -10
  13. package/dist/src/contexts.js +851 -199
  14. package/dist/src/debugger.js +2 -1
  15. package/dist/src/diagnostic-error.js +1 -1
  16. package/dist/src/inline-script.js +3 -4
  17. package/dist/src/lifecycle.d.ts +11 -0
  18. package/dist/src/lifecycle.js +34 -6
  19. package/dist/src/native-inputs.d.ts +6 -0
  20. package/dist/src/native-inputs.js +30 -6
  21. package/dist/src/native-queries.js +1 -6
  22. package/dist/src/native-service.d.ts +40 -0
  23. package/dist/src/native-service.js +406 -0
  24. package/dist/src/research.d.ts +29 -1
  25. package/dist/src/research.js +106 -27
  26. package/dist/src/server.d.ts +38 -1
  27. package/dist/src/server.js +160 -12
  28. package/dist/src/storage-gc.js +1 -1
  29. package/dist/src/sync-policy.js +2 -1
  30. package/dist/src/timed-backend.js +8 -0
  31. package/dist/src/timing-report.d.ts +32 -0
  32. package/dist/src/timing-report.js +74 -0
  33. package/dist/src/tool-runtime/identity.js +86 -1
  34. package/dist/src/tool-runtime/supervisor.js +6 -5
  35. package/dist/src/transport.d.ts +35 -0
  36. package/dist/src/transport.js +77 -7
  37. package/dist/src/unresolved-guidance.d.ts +46 -0
  38. package/dist/src/unresolved-guidance.js +55 -0
  39. package/dist/src/windbg.d.ts +1 -1
  40. package/dist/src/worker-lease.d.ts +17 -0
  41. package/dist/src/worker-lease.js +50 -0
  42. package/dist/src/workspace.d.ts +3 -9
  43. package/dist/src/workspace.js +9 -41
  44. package/package.json +1 -1
  45. package/references/native/InsightHeadlessMain.java +9 -2
  46. package/references/native/InsightNativeCheckout.java +113 -43
  47. package/references/native/InsightNativeFingerprint.java +28 -1
  48. package/references/native/InsightNativeRead.java +32 -9
  49. package/references/native/InsightNativeService.java +43 -0
  50. package/references/native/InsightNativeView.java +17 -6
  51. package/references/native/InsightOwnedScripts.java +170 -0
  52. package/references/native/InsightWorkerLease.java +132 -0
  53. package/references/recovery.md +68 -3
  54. package/references/research.md +38 -4
  55. package/references/setup.md +5 -1
  56. package/skill-bundle/insight-artifacts/SKILL.md +1 -1
  57. package/skill-bundle/insight-artifacts/references/recovery.md +68 -3
  58. package/skill-bundle/insight-binary/SKILL.md +1 -1
  59. package/skill-bundle/insight-capture/SKILL.md +1 -1
  60. package/skill-bundle/insight-cli/SKILL.md +1 -1
  61. package/skill-bundle/insight-cli/references/recovery.md +68 -3
  62. package/skill-bundle/insight-cli/references/setup.md +5 -1
  63. package/skill-bundle/insight-die/SKILL.md +1 -1
  64. package/skill-bundle/insight-dnspy/SKILL.md +1 -1
  65. package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
  66. package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
  67. package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
  68. package/skill-bundle/insight-frida/SKILL.md +1 -1
  69. package/skill-bundle/insight-ghidra/SKILL.md +1 -1
  70. package/skill-bundle/insight-ghidra/references/recovery.md +68 -3
  71. package/skill-bundle/insight-ghidra/references/research.md +38 -4
  72. package/skill-bundle/insight-ghidra/references/setup.md +5 -1
  73. package/skill-bundle/insight-ilspy/SKILL.md +1 -1
  74. package/skill-bundle/insight-interop/SKILL.md +1 -1
  75. package/skill-bundle/insight-lldb/SKILL.md +1 -1
  76. package/skill-bundle/insight-llvm/SKILL.md +1 -1
  77. package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
  78. package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
  79. package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
  80. package/skill-bundle/insight-overview/SKILL.md +1 -1
  81. package/skill-bundle/insight-procmon/SKILL.md +1 -1
  82. package/skill-bundle/insight-re/SKILL.md +1 -1
  83. package/skill-bundle/insight-re/references/recovery.md +68 -3
  84. package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
  85. package/skill-bundle/insight-strace/SKILL.md +1 -1
  86. package/skill-bundle/insight-tshark/SKILL.md +1 -1
  87. package/skill-bundle/insight-windbg/SKILL.md +1 -1
  88. package/skill-bundle/manifest.json +1 -1
  89. package/skills/insight-artifacts/SKILL.md +1 -1
  90. package/skills/insight-artifacts/references/recovery.md +68 -3
  91. package/skills/insight-binary/SKILL.md +1 -1
  92. package/skills/insight-capture/SKILL.md +1 -1
  93. package/skills/insight-die/SKILL.md +1 -1
  94. package/skills/insight-dnspy/SKILL.md +1 -1
  95. package/skills/insight-dotnet-dump/SKILL.md +1 -1
  96. package/skills/insight-dotnet-stack/SKILL.md +1 -1
  97. package/skills/insight-dotnet-trace/SKILL.md +1 -1
  98. package/skills/insight-frida/SKILL.md +1 -1
  99. package/skills/insight-ghidra/SKILL.md +1 -1
  100. package/skills/insight-ghidra/references/recovery.md +68 -3
  101. package/skills/insight-ghidra/references/research.md +38 -4
  102. package/skills/insight-ghidra/references/setup.md +5 -1
  103. package/skills/insight-ilspy/SKILL.md +1 -1
  104. package/skills/insight-interop/SKILL.md +1 -1
  105. package/skills/insight-lldb/SKILL.md +1 -1
  106. package/skills/insight-llvm/SKILL.md +1 -1
  107. package/skills/insight-managed-heap/SKILL.md +1 -1
  108. package/skills/insight-managed-metadata/SKILL.md +1 -1
  109. package/skills/insight-mitmproxy/SKILL.md +1 -1
  110. package/skills/insight-overview/SKILL.md +1 -1
  111. package/skills/insight-procmon/SKILL.md +1 -1
  112. package/skills/insight-re/SKILL.md +1 -1
  113. package/skills/insight-re/references/recovery.md +68 -3
  114. package/skills/insight-sevenzip/SKILL.md +1 -1
  115. package/skills/insight-strace/SKILL.md +1 -1
  116. package/skills/insight-tshark/SKILL.md +1 -1
  117. package/skills/insight-windbg/SKILL.md +1 -1
@@ -1 +1 @@
1
- {"version":1,"artifact":"49ed891cefff58d12359131fb56461982e403b544ff7a15e74661553b6219e00"}
1
+ {"version":1,"artifact":"3c5d4ee1cf073825a74ba09b3f8b851cccefea0688d1cae155be30f698c4713f"}
package/SKILL.md CHANGED
@@ -3,7 +3,7 @@ name: insight-cli
3
3
  description: Choose and prepare reverse-engineering capabilities from the insight-cli toolbox for binary, managed-code and runtime investigations. Use to discover the appropriate tool or its packaged skill before installing native runtimes.
4
4
  ---
5
5
 
6
- # insight-cli 0.7.0
6
+ # insight-cli 0.8.0
7
7
 
8
8
  If local help/status reports AppData or IPC access denied, retry that **read-only probe**
9
9
  with the agent host's normal permission escalation, then use that route for later authorized
@@ -42,10 +42,17 @@ export declare class AuditStore {
42
42
  readonly directory: string;
43
43
  readonly path: string;
44
44
  private readonly initialPolicy;
45
+ private readonly admissionMs;
46
+ /**
47
+ * `admissionMs` bounds the wait of a write for the shared writer lock (default three seconds). Its opening reads
48
+ * and its commit each wait for the database that long as well, and never less than three seconds; the waits add up.
49
+ */
45
50
  constructor(directory: string, limits?: {
46
51
  events: number;
47
52
  days: number;
48
53
  databaseBytes?: number;
54
+ }, options?: {
55
+ admissionMs?: number;
49
56
  });
50
57
  private open;
51
58
  private insert;
@@ -6,7 +6,7 @@ import { join } from 'node:path';
6
6
  import { performance } from 'node:perf_hooks';
7
7
  import { CliError } from '@eyeauras/cli-factory';
8
8
  import { diagnosticFailure } from './diagnostic-error.js';
9
- import { auditLimits, auditPolicy, auditUnavailable, initializeRetention, retentionState, auditStorageMode, requireAuditStorageMode, collectAudit, acquireAuditWriter } from './audit-retention.js';
9
+ import { auditLimits, auditPolicy, auditUnavailable, initializeRetention, retentionState, auditStorageMode, requireAuditStorageMode, collectAudit, acquireAuditWriter, auditAdmissionMs } from './audit-retention.js';
10
10
  export { auditLimits } from './audit-retention.js';
11
11
  const applicationId = 0x49534155;
12
12
  const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
@@ -101,10 +101,18 @@ export class AuditStore {
101
101
  directory;
102
102
  path;
103
103
  initialPolicy;
104
- constructor(directory, limits = auditLimits) {
104
+ admissionMs;
105
+ /**
106
+ * `admissionMs` bounds the wait of a write for the shared writer lock (default three seconds). Its opening reads
107
+ * and its commit each wait for the database that long as well, and never less than three seconds; the waits add up.
108
+ */
109
+ constructor(directory, limits = auditLimits, options = {}) {
105
110
  this.directory = directory;
106
111
  this.path = join(directory, 'activity.sqlite');
107
112
  this.initialPolicy = auditPolicy(limits);
113
+ this.admissionMs = options.admissionMs ?? auditAdmissionMs;
114
+ if (!Number.isSafeInteger(this.admissionMs) || this.admissionMs < 1 || this.admissionMs > 60000)
115
+ throw new Error('Invalid audit admission wait.');
108
116
  }
109
117
  open(write) {
110
118
  const existing = stat(this.directory);
@@ -119,8 +127,10 @@ export class AuditStore {
119
127
  return;
120
128
  let db;
121
129
  try {
130
+ // A writer's reads before admission wait as long as its admission does: another writer's durable commit can
131
+ // hold the database for longer than SQLite's short default under disk load.
122
132
  db = new DatabaseSync(this.path, { readOnly: !write });
123
- db.exec('PRAGMA busy_timeout=3000;');
133
+ db.exec('PRAGMA busy_timeout=' + (write ? Math.max(3000, this.admissionMs) : 3000) + ';');
124
134
  db.exec('BEGIN');
125
135
  const version = Number(db.prepare('PRAGMA user_version').get()?.user_version), app = Number(db.prepare('PRAGMA application_id').get()?.application_id), foreign = version === 0 && app === 0 && Boolean(db.prepare("SELECT name FROM sqlite_master WHERE type='table'").get());
126
136
  db.exec('END');
@@ -180,7 +190,7 @@ export class AuditStore {
180
190
  throw new Error('Invalid internal audit event.');
181
191
  const db = this.open(true);
182
192
  try {
183
- acquireAuditWriter(db);
193
+ acquireAuditWriter(db, this.directory, this.admissionMs);
184
194
  const metadata = this.metadata(db), version = Number(db.prepare('PRAGMA user_version').get()?.user_version);
185
195
  requireAuditStorageMode(db);
186
196
  if (version === 1)
@@ -7,9 +7,13 @@ export declare class AnalysisStorage {
7
7
  private readonly storeOverride;
8
8
  private readonly release;
9
9
  private readonly checkpoint?;
10
+ /** Stops idle owner services and idle warm workers (they hold no work) before the busy checks. */
11
+ private readonly quiesce?;
10
12
  private active;
11
13
  private changing;
12
- constructor(storeOverride: ProfileStoreContract | undefined, release: (c: CommandContext) => Promise<void>, checkpoint?: ((phase: string) => Promise<void>) | undefined);
14
+ constructor(storeOverride: ProfileStoreContract | undefined, release: (c: CommandContext) => Promise<void>, checkpoint?: ((phase: string) => Promise<void>) | undefined,
15
+ /** Stops idle owner services and idle warm workers (they hold no work) before the busy checks. */
16
+ quiesce?: ((c: CommandContext) => Promise<void>) | undefined);
13
17
  private control;
14
18
  private store;
15
19
  private binding;
@@ -124,12 +124,16 @@ export class AnalysisStorage {
124
124
  storeOverride;
125
125
  release;
126
126
  checkpoint;
127
+ quiesce;
127
128
  active = new Map();
128
129
  changing = new Set();
129
- constructor(storeOverride, release, checkpoint) {
130
+ constructor(storeOverride, release, checkpoint,
131
+ /** Stops idle owner services and idle warm workers (they hold no work) before the busy checks. */
132
+ quiesce) {
130
133
  this.storeOverride = storeOverride;
131
134
  this.release = release;
132
135
  this.checkpoint = checkpoint;
136
+ this.quiesce = quiesce;
133
137
  }
134
138
  control(c) { return join(c.appArguments.AppDataDirectory, 'storage'); }
135
139
  store(c) { return this.storeOverride ?? new ProfileStore({ applicationId: c.appArguments.AppName, appArguments: c.appArguments }); }
@@ -247,7 +251,10 @@ export class AnalysisStorage {
247
251
  busy(directory) { return this.changing.has(directory); }
248
252
  async exclusive(c, action) {
249
253
  const key = c.appArguments.AppDataDirectory;
250
- if (this.changing.has(key) || this.active.get(key) || toolProfileBusy(key))
254
+ if (this.changing.has(key) || this.active.get(key))
255
+ fail('busy', 'Finish active commands before storage migration.');
256
+ await this.quiesce?.(c);
257
+ if (toolProfileBusy(key))
251
258
  fail('busy', 'Finish active commands before storage migration.');
252
259
  this.changing.add(key);
253
260
  try {
@@ -31,8 +31,14 @@ export declare function auditStorageMode(db: DatabaseSync): {
31
31
  journalMode: string;
32
32
  };
33
33
  export declare function requireAuditStorageMode(db: DatabaseSync): void;
34
- /** Retry only a definitely unacquired auxiliary DB lock, never INSERT, COMMIT or a tool action. */
35
- export declare function acquireAuditWriter(db: DatabaseSync): void;
34
+ export declare const auditAdmissionMs = 3000;
35
+ /**
36
+ * Fair writer admission across processes. SQLite has no queue: a continuously re-entering writer can win every
37
+ * free interval and starve others past the deadline. Each writer registers an ordered waiter marker, only the
38
+ * oldest live waiter contends for the lock, and the marker is removed as soon as the lock is held.
39
+ * Retry only a definitely unacquired auxiliary DB lock, never INSERT, COMMIT or a tool action.
40
+ */
41
+ export declare function acquireAuditWriter(db: DatabaseSync, directory: string, admissionMs?: number): void;
36
42
  export declare function liveAuditBytes(db: DatabaseSync): number;
37
43
  /** The caller holds BEGIN IMMEDIATE. Summary insertion is direct, never another append/GC call. */
38
44
  export declare function collectAudit(db: DatabaseSync, now: number, incoming: number, pruned: number, state: RetentionState, summary: (data: Record<string, unknown>) => void): void;
@@ -1,3 +1,6 @@
1
+ import { readdirSync, unlinkSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { randomBytes } from 'node:crypto';
1
4
  import { CliError } from '@eyeauras/cli-factory';
2
5
  export const auditLimits = { events: 20000, days: 30, eventBytes: 4096, databaseBytes: 16 * 1024 * 1024, sweepIntervalMs: 5 * 60000 };
3
6
  export function auditUnavailable() { throw new CliError('Audit history is unavailable or incompatible; preserve its files. No history was reset.', { code: 'audit.unavailable' }); }
@@ -37,12 +40,65 @@ export function auditStorageMode(db) { return { autoVacuum: Number(db.prepare('P
37
40
  export function requireAuditStorageMode(db) { const mode = auditStorageMode(db); if (mode.autoVacuum !== 1 || mode.journalMode !== 'delete')
38
41
  auditUnavailable(); }
39
42
  const writerWait = new Int32Array(new SharedArrayBuffer(4));
40
- /** Retry only a definitely unacquired auxiliary DB lock, never INSERT, COMMIT or a tool action. */
41
- export function acquireAuditWriter(db) {
42
- const deadline = performance.now() + 3000;
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;
43
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. */ }
44
96
  try {
45
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
+ }
46
102
  const remaining = deadline - performance.now();
47
103
  db.exec('PRAGMA busy_timeout=' + Math.max(0, Math.min(50, Math.ceil(remaining))));
48
104
  try {
@@ -58,14 +114,19 @@ export function acquireAuditWriter(db) {
58
114
  catch { }
59
115
  if (!busy || performance.now() >= deadline)
60
116
  throw error;
61
- // SQLite's long busy-handler backoff can repeatedly miss short free intervals.
62
- // Restart it with a bounded jitter so a continuous producer cannot monopolize admission.
63
- Atomics.wait(writerWait, 0, 0, Math.max(0, Math.min(5 + (process.pid + attempt++ * 13) % 21, deadline - performance.now())));
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())));
64
119
  }
65
120
  }
66
121
  }
67
122
  finally {
68
- db.exec('PRAGMA busy_timeout=3000');
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)));
69
130
  }
70
131
  }
71
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); }
package/dist/src/cli.js CHANGED
@@ -57,6 +57,7 @@ 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';
60
61
  import { ActivityAudit } from './audit-commands.js';
61
62
  import { timedBackend } from './timed-backend.js';
62
63
  import { readInitialProgress } from './initial-progress.js';
@@ -78,6 +79,8 @@ class Owner {
78
79
  try {
79
80
  if (!quiescent)
80
81
  return await action();
82
+ if (current)
83
+ await (await current.backend)?.quiesce?.();
81
84
  const processes = await runtimeProcesses(directory);
82
85
  if (processes.length)
83
86
  fail('busy', 'Close Ghidra contexts and stop the owned server before changing or checking the runtime.', { processes });
@@ -164,6 +167,8 @@ class Owner {
164
167
  fail('busy', 'Finish research operations before ' + name + '.');
165
168
  this.runtimeChanging.add(c.appArguments.AppDataDirectory);
166
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?.();
167
172
  // A missing private-worker receipt does not prove an interrupted native helper stopped.
168
173
  const helpers = await migrationProcessBlockers(c.appArguments.AppDataDirectory);
169
174
  const workers = (await runtimeProcesses(analysisDirectory(c))).filter(p => p.kind !== 'server');
@@ -181,6 +186,9 @@ class Owner {
181
186
  fail('busy', 'Storage migration is in progress.');
182
187
  if (this.runtimeChanging.has(directory))
183
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?.();
184
192
  if (toolProfileBusy(directory))
185
193
  fail('busy', 'A tool operation is active.');
186
194
  if ((await listProcesses(directory)).some(r => !['exited', 'failed'].includes(r.state)))
@@ -195,6 +203,9 @@ class Owner {
195
203
  this.profiles.delete(directory);
196
204
  }
197
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?.(); }
198
209
  async releaseStorage(c) {
199
210
  const directory = c.appArguments.AppDataDirectory, profile = this.profiles.get(directory);
200
211
  if (!profile)
@@ -272,6 +283,7 @@ const fields = [
272
283
  ['initialImportSeconds', '--initial-import-seconds <seconds>', 'Initial import/analysis budget (default 3600, range 1–86400 seconds)'],
273
284
  ['saveSeconds', '--save-seconds <seconds>', 'Native save/export budget (default 120, range 1–3600 seconds)'],
274
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)'],
275
287
  ['debuggerPython', '--debugger-python <path>', 'Optional Python executable for a configured debugger offer'],
276
288
  ['windbgDir', '--windbg-dir <path>', 'Optional Windows debugger runtime directory'],
277
289
  ['archiveUrl', '--archive-url <url>', 'Explicit archive service base URL (disabled by default)'],
@@ -337,18 +349,20 @@ function scopedFailures(entry, owner, parents = []) {
337
349
  throw new CliError(error.message, { code: error.code, exitCode: error.exitCode, next: error.next, result: { ...result, ...selected } });
338
350
  }
339
351
  };
340
- return path[1] === 'open' || input.options.session && input.options.target ? traceCommand(join(analysisDirectory(c), 'workspace'), name, execute, { session: input.options.session, target: input.options.target }) : 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();
341
355
  } } : {}) };
342
356
  }
343
357
  export function createDefinition(options = {}) {
344
358
  const owner = new Owner(options);
345
- 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));
346
360
  owner.storage = storage;
347
361
  const definition = {
348
362
  name: 'insight-cli', applicationId: 'insight-cli', version: packageVersion, description: 'Isolated research contexts and coordinated Ghidra analysis',
349
363
  resources: [owner], permissions: { categories: [{ name: 'Destructive', description: 'Explicit deletion or replacement of retained research data', enabledByDefault: false }] }, ...(options.runtime ? { runtime: options.runtime } : {}),
350
364
  profile: { fields: fields.map(([name, flags, description]) => ({ name: name, flags: flags, description: description,
351
- ...(['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) } : {}) })) },
352
366
  auth: {
353
367
  loginOptions: [{ flags: '--role <role>', description: 'External reader, publisher or archive role', defaultValue: 'reader' },
354
368
  { flags: '--password-stdin', description: 'Read the password from stdin' }],
@@ -465,9 +479,9 @@ export function createDefinition(options = {}) {
465
479
  }, { permission: Permission.Update, options: [{ flags: '--initial-import-seconds <seconds>', description: 'Initial import/analysis: 1–86400 seconds' },
466
480
  { flags: '--save-seconds <seconds>', description: 'Native save/export: 1–3600 seconds' }] })
467
481
  ]),
468
- 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' }] }),
469
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] }),
470
- 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' }] }),
471
485
  command('open [input]', 'Start independent work or continue a context', async ({ args, options: o }, c) => {
472
486
  if (Boolean(args.input) === Boolean(o.target))
473
487
  fail('invalid', 'Supply exactly one input path or --target.');
@@ -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
  }