@eyeauras/insight-cli 0.9.2 → 0.9.3

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 (80) hide show
  1. package/.cli-package-build.json +1 -1
  2. package/README.md +5 -5
  3. package/SKILL.md +1 -1
  4. package/dist/src/cli.js +29 -6
  5. package/dist/src/core/coordinator.d.ts +37 -5
  6. package/dist/src/core/coordinator.js +103 -42
  7. package/dist/src/core/legacy-import.js +2 -2
  8. package/dist/src/hub/admin.d.ts +15 -0
  9. package/dist/src/hub/admin.js +10 -1
  10. package/dist/src/hub/client.d.ts +3 -1
  11. package/dist/src/hub/client.js +4 -0
  12. package/dist/src/hub/commands.d.ts +2 -1
  13. package/dist/src/hub/commands.js +33 -4
  14. package/dist/src/hub/contract.d.ts +27 -0
  15. package/dist/src/hub/ledger-store.d.ts +40 -2
  16. package/dist/src/hub/ledger-store.js +38 -8
  17. package/dist/src/hub/ledger.js +26 -3
  18. package/dist/src/hub/server.js +33 -1
  19. package/dist/src/hub/store.d.ts +29 -0
  20. package/dist/src/hub/store.js +109 -14
  21. package/dist/src/native/contract.d.ts +4 -3
  22. package/dist/src/native/ghidra.d.ts +1 -1
  23. package/dist/src/native/ghidra.js +4 -2
  24. package/dist/src/research.js +2 -0
  25. package/dist/src/work/client.d.ts +6 -3
  26. package/dist/src/work/client.js +12 -9
  27. package/dist/src/work/commands.js +33 -25
  28. package/dist/src/work/model.d.ts +2 -0
  29. package/package.json +1 -1
  30. package/references/native/InsightWcOps.java +42 -5
  31. package/skill-bundle/insight-artifacts/SKILL.md +1 -1
  32. package/skill-bundle/insight-binary/SKILL.md +1 -1
  33. package/skill-bundle/insight-capture/SKILL.md +1 -1
  34. package/skill-bundle/insight-cli/SKILL.md +1 -1
  35. package/skill-bundle/insight-die/SKILL.md +1 -1
  36. package/skill-bundle/insight-dnspy/SKILL.md +1 -1
  37. package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
  38. package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
  39. package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
  40. package/skill-bundle/insight-frida/SKILL.md +1 -1
  41. package/skill-bundle/insight-ghidra/SKILL.md +6 -4
  42. package/skill-bundle/insight-ilspy/SKILL.md +1 -1
  43. package/skill-bundle/insight-interop/SKILL.md +1 -1
  44. package/skill-bundle/insight-lldb/SKILL.md +1 -1
  45. package/skill-bundle/insight-llvm/SKILL.md +1 -1
  46. package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
  47. package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
  48. package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
  49. package/skill-bundle/insight-overview/SKILL.md +1 -1
  50. package/skill-bundle/insight-procmon/SKILL.md +1 -1
  51. package/skill-bundle/insight-re/SKILL.md +1 -1
  52. package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
  53. package/skill-bundle/insight-strace/SKILL.md +1 -1
  54. package/skill-bundle/insight-tshark/SKILL.md +1 -1
  55. package/skill-bundle/insight-windbg/SKILL.md +1 -1
  56. package/skill-bundle/manifest.json +1 -1
  57. package/skills/insight-artifacts/SKILL.md +1 -1
  58. package/skills/insight-binary/SKILL.md +1 -1
  59. package/skills/insight-capture/SKILL.md +1 -1
  60. package/skills/insight-die/SKILL.md +1 -1
  61. package/skills/insight-dnspy/SKILL.md +1 -1
  62. package/skills/insight-dotnet-dump/SKILL.md +1 -1
  63. package/skills/insight-dotnet-stack/SKILL.md +1 -1
  64. package/skills/insight-dotnet-trace/SKILL.md +1 -1
  65. package/skills/insight-frida/SKILL.md +1 -1
  66. package/skills/insight-ghidra/SKILL.md +6 -4
  67. package/skills/insight-ilspy/SKILL.md +1 -1
  68. package/skills/insight-interop/SKILL.md +1 -1
  69. package/skills/insight-lldb/SKILL.md +1 -1
  70. package/skills/insight-llvm/SKILL.md +1 -1
  71. package/skills/insight-managed-heap/SKILL.md +1 -1
  72. package/skills/insight-managed-metadata/SKILL.md +1 -1
  73. package/skills/insight-mitmproxy/SKILL.md +1 -1
  74. package/skills/insight-overview/SKILL.md +1 -1
  75. package/skills/insight-procmon/SKILL.md +1 -1
  76. package/skills/insight-re/SKILL.md +1 -1
  77. package/skills/insight-sevenzip/SKILL.md +1 -1
  78. package/skills/insight-strace/SKILL.md +1 -1
  79. package/skills/insight-tshark/SKILL.md +1 -1
  80. package/skills/insight-windbg/SKILL.md +1 -1
@@ -1 +1 @@
1
- {"version":1,"artifact":"1315e5bbeb5a93970933bff9a23cb319d31114d7c8e74f4cde32335bc1d4ed07"}
1
+ {"version":1,"artifact":"3cab7fa6940b63b4e0f7a149ac7d7ed835de9f617cbf9d4eee687f000aa38b7a"}
package/README.md CHANGED
@@ -52,7 +52,7 @@ insight-cli ghidra merge --session SESSION --target TARGET --json
52
52
  The search reads raw literal bytes, so it does not require defined Ghidra strings.
53
53
  Results include scan coverage and a continuation cursor when incomplete. New imports
54
54
  skip full automatic analysis by default; add `--analysis` to the first `open` to opt in.
55
- Another machine continues with `ghidra targets list` and `ghidra open --target TARGET --session new`.
55
+ Another machine continues with `hub targets list` and `ghidra open --target TARGET --session new`.
56
56
 
57
57
  ## Other tools
58
58
 
@@ -66,12 +66,12 @@ tool and locates its agent skill (for example `insight-cli skill insight-ilspy`)
66
66
 
67
67
  `insight-cli work` is an opt-in ledger for agents that reconstruct functions of one binary
68
68
  together: nonoverlapping leased slices, retained source and contracts, evidence, and review by
69
- a different worker. Every change takes a request ID, so a lost reply can be retried safely.
69
+ a different worker.
70
70
 
71
71
  ```sh
72
- insight-cli -p RE work create --project client --target TARGET --name Client --request-id create-client --json
73
- insight-cli -p RE work import --project client --file functions.json --request-id import-1 --json
74
- insight-cli -p RE work next --project client --worker agent-a --request-id agent-a-next-1 --json
72
+ insight-cli -p RE work create --plan client --target TARGET --name Client --json
73
+ insight-cli -p RE work import --plan client --file functions.json --json
74
+ insight-cli -p RE work next --plan client --worker agent-a --json
75
75
  ```
76
76
 
77
77
  `insight-cli work --help` has the commands.
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.9.2
6
+ # insight-cli 0.9.3
7
7
 
8
8
  Discover capabilities with `insight-cli tools list --json` and `insight-cli tools show <tool> --json`;
9
9
  each tool names its skill (`insight-cli skill <name>`). Update permission is required for tool preparation,
package/dist/src/cli.js CHANGED
@@ -228,14 +228,37 @@ function loaderInputs(o) {
228
228
  return Object.keys(l).length ? l : undefined;
229
229
  }
230
230
  const targetView = (target) => ({ target: target.id, name: target.name, binarySha256: target.binarySha256, size: target.size, createdAt: target.createdAt });
231
+ /** A comma-separated option as its non-empty trimmed items. */
232
+ const commaList = (value) => value === undefined ? [] : String(value).split(',').map(s => s.trim()).filter(Boolean);
233
+ /** `hub targets list|set|file` (#186): targets of this profile's hub project, or of --project. */
234
+ function targetCommands(owner) {
235
+ const core = (c) => owner.core(c), hubProject = { flags: '--project <name>', description: 'Hub project name or id (default: the profile hub project)' };
236
+ return [
237
+ command('list', 'List the project\'s targets with their version label and tags; --tags and --version-label select builds', async ({ options: o }, c) => {
238
+ // A target matches when it has every listed tag and, with --version, exactly that label (tags compare lower-case, labels as written).
239
+ const tags = commaList(o.tags).map(t => t.toLowerCase()), label = o.versionLabel === undefined ? undefined : String(o.versionLabel).trim();
240
+ return { items: (await core(c).targets(o.project === undefined ? undefined : String(o.project))).filter(t => tags.every(g => t.tags.includes(g)) && (label === undefined || t.versionLabel === label))
241
+ .map(t => ({ target: t.id, name: t.name, versionLabel: t.versionLabel, tags: t.tags, sha256: t.sha256, size: t.size, createdAt: t.createdAt, createdBy: t.createdBy })) };
242
+ }, { permission: Permission.ReadOnly, options: [hubProject, { flags: '--tags <tags>', description: 'Only targets with all these tags, comma separated' }, { flags: '--version-label <label>', description: 'Only targets with exactly this version label' }] }),
243
+ command('set', 'Set or clear a target\'s version label and add or remove tags (shared on the hub; the binary and its history are unchanged)', async ({ options: o }, c) => {
244
+ if (o.versionLabel !== undefined && o.clearVersionLabel)
245
+ fail('invalid', 'Use --version-label or --clear-version-label, not both.');
246
+ const change = { ...(o.clearVersionLabel ? { versionLabel: null } : o.versionLabel !== undefined ? { versionLabel: String(o.versionLabel) } : {}),
247
+ ...(o.addTags !== undefined ? { addTags: commaList(o.addTags) } : {}), ...(o.removeTags !== undefined ? { removeTags: commaList(o.removeTags) } : {}) };
248
+ const t = await core(c).updateTarget(id(o.target, '--target'), change, o.project === undefined ? undefined : String(o.project));
249
+ return { target: t.id, name: t.name, versionLabel: t.versionLabel, tags: t.tags };
250
+ }, { permission: Permission.Update, options: [{ flags: '--target <id>', description: 'Hub target', required: true }, hubProject,
251
+ { flags: '--version-label <label>', description: 'Version label of the binary\'s build (1-128 printable characters; case kept)' },
252
+ { flags: '--clear-version-label', description: 'Remove the version label' },
253
+ { flags: '--add-tags <tags>', description: 'Tags to add, comma separated (lower-cased; a-z 0-9 . _ - + :)' },
254
+ { flags: '--remove-tags <tags>', description: 'Tags to remove, comma separated' }] }),
255
+ command('file', 'Download the original input of a target into the local cache (hash verified)', async ({ options: o }, c) => ({ target: id(o.target, '--target'), path: await core(c).targetFile(id(o.target, '--target')) }), { permission: Permission.Update, options: [{ flags: '--target <id>', description: 'Hub target', required: true }] }),
256
+ ];
257
+ }
231
258
  /** Core context commands: open, publish, refresh, discard, close and collection on the hub. */
232
259
  function coreCommands(owner, options) {
233
260
  const core = (c) => owner.core(c);
234
261
  return [
235
- command('targets', 'Targets registered in this profile\'s hub project', [
236
- command('list', 'List the project\'s targets', async (_input, c) => ({ items: (await core(c).targets()).map(t => ({ target: t.id, name: t.name, sha256: t.sha256, size: t.size, createdAt: t.createdAt, createdBy: t.createdBy })) }), { permission: Permission.ReadOnly }),
237
- command('file', 'Download the original input of a target into the local cache (hash verified)', async ({ options: o }, c) => ({ target: id(o.target, '--target'), path: await core(c).targetFile(id(o.target, '--target')) }), { permission: Permission.Update, options: [{ flags: '--target <id>', description: 'Hub target', required: true }] }),
238
- ]),
239
262
  command('open [input]', 'Open a file or a hub target in a session; the first machine imports and publishes version 1', async ({ args, options: o }, c) => {
240
263
  if (Boolean(args.input) === Boolean(o.target))
241
264
  fail('invalid', 'Supply exactly one input path or --target.');
@@ -274,7 +297,7 @@ function coreCommands(owner, options) {
274
297
  command('discard', 'Drop local changes and check out the latest version again', ({ options: o }, c) => core(c).discard(scope(o)), { permission: 'Destructive', options: scoped }),
275
298
  ]),
276
299
  command('close', 'Stop the context worker; --release also ends the checkout and deletes the copy', ({ options: o }, c) => core(c).close(scope(o), { release: Boolean(o.release), force: Boolean(o.force) }), { permission: Permission.Update, options: [...scoped, { flags: '--release', description: 'End the checkout and delete the working copy' }, { flags: '--force', description: 'With --release, discard unpublished changes' }] }),
277
- command('gc', 'Release unmodified copies of closed contexts and cached binaries no open context uses', ({ options: o }, c) => core(c).gc({ dryRun: Boolean(o.dryRun) }), { permission: Permission.Update, options: [{ flags: '--dry-run', description: 'Report what would be removed' }] }),
300
+ command('gc', 'Release unmodified copies of closed contexts and of contexts idle for a day, and cached binaries no open context uses (open runs it hourly)', ({ options: o }, c) => core(c).gc({ dryRun: Boolean(o.dryRun) }), { permission: Permission.Update, options: [{ flags: '--dry-run', description: 'Report what would be removed' }] }),
278
301
  command('budgets', 'Inspect or configure native execution budgets', [
279
302
  command('show', 'Read effective per-request native budgets', (_invocation, c) => budgetsView(c.profile.name, c.profile.values), { permission: Permission.ReadOnly }),
280
303
  command('set', 'Configure subsequent native requests', async ({ options: o }, c) => {
@@ -417,7 +440,7 @@ export function createDefinition(options = {}) {
417
440
  return { session, contexts: contexts.map(r => ({ target: r.target, name: r.name, sha256: r.sha256, mode: r.mode, state: r.closedAt ? 'closed' : 'open', worker: r.worker })) };
418
441
  }, { permission: Permission.ReadOnly }),
419
442
  ]),
420
- hubCommands(),
443
+ hubCommands(targetCommands(owner)),
421
444
  command('ghidra', 'Shared Ghidra analysis: one working copy per session and target', ghidra),
422
445
  ],
423
446
  };
@@ -1,4 +1,4 @@
1
- import type { HubClient, HubTarget } from '../hub/contract.js';
1
+ import type { HubClient, HubTarget, HubTargetChange } from '../hub/contract.js';
2
2
  import type { LoaderInputs, NativeGhidra, NativeWorker } from '../native/contract.js';
3
3
  export interface Scope {
4
4
  session: string;
@@ -18,6 +18,8 @@ export interface CoordinatorOptions {
18
18
  project: string;
19
19
  /** Idle minutes after the last call before a context worker stops (default 15). */
20
20
  idleMinutes?: number;
21
+ /** `open` starts a background gc at most this often per profile, across owners (default 60; 0 never). */
22
+ gcIntervalMinutes?: number;
21
23
  }
22
24
  /** Minimal local context list: what was opened, nothing about operations. */
23
25
  interface ContextRecord {
@@ -32,6 +34,12 @@ interface ContextRecord {
32
34
  export declare function fileSha256(path: string): Promise<string>;
33
35
  /** A cached binary unused for this long and not used by an open context of this profile may be collected (other profiles share the cache). */
34
36
  export declare const BLOB_CACHE_GRACE_MS: number;
37
+ /**
38
+ * An open context without a running worker and not used for this long is collected like a closed one (#177). Its record's
39
+ * modification time is its last use: every command on the context sets it. Copies are created by opens, so `open` is
40
+ * where gc starts by itself.
41
+ */
42
+ export declare const CONTEXT_IDLE_MS: number;
35
43
  export declare class Coordinator {
36
44
  private readonly o;
37
45
  private readonly running;
@@ -41,6 +49,8 @@ export declare class Coordinator {
41
49
  private hubClient?;
42
50
  /** The hub project, looked up once; dropped with the client, or when the hub no longer knows it here. */
43
51
  private hubProject?;
52
+ /** The background gc started by `open`, while it runs. */
53
+ private collecting?;
44
54
  constructor(o: CoordinatorOptions);
45
55
  private key;
46
56
  private copy;
@@ -63,7 +73,12 @@ export declare class Coordinator {
63
73
  private context;
64
74
  /** The project on the hub without creating it (read-only commands never create projects or start Ghidra Server). */
65
75
  private existingProject;
66
- targets(): Promise<HubTarget[]>;
76
+ /** This profile's hub project, or the one named (by name or id), when it exists. */
77
+ private namedProject;
78
+ /** Targets of this profile's hub project, or of `project`; none when the project does not exist. */
79
+ targets(project?: string): Promise<HubTarget[]>;
80
+ /** Sets or clears a target's version label and adds or removes its tags on the hub (#182). */
81
+ updateTarget(targetId: string, change: HubTargetChange, project?: string): Promise<HubTarget>;
67
82
  /**
68
83
  * Opens a file or a registered target in a session. A new file is uploaded once and registered by its sha256;
69
84
  * the first machine to find the program absent imports and publishes version 1. Others only check out.
@@ -90,6 +105,13 @@ export declare class Coordinator {
90
105
  published: boolean;
91
106
  mode: ToolMode;
92
107
  }>;
108
+ /**
109
+ * Starts gc without waiting for it, when none runs here and the profile's last start (the stamp's modification time,
110
+ * so a new owner keeps the interval) is older than the interval. A failed run is left to the next one.
111
+ */
112
+ private collectInBackground;
113
+ /** Records a use of the context: its record's modification time is what idle collection reads. */
114
+ private used;
93
115
  /** The native layer alone (no hub): file-level helpers and installation facts. */
94
116
  nativeLayer(): Promise<NativeGhidra>;
95
117
  /** Runs one file-level native helper in the native host (no hub, no worker). */
@@ -100,6 +122,11 @@ export declare class Coordinator {
100
122
  localDirectory(...parts: string[]): string;
101
123
  /** A new scratch directory inside the working copy: the worker's bridge reads and writes files only below the copy root. */
102
124
  copyScratch(s: Scope): Promise<string>;
125
+ /**
126
+ * Marks a use of an open context in its order, for a command that works on the copy outside a worker: a gc releasing
127
+ * the copy finishes first (the command then finds no context), and after this use gc keeps the copy for a day.
128
+ */
129
+ use(s: Scope): Promise<void>;
103
130
  /** Root of a context's working copy (scripts and other context-local files). */
104
131
  copyRoot(s: Scope): string;
105
132
  /** Mode of an open context. */
@@ -269,13 +296,18 @@ export declare class Coordinator {
269
296
  contexts(session?: string): Promise<(ContextRecord & {
270
297
  worker: 'running' | 'stopped';
271
298
  })[]>;
299
+ /** Session and target of each context record on this machine, from file names alone. */
300
+ private scopes;
272
301
  /** The original input of a target, downloaded from the hub into the installation cache. */
273
302
  targetFile(targetId: string): Promise<string>;
274
303
  private download;
275
304
  /**
276
- * Releases unmodified copies of closed contexts, and cached binaries that no open context of this profile uses and that
277
- * were not used for BLOB_CACHE_GRACE_MS (the cache is shared by every profile of the installation; a removed binary is
278
- * downloaded again when needed). Files in use are skipped and reported.
305
+ * Releases unmodified copies of closed contexts and of open contexts without a running worker that were not used for
306
+ * CONTEXT_IDLE_MS (a copy holding unpublished changes, context scripts or other local project files is kept), and cached binaries that
307
+ * no open context of this profile uses and that were not used for BLOB_CACHE_GRACE_MS (the cache is shared by every
308
+ * profile of the installation; a removed binary is downloaded again when needed). Files in use are skipped and
309
+ * reported; a copy that cannot be released is reported and the others are still collected. The server is contacted
310
+ * only when a copy is to be released.
279
311
  */
280
312
  gc(options?: {
281
313
  dryRun?: boolean;
@@ -28,6 +28,12 @@ export async function fileSha256(path) {
28
28
  const newSession = () => 's_' + randomBytes(6).toString('hex');
29
29
  /** A cached binary unused for this long and not used by an open context of this profile may be collected (other profiles share the cache). */
30
30
  export const BLOB_CACHE_GRACE_MS = 24 * 3_600_000;
31
+ /**
32
+ * An open context without a running worker and not used for this long is collected like a closed one (#177). Its record's
33
+ * modification time is its last use: every command on the context sets it. Copies are created by opens, so `open` is
34
+ * where gc starts by itself.
35
+ */
36
+ export const CONTEXT_IDLE_MS = 24 * 3_600_000;
31
37
  const isUnavailable = (error) => error instanceof CliError && error.code === 'hub.unavailable';
32
38
  const hubCode = (error) => { const code = error?.code; return typeof code === 'string' ? code.replace(/_([a-z])/g, (_, c) => c.toUpperCase()) : undefined; };
33
39
  export class Coordinator {
@@ -39,6 +45,8 @@ export class Coordinator {
39
45
  hubClient;
40
46
  /** The hub project, looked up once; dropped with the client, or when the hub no longer knows it here. */
41
47
  hubProject;
48
+ /** The background gc started by `open`, while it runs. */
49
+ collecting;
42
50
  constructor(o) {
43
51
  this.o = o;
44
52
  this.paths = localPaths(o.analysis, o.cacheBase);
@@ -138,14 +146,29 @@ export class Coordinator {
138
146
  failure('coordinator.notFound', 'No context for this session and target; run `ghidra open --session <id> --target <id>`.', { ...s });
139
147
  if (record.closedAt)
140
148
  failure('coordinator.closed', 'This context is closed; reopen it with `ghidra open --session ' + s.session + ' --target ' + s.target + '`.', { ...s });
149
+ await this.used(s);
141
150
  return record;
142
151
  }
143
152
  /** The project on the hub without creating it (read-only commands never create projects or start Ghidra Server). */
144
153
  async existingProject(hub) {
145
154
  return this.hubProject ??= (await hub.projects()).find(p => p.name === this.o.project);
146
155
  }
147
- async targets() {
148
- return this.withHub(async (hub) => { const project = await this.existingProject(hub); return project ? await hub.targets(project.id) : []; });
156
+ /** This profile's hub project, or the one named (by name or id), when it exists. */
157
+ async namedProject(hub, name) {
158
+ return name === undefined ? this.existingProject(hub) : (await hub.projects()).find(p => p.name === name || p.id === name);
159
+ }
160
+ /** Targets of this profile's hub project, or of `project`; none when the project does not exist. */
161
+ async targets(project) {
162
+ return this.withHub(async (hub) => { const p = await this.namedProject(hub, project); return p ? await hub.targets(p.id) : []; });
163
+ }
164
+ /** Sets or clears a target's version label and adds or removes its tags on the hub (#182). */
165
+ async updateTarget(targetId, change, project) {
166
+ return this.withHub(async (hub) => {
167
+ const p = await this.namedProject(hub, project);
168
+ if (!p)
169
+ failure('hub.notFound', 'Hub project ' + (project ?? this.o.project) + ' does not exist yet.');
170
+ return hub.updateTarget(p.id, targetId, change);
171
+ });
149
172
  }
150
173
  /**
151
174
  * Opens a file or a registered target in a session. A new file is uploaded once and registered by its sha256;
@@ -176,7 +199,7 @@ export class Coordinator {
176
199
  ...(input.timeoutSeconds ? { timeoutSeconds: input.timeoutSeconds } : {}), ...(input.loader ? { loader: input.loader } : {}) })).state === 'published';
177
200
  }
178
201
  const session = input.session === 'new' ? newSession() : input.session, s = { session, target: target.id };
179
- return await this.ordered(s, async () => {
202
+ const opened = await this.ordered(s, async () => {
180
203
  const previous = await this.record(s), mode = input.mode ?? previous?.mode ?? 'headless', key = this.key(s), current = this.running.get(key);
181
204
  if (current && current.mode !== mode)
182
205
  await this.stopWorker(s);
@@ -189,11 +212,33 @@ export class Coordinator {
189
212
  await this.startWorker(s, native, mode);
190
213
  return { session, target: target.id, name: target.name, sha256: target.sha256, uploaded, registered, published, mode, ...this.view(status) };
191
214
  });
215
+ this.collectInBackground();
216
+ return opened;
192
217
  }
193
218
  catch (error) {
194
219
  throw this.surface(error);
195
220
  }
196
221
  }
222
+ /**
223
+ * Starts gc without waiting for it, when none runs here and the profile's last start (the stamp's modification time,
224
+ * so a new owner keeps the interval) is older than the interval. A failed run is left to the next one.
225
+ */
226
+ collectInBackground() {
227
+ const minutes = this.o.gcIntervalMinutes ?? 60;
228
+ if (!minutes || this.collecting)
229
+ return;
230
+ const stamp = join(this.o.analysis, 'contexts.gc');
231
+ this.collecting = (async () => {
232
+ const last = await stat(stamp).then(st => st.mtimeMs, () => 0);
233
+ if (Date.now() - last < minutes * 60_000)
234
+ return;
235
+ await mkdir(this.o.analysis, { recursive: true });
236
+ await writeFile(stamp, '');
237
+ await this.gc();
238
+ })().catch(() => { }).finally(() => { this.collecting = undefined; });
239
+ }
240
+ /** Records a use of the context: its record's modification time is what idle collection reads. */
241
+ async used(s) { const now = new Date(); await utimes(this.recordPath(s), now, now); }
197
242
  /** The native layer alone (no hub): file-level helpers and installation facts. */
198
243
  async nativeLayer() { try {
199
244
  return (await this.o.native()).native;
@@ -219,6 +264,11 @@ export class Coordinator {
219
264
  localDirectory(...parts) { return join(this.o.analysis, ...parts); }
220
265
  /** A new scratch directory inside the working copy: the worker's bridge reads and writes files only below the copy root. */
221
266
  async copyScratch(s) { const parent = join(this.copy(s).root, 'tmp'); await mkdir(parent, { recursive: true }); return mkdtemp(join(parent, 'x-')); }
267
+ /**
268
+ * Marks a use of an open context in its order, for a command that works on the copy outside a worker: a gc releasing
269
+ * the copy finishes first (the command then finds no context), and after this use gc keeps the copy for a day.
270
+ */
271
+ async use(s) { await this.ordered(s, () => this.context(s)); }
222
272
  /** Root of a context's working copy (scripts and other context-local files). */
223
273
  copyRoot(s) { return this.copy(s).root; }
224
274
  /** Mode of an open context. */
@@ -255,7 +305,7 @@ export class Coordinator {
255
305
  /** Writes the version the working copy is based on (or `version`) from the repository as a GZF at `output`. Needs the hub. */
256
306
  async exportBase(s, output, version) {
257
307
  try {
258
- await this.context(s);
308
+ await this.use(s);
259
309
  const { native, ref } = await this.repository();
260
310
  if (!native.exportVersion)
261
311
  failure('coordinator.unsupported', 'This native layer cannot export repository versions.');
@@ -459,8 +509,9 @@ export class Coordinator {
459
509
  released = await native.release(ref, copy, Boolean(options.force));
460
510
  }
461
511
  catch (error) {
512
+ // Ghidra's unpublished changes, or files only the copy holds (context scripts, other programs); the message names them.
462
513
  if (error.code === 'native.modified')
463
- failure('coordinator.modified', 'The working copy has unpublished changes; merge them, discard them, or close with --force.', { ...s, state: 'modified' });
514
+ failure('coordinator.modified', error.message + '. Merge or discard changes, move local files, or close with --force.', { ...s, state: 'modified' });
464
515
  throw error;
465
516
  }
466
517
  await rm(this.recordPath(s), { force: true });
@@ -472,6 +523,7 @@ export class Coordinator {
472
523
  const record = await this.record(s);
473
524
  if (!record)
474
525
  failure('coordinator.notFound', 'No context for this session and target.', { ...s });
526
+ await this.used(s);
475
527
  const base = { ...s, name: record.name, sha256: record.sha256, mode: record.mode, state: record.closedAt ? 'closed' : 'open', worker: this.running.has(this.key(s)) ? 'running' : 'stopped' };
476
528
  // Read-only: the checkout is compared with a Ghidra Server that already runs; nothing is created or started.
477
529
  let server;
@@ -492,17 +544,24 @@ export class Coordinator {
492
544
  }
493
545
  /** Contexts on this machine, from the working copy records. */
494
546
  async contexts(session) {
547
+ const result = [];
548
+ for (const s of await this.scopes(session)) {
549
+ const record = await this.record(s);
550
+ if (record)
551
+ result.push({ ...record, worker: this.running.has(this.key(record)) ? 'running' : 'stopped' });
552
+ }
553
+ return result;
554
+ }
555
+ /** Session and target of each context record on this machine, from file names alone. */
556
+ async scopes(session) {
495
557
  const sessions = session ? [session] : await readdir(this.paths.contexts).catch(error => { if (error.code === 'ENOENT')
496
558
  return []; throw error; });
497
559
  const result = [];
498
560
  for (const name of sessions.sort()) {
499
561
  const files = await readdir(join(this.paths.contexts, name)).catch(error => { if (error.code === 'ENOENT' || error.code === 'ENOTDIR')
500
562
  return []; throw error; });
501
- for (const file of files.filter(f => f.endsWith('.json')).sort()) {
502
- const record = await this.record({ session: name, target: file.slice(0, -5) });
503
- if (record)
504
- result.push({ ...record, worker: this.running.has(this.key(record)) ? 'running' : 'stopped' });
505
- }
563
+ for (const file of files.filter(f => f.endsWith('.json')).sort())
564
+ result.push({ session: name, target: file.slice(0, -5) });
506
565
  }
507
566
  return result;
508
567
  }
@@ -528,42 +587,43 @@ export class Coordinator {
528
587
  return path;
529
588
  }
530
589
  /**
531
- * Releases unmodified copies of closed contexts, and cached binaries that no open context of this profile uses and that
532
- * were not used for BLOB_CACHE_GRACE_MS (the cache is shared by every profile of the installation; a removed binary is
533
- * downloaded again when needed). Files in use are skipped and reported.
590
+ * Releases unmodified copies of closed contexts and of open contexts without a running worker that were not used for
591
+ * CONTEXT_IDLE_MS (a copy holding unpublished changes, context scripts or other local project files is kept), and cached binaries that
592
+ * no open context of this profile uses and that were not used for BLOB_CACHE_GRACE_MS (the cache is shared by every
593
+ * profile of the installation; a removed binary is downloaded again when needed). Files in use are skipped and
594
+ * reported; a copy that cannot be released is reported and the others are still collected. The server is contacted
595
+ * only when a copy is to be released.
534
596
  */
535
597
  async gc(options = {}) {
536
- const records = await this.contexts(), released = [], retained = [], removedBlobs = [], skippedBlobs = [];
537
- const closed = records.filter(r => r.closedAt);
538
- if (closed.length) {
539
- const { native, ref } = await this.repository();
540
- for (const r of closed) {
541
- const s = { session: r.session, target: r.target };
542
- await this.ordered(s, async () => {
543
- if (options.dryRun) {
544
- if ((await native.status(ref, this.copy(s))).modified)
545
- retained.push({ ...s, reason: 'modified' });
546
- else
547
- released.push(s);
548
- return;
549
- }
550
- // Ghidra refuses to release a modified copy: that copy is kept.
551
- try {
552
- await native.release(ref, this.copy(s), false);
553
- }
554
- catch (error) {
555
- if (error.code === 'native.modified') {
556
- retained.push({ ...s, reason: 'modified' });
557
- return;
558
- }
559
- throw error;
560
- }
598
+ const released = [], retained = [], removedBlobs = [], skippedBlobs = [];
599
+ const now = options.now ?? Date.now();
600
+ let server;
601
+ for (const s of await this.scopes()) {
602
+ await this.ordered(s, async () => {
603
+ // Decided in the context's order: an open or a call queued before this step keeps the context.
604
+ const record = await this.record(s);
605
+ if (!record || this.running.has(this.key(s)))
606
+ return;
607
+ if (!record.closedAt && now - (await stat(this.recordPath(s))).mtimeMs < CONTEXT_IDLE_MS)
608
+ return;
609
+ const { native, ref } = await (server ??= this.repository());
610
+ // A copy with unpublished changes, context scripts or other local project files is refused and kept; a preview
611
+ // asks the same release without changing anything.
612
+ try {
613
+ await native.release(ref, this.copy(s), false, options.dryRun);
614
+ }
615
+ catch (error) {
616
+ retained.push({ ...s, reason: error.code === 'native.modified' ? 'modified' : error instanceof Error ? error.message : String(error) });
617
+ return;
618
+ }
619
+ if (!options.dryRun)
561
620
  await rm(this.recordPath(s), { force: true });
562
- released.push(s);
563
- });
564
- }
621
+ released.push(s);
622
+ }).catch(error => { retained.push({ ...s, reason: error instanceof Error ? error.message : String(error) }); });
565
623
  }
566
- const used = new Set(records.filter(r => !r.closedAt).map(r => r.sha256)), cache = dirname(dirname(this.paths.blobCache('00'))), now = options.now ?? Date.now();
624
+ // Contexts as they are now (a context opened again after its release counts); a preview leaves out those it would release.
625
+ const gone = new Set(options.dryRun ? released.map(s => this.key(s)) : []);
626
+ const used = new Set((await this.contexts()).filter(r => !r.closedAt && !gone.has(this.key(r))).map(r => r.sha256)), cache = dirname(dirname(this.paths.blobCache('00')));
567
627
  for (const prefix of (await readdir(cache).catch(() => [])).filter(p => /^[a-f0-9]{2}$/.test(p)))
568
628
  // Only finished entries: `.download-*` temporaries belong to a download in progress.
569
629
  for (const blob of (await readdir(join(cache, prefix)).catch(() => [])).filter(b => /^[a-f0-9]{64}$/.test(b) && b.startsWith(prefix))) {
@@ -586,6 +646,7 @@ export class Coordinator {
586
646
  }
587
647
  /** Stops every worker of this owner (IPC owner shutdown or profile change). Working copies stay. */
588
648
  async dispose() {
649
+ await this.collecting;
589
650
  await Promise.allSettled([...this.running.keys()].map(key => { const [session, target] = key.split('/'); return this.ordered({ session, target }, () => this.stopWorker({ session, target })); }));
590
651
  }
591
652
  }
@@ -87,7 +87,7 @@ async function plan(o, temp) {
87
87
  invalid(`Old target ${String(t.id)} is malformed.`);
88
88
  if (!await exists(file))
89
89
  invalid(`Input of target ${String(t.id)} is missing: ${file}.`);
90
- targets.push({ id: String(t.id), projectId: id, sha256, name: String(t.name), size: (await stat(file)).size, createdAt: String(t.createdAt ?? new Date().toISOString()), createdBy: user });
90
+ targets.push({ id: String(t.id), projectId: id, sha256, name: String(t.name), size: (await stat(file)).size, createdAt: String(t.createdAt ?? new Date().toISOString()), createdBy: user, versionLabel: null, tags: [] });
91
91
  inputs.set(sha256, file);
92
92
  }
93
93
  const items = await scanRepository(source), copies = [], skipped = [];
@@ -147,7 +147,7 @@ export async function importLegacyProfile(o) {
147
147
  await copyFile(file, join(bundleDir, 'blobs', sha256));
148
148
  }
149
149
  const bundle = { schema: 1, format: 'insight-hub-project', createdAt: new Date().toISOString(), source: { legacyProfile: o.profile }, runtimeFingerprint: o.runtimeFingerprint ?? null,
150
- project: { id: p.id, name: o.profile, repository: p.repository, createdAt: new Date().toISOString() }, targets: p.targets, programs,
150
+ project: { id: p.id, name: o.profile, repository: p.repository, createdAt: new Date().toISOString(), description: null, tags: [] }, targets: p.targets, programs,
151
151
  blobs: [...p.inputs.keys()].map(sha256 => ({ sha256 })), extensions: [] };
152
152
  await writeFile(join(bundleDir, BUNDLE_FILE), JSON.stringify(bundle, null, 1));
153
153
  await hub.admin('import', { input: bundleDir });
@@ -97,5 +97,20 @@ export declare function collectGarbage(hub: Hub, body: Record<string, unknown>,
97
97
  reason: string;
98
98
  }[];
99
99
  }>;
100
+ /** Projects with their state, metadata and how many targets and plans they hold (#186); `project` selects one. */
101
+ export declare function listProjects(hub: Hub, body: Record<string, unknown>): {
102
+ items: {
103
+ project: string;
104
+ id: string;
105
+ state: "active" | "frozen" | "moved";
106
+ movedTo: string | null;
107
+ description: string | null;
108
+ tags: string[];
109
+ targets: number;
110
+ plans: number;
111
+ repository: string;
112
+ createdAt: string;
113
+ }[];
114
+ };
100
115
  /** Admin routes: POST /admin/<operation>. Paths in a body are paths on the hub machine, so those need a local caller. */
101
116
  export declare function adminRoute(hub: Hub, operation: string, body: Record<string, unknown>, local: boolean): Promise<unknown>;
@@ -100,7 +100,7 @@ export async function exportProject(hub, body) {
100
100
  extensions.push(e.prefix);
101
101
  }
102
102
  const bundle = { schema: 1, format: 'insight-hub-project', createdAt: new Date().toISOString(), source: { hubId: hub.store.hubId, address: `${hub.o.listen}:${hub.o.port}` },
103
- runtimeFingerprint: hub.ghidra.runtime?.fingerprint ?? null, project: { id: p.id, name: p.name, repository: p.repository, createdAt: p.createdAt }, targets, programs,
103
+ runtimeFingerprint: hub.ghidra.runtime?.fingerprint ?? null, project: { id: p.id, name: p.name, repository: p.repository, createdAt: p.createdAt, description: p.description, tags: p.tags }, targets, programs,
104
104
  blobs: [...blobs].map(sha256 => ({ sha256 })), extensions };
105
105
  await writeFile(join(stage, BUNDLE_FILE), JSON.stringify(bundle, null, 1));
106
106
  await rm(output, { recursive: true, force: true });
@@ -289,6 +289,14 @@ export async function collectGarbage(hub, body, now = Date.now()) {
289
289
  }
290
290
  return { dryRun, items, versions, blobs: blobs.map(b => ({ sha256: b.sha256, size: b.size })), skipped };
291
291
  }
292
+ /** Projects with their state, metadata and how many targets and plans they hold (#186); `project` selects one. */
293
+ export function listProjects(hub, body) {
294
+ const projects = body.project ? [projectRef(hub, body.project)] : hub.store.projects().map(p => ({ ...p, ...hub.store.projectState(p.id) }));
295
+ const count = (sql) => new Map(hub.store.db.prepare(sql).all().map(r => [String(r.id), Number(r.n)]));
296
+ const targets = count('SELECT project_id AS id,count(*) AS n FROM targets GROUP BY project_id'), plans = count('SELECT scope AS id,count(*) AS n FROM ledger_projects GROUP BY scope');
297
+ return { items: projects.map(p => ({ project: p.name, id: p.id, state: p.state, movedTo: p.movedTo, description: p.description, tags: p.tags,
298
+ targets: targets.get(p.id) ?? 0, plans: plans.get(p.id) ?? 0, repository: p.repository, createdAt: p.createdAt })) };
299
+ }
292
300
  /** Admin routes: POST /admin/<operation>. Paths in a body are paths on the hub machine, so those need a local caller. */
293
301
  export async function adminRoute(hub, operation, body, local) {
294
302
  const needsLocal = (o) => { if (!local)
@@ -304,6 +312,7 @@ export async function adminRoute(hub, operation, body, local) {
304
312
  case 'purge': return purgeProject(hub, body);
305
313
  case 'remove-target': return removeTarget(hub, body);
306
314
  case 'checkouts': return listCheckouts(hub, body);
315
+ case 'projects': return listProjects(hub, body);
307
316
  case 'release': return releaseCheckout(hub, body);
308
317
  case 'gc': return collectGarbage(hub, body);
309
318
  case 'runtime':
@@ -1,6 +1,6 @@
1
1
  import type { CommandContext } from '@eyeauras/cli-factory';
2
2
  import { type HubSettings } from '../core/layout.js';
3
- import type { GhidraEndpoint, HubClient, HubProject, HubStatus, HubTarget } from './contract.js';
3
+ import type { GhidraEndpoint, HubClient, HubProject, HubStatus, HubProjectChange, HubTarget, HubTargetChange } from './contract.js';
4
4
  import { type Autostart } from './autostart.js';
5
5
  import type { HubRuntime } from './ghidra.js';
6
6
  /** A value, or a function that computes it when it is first needed. */
@@ -47,6 +47,8 @@ export declare class HttpHubClient implements HubClient {
47
47
  target: HubTarget;
48
48
  created: boolean;
49
49
  }>;
50
+ updateProject(projectId: string, change: HubProjectChange): Promise<HubProject>;
51
+ updateTarget(projectId: string, targetId: string, change: HubTargetChange): Promise<HubTarget>;
50
52
  hasBlob(sha256: string): Promise<boolean>;
51
53
  shutdown(): Promise<void>;
52
54
  /** Hub administration (admin.ts): export, import, state, purge, remove-target, checkouts, release, gc. */
@@ -101,6 +101,10 @@ export class HttpHubClient {
101
101
  registerTarget(projectId, input) {
102
102
  return this.json('POST', `/projects/${encodeURIComponent(projectId)}/targets`, { ...input, createdBy: this.client });
103
103
  }
104
+ updateProject(projectId, change) { return this.json('PATCH', `/projects/${encodeURIComponent(projectId)}`, change); }
105
+ updateTarget(projectId, targetId, change) {
106
+ return this.json('PATCH', `/projects/${encodeURIComponent(projectId)}/targets/${encodeURIComponent(targetId)}`, change);
107
+ }
104
108
  async hasBlob(sha256) { return (await this.request('HEAD', '/blobs/' + sha256, { missing: true })).status === 200; }
105
109
  async shutdown() { await this.json('POST', '/shutdown'); }
106
110
  /** Hub administration (admin.ts): export, import, state, purge, remove-target, checkouts, release, gc. */
@@ -10,4 +10,5 @@ export declare function runHubProcess(o: Record<string, unknown>, signal?: Abort
10
10
  hubId: string;
11
11
  dataRoot: string;
12
12
  }>;
13
- export declare function hubCommands(): CommandDefinition;
13
+ /** `targetCommands`: list, set and file of the targets, served by the profile coordinator. */
14
+ export declare function hubCommands(targetCommands?: CommandDefinition[]): CommandDefinition;