@eyeauras/insight-cli 0.9.1 → 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 (81) hide show
  1. package/.cli-package-build.json +1 -1
  2. package/README.md +10 -6
  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/native-merge-patches.js +10 -0
  25. package/dist/src/research.js +2 -0
  26. package/dist/src/work/client.d.ts +6 -3
  27. package/dist/src/work/client.js +12 -9
  28. package/dist/src/work/commands.js +42 -28
  29. package/dist/src/work/model.d.ts +2 -0
  30. package/package.json +1 -1
  31. package/references/native/InsightWcOps.java +48 -9
  32. package/skill-bundle/insight-artifacts/SKILL.md +1 -1
  33. package/skill-bundle/insight-binary/SKILL.md +1 -1
  34. package/skill-bundle/insight-capture/SKILL.md +1 -1
  35. package/skill-bundle/insight-cli/SKILL.md +1 -1
  36. package/skill-bundle/insight-die/SKILL.md +1 -1
  37. package/skill-bundle/insight-dnspy/SKILL.md +1 -1
  38. package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
  39. package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
  40. package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
  41. package/skill-bundle/insight-frida/SKILL.md +1 -1
  42. package/skill-bundle/insight-ghidra/SKILL.md +6 -4
  43. package/skill-bundle/insight-ilspy/SKILL.md +1 -1
  44. package/skill-bundle/insight-interop/SKILL.md +1 -1
  45. package/skill-bundle/insight-lldb/SKILL.md +1 -1
  46. package/skill-bundle/insight-llvm/SKILL.md +1 -1
  47. package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
  48. package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
  49. package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
  50. package/skill-bundle/insight-overview/SKILL.md +1 -1
  51. package/skill-bundle/insight-procmon/SKILL.md +1 -1
  52. package/skill-bundle/insight-re/SKILL.md +1 -1
  53. package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
  54. package/skill-bundle/insight-strace/SKILL.md +1 -1
  55. package/skill-bundle/insight-tshark/SKILL.md +1 -1
  56. package/skill-bundle/insight-windbg/SKILL.md +1 -1
  57. package/skill-bundle/manifest.json +1 -1
  58. package/skills/insight-artifacts/SKILL.md +1 -1
  59. package/skills/insight-binary/SKILL.md +1 -1
  60. package/skills/insight-capture/SKILL.md +1 -1
  61. package/skills/insight-die/SKILL.md +1 -1
  62. package/skills/insight-dnspy/SKILL.md +1 -1
  63. package/skills/insight-dotnet-dump/SKILL.md +1 -1
  64. package/skills/insight-dotnet-stack/SKILL.md +1 -1
  65. package/skills/insight-dotnet-trace/SKILL.md +1 -1
  66. package/skills/insight-frida/SKILL.md +1 -1
  67. package/skills/insight-ghidra/SKILL.md +6 -4
  68. package/skills/insight-ilspy/SKILL.md +1 -1
  69. package/skills/insight-interop/SKILL.md +1 -1
  70. package/skills/insight-lldb/SKILL.md +1 -1
  71. package/skills/insight-llvm/SKILL.md +1 -1
  72. package/skills/insight-managed-heap/SKILL.md +1 -1
  73. package/skills/insight-managed-metadata/SKILL.md +1 -1
  74. package/skills/insight-mitmproxy/SKILL.md +1 -1
  75. package/skills/insight-overview/SKILL.md +1 -1
  76. package/skills/insight-procmon/SKILL.md +1 -1
  77. package/skills/insight-re/SKILL.md +1 -1
  78. package/skills/insight-sevenzip/SKILL.md +1 -1
  79. package/skills/insight-strace/SKILL.md +1 -1
  80. package/skills/insight-tshark/SKILL.md +1 -1
  81. package/skills/insight-windbg/SKILL.md +1 -1
@@ -12,6 +12,7 @@ import { autostartName, platformAutostart } from './autostart.js';
12
12
  import { HttpHubClient, compareVersions, connect, hubDataRoot, hubLogPath, profileRuntime, runtimeArguments } from './client.js';
13
13
  import { acquireHubLock, lockPid } from './lock.js';
14
14
  import { Hub } from './server.js';
15
+ import { hubProjectName } from '../work/client.js';
15
16
  import { hubUrl, invalid, listenAddress, localHubUrl, minutes, port, readHubSettings, remoteAddress, restartFields, writeHubSettings } from './settings.js';
16
17
  const delay = (ms) => new Promise(r => setTimeout(r, ms));
17
18
  const roaming = (c) => c.appArguments.RoamingAppDataDirectory;
@@ -215,8 +216,33 @@ async function storageMove(c, o) {
215
216
  const removed = o.keepSource ? { deleted: false } : await removeDataRoot(from);
216
217
  return { moved: true, from, to, ...copied, restarted, sourceDeleted: removed.deleted, ...(removed.reason ? { sourceKept: removed.reason } : {}) };
217
218
  }
219
+ const tagList = (value) => value === undefined ? [] : String(value).split(',').map(t => t.trim()).filter(Boolean);
220
+ /** Hub projects (#186): what is researched, one Ghidra repository each. --project defaults to the profile hub project. */
221
+ function projectCommands() {
222
+ const project = { flags: '--project <name>', description: 'Hub project name or id (default: the profile hub project)' };
223
+ const named = (c, o) => typeof o.project === 'string' && o.project ? o.project : hubProjectName(c);
224
+ return command('projects', 'Hub projects: what is researched; each is one Ghidra repository with its targets and plans', [
225
+ command('list', 'List projects with state, description, tags and their numbers of targets and plans; --tags selects', async ({ options }, c) => {
226
+ const tags = tagList(options.tags).map(t => t.toLowerCase()), { items } = await (await adminHub(c)).admin('projects', {});
227
+ return { items: items.filter(p => tags.every(t => p.tags.includes(t))) };
228
+ }, { permission: Permission.ReadOnly, options: [{ flags: '--tags <tags>', description: 'Only projects with all these tags, comma separated' }] }),
229
+ command('show', 'One project: state, description, tags, repository and its numbers of targets and plans', async ({ options }, c) => (await (await adminHub(c)).admin('projects', { project: named(c, options) })).items[0], { permission: Permission.ReadOnly, options: [project] }),
230
+ command('set', 'Set or clear a project description and add or remove its tags (shared on the hub)', async ({ options }, c) => {
231
+ if (options.description !== undefined && options.clearDescription)
232
+ invalid('Use --description or --clear-description, not both.');
233
+ const hub = await adminHub(c), name = named(c, options), found = (await hub.projects()).find(p => p.name === name || p.id === name);
234
+ if (!found)
235
+ invalid('Project ' + name + ' does not exist on this hub.');
236
+ return hub.updateProject(found.id, { ...(options.clearDescription ? { description: null } : options.description !== undefined ? { description: String(options.description) } : {}),
237
+ ...(options.addTags !== undefined ? { addTags: tagList(options.addTags) } : {}), ...(options.removeTags !== undefined ? { removeTags: tagList(options.removeTags) } : {}) });
238
+ }, { permission: Permission.Update, options: [project, { flags: '--description <text>', description: 'What the project researches (1-1000 characters)' },
239
+ { flags: '--clear-description', description: 'Remove the description' },
240
+ { flags: '--add-tags <tags>', description: 'Tags to add, comma separated (lower-cased; a-z 0-9 . _ - + :)' },
241
+ { flags: '--remove-tags <tags>', description: 'Tags to remove, comma separated' }] })
242
+ ]);
243
+ }
218
244
  /** Commands of moving projects, legacy import, storage, GC and checkouts. */
219
- function transferCommands() {
245
+ function transferCommands(targetCommands) {
220
246
  const project = { flags: '--project <name>', description: 'Project name (or id) on the hub' };
221
247
  return [
222
248
  command('export', 'Freeze a project and write it with its targets, binaries and extension data to a bundle directory', async ({ options }, c) => (await adminHub(c, { local: true })).admin('export', { project: required(options, 'project', '--project'), output: resolve(c.cwd, required(options, 'output', '--output')) }), { permission: Permission.Update, options: [project, { flags: '--output <dir>', description: 'Bundle directory to create' }] }),
@@ -230,7 +256,8 @@ function transferCommands() {
230
256
  command('move', 'Stop the hub, copy its data root, switch the setting, restart, then delete the source', ({ options }, c) => storageMove(c, options), { permission: Permission.Update, options: [{ flags: '--to <dir>', description: 'New hub data root (absent or empty)' }, { flags: '--keep-source', description: 'Keep the old data root' }] })
231
257
  ]),
232
258
  command('gc', 'Delete Ghidra programs of removed targets and unreferenced binaries; old versions only with --versions', async ({ options }, c) => (await adminHub(c)).admin('gc', { dryRun: Boolean(options.dryRun), ...(options.versions === undefined ? {} : { versions: Number(options.versions) }) }), { permission: Permission.Update, options: [{ flags: '--dry-run', description: 'Report what would be deleted' }, { flags: '--versions <keep>', description: 'Keep only the newest <keep> versions of each program' }] }),
233
- command('targets', 'Targets of hub projects', [
259
+ command('targets', 'Targets (binary builds) of hub projects: list, version labels and tags, files, removal', [
260
+ ...targetCommands,
234
261
  command('remove', 'Remove a target registration; hub gc then deletes its program and binary', async ({ options }, c) => (await adminHub(c)).admin('remove-target', { project: required(options, 'project', '--project'), target: required(options, 'target', '--target') }), { permission: Permission.Update, options: [project, { flags: '--target <id>', description: 'Target id' }] })
235
262
  ]),
236
263
  command('checkouts', 'Ghidra checkouts held on the hub', [
@@ -239,7 +266,8 @@ function transferCommands() {
239
266
  ])
240
267
  ];
241
268
  }
242
- export function hubCommands() {
269
+ /** `targetCommands`: list, set and file of the targets, served by the profile coordinator. */
270
+ export function hubCommands(targetCommands = []) {
243
271
  return command('hub', 'Shared hub of projects, targets, binaries and Ghidra Server', [
244
272
  localCommand('run', 'Run the hub in this process (started on demand or by the OS registration)', ({ options }) => runHubProcess(options), { options: [
245
273
  { flags: '--data-root <dir>', description: 'Hub data root (default: configured)' },
@@ -275,6 +303,7 @@ export function hubCommands() {
275
303
  command('uninstall', 'Remove the OS registration', (_i, c) => service(c, 'uninstall'), { permission: Permission.Update }),
276
304
  command('status', 'Read the registration from the OS', (_i, c) => service(c, 'status'), { permission: Permission.ReadOnly })
277
305
  ]),
278
- ...transferCommands()
306
+ projectCommands(),
307
+ ...transferCommands(targetCommands)
279
308
  ]);
280
309
  }
@@ -20,6 +20,16 @@ export interface HubProject {
20
20
  name: string;
21
21
  repository: string;
22
22
  createdAt: string;
23
+ /** What the project researches; null when unset. */
24
+ description: string | null;
25
+ /** Shared tags, lower-case and sorted (target tag rules). */
26
+ tags: string[];
27
+ }
28
+ /** A metadata edit of a project: description set or cleared (empty or null), tags added or removed one by one. */
29
+ export interface HubProjectChange {
30
+ description?: string | null;
31
+ addTags?: string[];
32
+ removeTags?: string[];
23
33
  }
24
34
  export interface HubTarget {
25
35
  id: string;
@@ -30,6 +40,19 @@ export interface HubTarget {
30
40
  createdAt: string;
31
41
  /** Client user name (`user.machine`) that registered it. */
32
42
  createdBy: string;
43
+ /** Human-readable product/build version of the binary (not a Ghidra version); null when unset. */
44
+ versionLabel: string | null;
45
+ /** Shared tags, lower-case and sorted; empty when none. */
46
+ tags: string[];
47
+ }
48
+ /**
49
+ * A metadata edit of a target. `versionLabel` sets it (trimmed; empty or null clears it, last write wins); tags are
50
+ * trimmed and lower-cased, and each is added or removed on its own, so edits of different tags by several clients all apply.
51
+ */
52
+ export interface HubTargetChange {
53
+ versionLabel?: string | null;
54
+ addTags?: string[];
55
+ removeTags?: string[];
33
56
  }
34
57
  /** Where a client connects to Ghidra Server. Returned by POST /ghidra/ensure after the server is running. */
35
58
  export interface GhidraEndpoint {
@@ -44,11 +67,13 @@ export interface GhidraEndpoint {
44
67
  * POST /ghidra/ensure {runtimeFingerprint,java?,ghidraHome?} -> GhidraEndpoint (starts Ghidra Server if needed; 409 on fingerprint mismatch)
45
68
  * GET /projects -> HubProject[]
46
69
  * POST /projects {name} -> HubProject (idempotent by name; repository 'insight_<id hex>')
70
+ * PATCH /projects/:id HubProjectChange -> HubProject
47
71
  * GET /projects/:id/targets -> HubTarget[]
48
72
  * GET /projects/:id/targets/:target -> HubTarget
49
73
  * POST /projects/:id/targets {sha256,name,createdBy} -> {target:HubTarget;created:boolean}
50
74
  * (idempotent by sha256 within the project; the size is the stored binary's,
51
75
  * a `size` field is accepted and ignored; 409 if the blob is absent)
76
+ * PATCH /projects/:id/targets/:target HubTargetChange -> HubTarget (metadata only; id, binary and history unchanged)
52
77
  * HEAD /blobs/:sha256 -> 200 | 404
53
78
  * PUT /blobs/:sha256 (octet-stream body) -> {sha256,size} (present blob = no-op)
54
79
  * GET /blobs/:sha256 -> octet-stream
@@ -77,6 +102,8 @@ export interface HubClient {
77
102
  target: HubTarget;
78
103
  created: boolean;
79
104
  }>;
105
+ updateTarget(projectId: string, targetId: string, change: HubTargetChange): Promise<HubTarget>;
106
+ updateProject(projectId: string, change: HubProjectChange): Promise<HubProject>;
80
107
  hasBlob(sha256: string): Promise<boolean>;
81
108
  /** Streams the file unless the hub has it already; idempotent. True when this call uploaded it. */
82
109
  putBlob(sha256: string, file: string): Promise<boolean>;
@@ -117,10 +117,47 @@ export declare class LedgerStore {
117
117
  revision: number;
118
118
  accepted1to1: boolean;
119
119
  };
120
- create(projectId: string, targetId: string, name: string): {
120
+ create(projectId: string, targetId: string, name: string, tags?: string[]): {
121
121
  project: Project;
122
122
  strict1to1: string;
123
123
  };
124
+ /** Compact rows of every plan (#186): without inventory sources, with the target's name and version label from the hub. */
125
+ list(): {
126
+ plan: string;
127
+ name: string;
128
+ tags: string[];
129
+ target: string;
130
+ targetName: string | null;
131
+ targetVersionLabel: string | null;
132
+ revision: number;
133
+ createdAt: string;
134
+ }[];
135
+ private planRows;
136
+ /** One plan in full: its list row and the stored plan, inventory sources included. */
137
+ show(projectId: string): {
138
+ stored: Project;
139
+ plan: string;
140
+ name: string;
141
+ tags: string[];
142
+ target: string;
143
+ targetName: string | null;
144
+ targetVersionLabel: string | null;
145
+ revision: number;
146
+ createdAt: string;
147
+ };
148
+ /**
149
+ * Renames a plan or adds and removes its tags. A metadata edit: no revision or event, no effect on planning. Tags are
150
+ * applied one by one inside the transaction, so edits of different tags by several agents all apply.
151
+ */
152
+ setPlan(projectId: string, change: {
153
+ name?: string;
154
+ addTags?: string[];
155
+ removeTags?: string[];
156
+ }): {
157
+ plan: string;
158
+ name: string;
159
+ tags: string[];
160
+ };
124
161
  importInventory(projectId: string, input: unknown, artifact: Attachment, epoch?: string): {
125
162
  project: string;
126
163
  revision: number;
@@ -147,12 +184,14 @@ export declare class LedgerStore {
147
184
  private planDiscovery;
148
185
  claim(taskId: string, worker: string, ttl: number): {
149
186
  task: Task;
187
+ target: string;
150
188
  revision: number;
151
189
  lease: string;
152
190
  };
153
191
  /** Plan and claim one slice atomically at the current state; no observed revision is needed. */
154
192
  next(projectId: string, worker: string, count: number, kind: TaskKind, ttl: number, epoch?: string, selected?: string[], discover?: DiscoverScope): {
155
193
  task: Task;
194
+ target: string;
156
195
  revision: number;
157
196
  lease: string;
158
197
  };
@@ -285,7 +324,6 @@ export declare class LedgerStore {
285
324
  epoch: string | undefined;
286
325
  revision: number;
287
326
  };
288
- projects(): Project[];
289
327
  events(projectId: string, after: number, limit: number): {
290
328
  project: string;
291
329
  revision: number;
@@ -306,12 +306,12 @@ export class LedgerStore {
306
306
  previousReview: fn.review, reason: why, version: fn.version });
307
307
  return result();
308
308
  }
309
- create(projectId, targetId, name) {
309
+ create(projectId, targetId, name, tags = []) {
310
310
  const id = identifier(projectId);
311
311
  name = string(name);
312
312
  const target = this.db.prepare('SELECT id,sha256 FROM targets WHERE project_id=? AND id=?').get(this.scope, string(targetId, 128));
313
313
  if (!target)
314
- fail('notFound', 'Target is not registered in this hub project; see ghidra targets list.');
314
+ fail('notFound', 'Target is not registered in this hub project; see hub targets list.');
315
315
  const strict1to1 = 'No function is accepted without a replayable exhaustive/formal verifier.';
316
316
  const prior = this.get('SELECT data FROM ledger_projects WHERE scope=? AND id=?', id);
317
317
  if (prior) {
@@ -321,11 +321,42 @@ export class LedgerStore {
321
321
  fail('conflict', 'Project ID already exists with another target or name.');
322
322
  }
323
323
  const project = { id, target: String(target.id), binarySha256: String(target.sha256), name, revision: 1, planningRevision: 1, epoch: randomUUID(),
324
- phase: 'reverse-engineering', inventory: { complete: false, reportedTotal: null, sources: [] }, createdAt: this.clock() };
324
+ phase: 'reverse-engineering', inventory: { complete: false, reportedTotal: null, sources: [] }, createdAt: this.clock(), ...(tags.length ? { tags: [...new Set(tags)].sort() } : {}) };
325
325
  this.run('INSERT INTO ledger_projects(scope,id,data) VALUES(?,?,?)', id, stable(project));
326
326
  this.insertEvent(id, 1, 'project.created', { target: project.target });
327
327
  return { project, strict1to1 };
328
328
  }
329
+ /** Compact rows of every plan (#186): without inventory sources, with the target's name and version label from the hub. */
330
+ list() { return this.tx(() => this.planRows()); }
331
+ planRows() {
332
+ const targets = new Map(this.db.prepare('SELECT id,name,version_label FROM targets WHERE project_id=?').all(this.scope).map(t => [String(t.id), t]));
333
+ return this.all('SELECT data FROM ledger_projects WHERE scope=? ORDER BY id').map(r => {
334
+ const p = JSON.parse(String(r.data)), t = targets.get(p.target);
335
+ return { plan: p.id, name: p.name, tags: p.tags ?? [], target: p.target, targetName: t ? String(t.name) : null,
336
+ targetVersionLabel: t && t.version_label !== null ? String(t.version_label) : null, revision: p.revision, createdAt: new Date(p.createdAt).toISOString() };
337
+ });
338
+ }
339
+ /** One plan in full: its list row and the stored plan, inventory sources included. */
340
+ show(projectId) {
341
+ return this.tx(() => { const project = this.project(projectId); return { ...this.planRows().find(row => row.plan === project.id), stored: project }; });
342
+ }
343
+ /**
344
+ * Renames a plan or adds and removes its tags. A metadata edit: no revision or event, no effect on planning. Tags are
345
+ * applied one by one inside the transaction, so edits of different tags by several agents all apply.
346
+ */
347
+ setPlan(projectId, change) {
348
+ const project = this.project(projectId);
349
+ if (change.name !== undefined)
350
+ project.name = string(change.name);
351
+ const tags = new Set(project.tags ?? []);
352
+ for (const t of change.addTags ?? [])
353
+ tags.add(t);
354
+ for (const t of change.removeTags ?? [])
355
+ tags.delete(t);
356
+ project.tags = [...tags].sort();
357
+ this.putProject(project);
358
+ return { plan: project.id, name: project.name, tags: project.tags };
359
+ }
329
360
  importInventory(projectId, input, artifact, epoch) {
330
361
  const project = this.project(projectId), manifest = object(input);
331
362
  this.checkEpoch(project, epoch);
@@ -516,7 +547,7 @@ export class LedgerStore {
516
547
  const now = this.clock();
517
548
  // Claiming the lease you already hold returns it unchanged.
518
549
  if (task.status === 'leased' && task.worker === worker && task.leaseUntil > now)
519
- return { task, revision: project.revision, lease: leaseToken(task) };
550
+ return { task, target: project.target, revision: project.revision, lease: leaseToken(task) };
520
551
  if (task.status === 'submitted')
521
552
  fail('alreadyClaimed', 'Task is already submitted.', { task: task.id, worker: task.worker ?? null });
522
553
  if (task.status === 'leased' && task.leaseUntil > now)
@@ -530,7 +561,7 @@ export class LedgerStore {
530
561
  task.leaseUntil = now + ttl * 1000;
531
562
  this.putTask(task);
532
563
  this.event(project, 'task.claimed', { task: task.id, worker, fence: task.fence, leaseUntil: task.leaseUntil }, false);
533
- return { task, revision: project.revision, lease: leaseToken(task) };
564
+ return { task, target: project.target, revision: project.revision, lease: leaseToken(task) };
534
565
  }
535
566
  /** Plan and claim one slice atomically at the current state; no observed revision is needed. */
536
567
  next(projectId, worker, count, kind, ttl, epoch, selected, discover) {
@@ -543,7 +574,7 @@ export class LedgerStore {
543
574
  for (const row of this.all("SELECT data FROM ledger_tasks WHERE scope=? AND project=? AND status='leased'", project.id)) {
544
575
  const held = JSON.parse(String(row.data));
545
576
  if (held.worker === worker && held.kind === kind && held.leaseUntil > this.clock() && stable([...held.functions].sort()) === wanted && stable(held.discover ?? null) === stable(discover ?? null))
546
- return { task: held, revision: project.revision, lease: leaseToken(held) };
577
+ return { task: held, target: project.target, revision: project.revision, lease: leaseToken(held) };
547
578
  }
548
579
  }
549
580
  // Outstanding work goes out first: a released task, or one whose lease expired (its agent stopped or crashed), keeps
@@ -552,7 +583,7 @@ export class LedgerStore {
552
583
  const now = this.clock();
553
584
  for (const row of this.all("SELECT data FROM ledger_tasks WHERE scope=? AND project=? AND status IN ('queued','leased') ORDER BY json_extract(data,'$.createdAt'),id", project.id)) {
554
585
  const open = JSON.parse(String(row.data));
555
- if (kind === 'discover' || open.kind !== kind || open.epoch !== project.epoch || open.status === 'leased' && open.leaseUntil > now)
586
+ if (open.kind !== kind || open.epoch !== project.epoch || open.status === 'leased' && open.leaseUntil > now)
556
587
  continue;
557
588
  if (kind === 'review' && open.functions.some(id => this.function(project.id, id).author === worker))
558
589
  continue;
@@ -844,7 +875,6 @@ export class LedgerStore {
844
875
  const { id, target, binarySha256, epoch, revision } = this.project(projectId);
845
876
  return { id, target, binarySha256, epoch, revision };
846
877
  }
847
- projects() { return this.tx(() => this.all('SELECT data FROM ledger_projects WHERE scope=? ORDER BY id').map(r => JSON.parse(String(r.data)))); }
848
878
  events(projectId, after, limit) {
849
879
  return this.tx(() => {
850
880
  const project = this.project(projectId), rows = this.all('SELECT seq,revision,kind,data FROM ledger_events WHERE scope=? AND project=? AND seq>? ORDER BY seq LIMIT ?', project.id, integer(after, 0, Number.MAX_SAFE_INTEGER), integer(limit, 1, 1000) + 1);
@@ -6,6 +6,7 @@ import { readFile, stat, writeFile } from 'node:fs/promises';
6
6
  import { join } from 'node:path';
7
7
  import { hubPaths } from '../core/layout.js';
8
8
  import { hubError } from './settings.js';
9
+ import { targetTag } from './store.js';
9
10
  import { LedgerStore, ledgerDigest, ledgerSchema, ledgerTables, readRows, rowCounts, transaction, writeRows } from './ledger-store.js';
10
11
  import { array, discoverLimits, discoverScope, fail, identifier, integer, object, passport, rva, sha, string } from '../work/model.js';
11
12
  const MiB = 1024 * 1024;
@@ -35,10 +36,32 @@ const functions = (b) => b.functions === undefined || b.functions === null ? und
35
36
  const scope = (b) => b.discover === undefined || b.discover === null ? undefined : discoverScope(object(b.discover));
36
37
  const lease = (b) => ({ task: identifier(b.task), worker: identifier(b.worker), fence: integer(b.fence, 1, Number.MAX_SAFE_INTEGER), epoch: epoch(b) });
37
38
  const ttl = (b) => integer(b.ttl ?? 600, 30, 3600);
39
+ /** Tags of a plan, by the target tag rules (#182): trimmed, lower-cased, de-duplicated. */
40
+ function tags(value, field) {
41
+ if (value === undefined || value === null)
42
+ return undefined;
43
+ if (!Array.isArray(value))
44
+ fail('invalid', field + ' must be an array of tags.');
45
+ try {
46
+ return [...new Set(value.map(targetTag))];
47
+ }
48
+ catch (error) {
49
+ return fail('invalid', error.message);
50
+ }
51
+ }
38
52
  /** Every operation reads its blob inputs first, then changes the ledger in one transaction. */
39
53
  const operations = {
40
54
  context: async ({ s, b }) => b.project === undefined || b.project === null ? null : s.tx(() => s.context(identifier(b.project))),
41
- projects: async ({ s }) => s.projects(),
55
+ list: async ({ s }) => s.list(),
56
+ show: async ({ s, b }) => s.show(identifier(b.project)),
57
+ set: async ({ s, b }) => {
58
+ const name = b.name === undefined || b.name === null ? undefined : string(b.name), addTags = tags(b.addTags, 'addTags'), removeTags = tags(b.removeTags, 'removeTags');
59
+ if (addTags?.some(t => removeTags?.includes(t)))
60
+ fail('invalid', 'A tag cannot be added and removed in one change.');
61
+ if (name === undefined && !addTags?.length && !removeTags?.length)
62
+ fail('invalid', 'Supply name, addTags or removeTags.');
63
+ return s.tx(() => s.setPlan(identifier(b.project), { ...(name === undefined ? {} : { name }), ...(addTags ? { addTags } : {}), ...(removeTags ? { removeTags } : {}) }), true);
64
+ },
42
65
  brief: async ({ s, b }) => s.snapshot(identifier(b.project), integer(b.limit ?? 200, 1, 1000)),
43
66
  functions: async ({ s, b }) => s.functions(identifier(b.project), b.afterRva === undefined || b.afterRva === null ? -1 : rva(b.afterRva), integer(b.limit ?? 100, 1, 1000)),
44
67
  graph: async ({ s, b }) => {
@@ -52,7 +75,7 @@ const operations = {
52
75
  handoff: async ({ s, b }) => s.handoff(identifier(b.task)),
53
76
  export: async ({ s, b }) => s.export(identifier(b.project)),
54
77
  certify: async ({ s }) => s.certify(),
55
- create: async ({ s, b }) => s.tx(() => s.create(identifier(b.project), string(b.target, 128), string(b.name)), true),
78
+ create: async ({ s, b }) => s.tx(() => s.create(identifier(b.project), string(b.target, 128), string(b.name), tags(b.tags, 'tags')), true),
56
79
  import: async ({ s, b, dataRoot }) => {
57
80
  const input = await json(dataRoot, b.artifact);
58
81
  return s.tx(() => s.importInventory(identifier(b.project), input.value, input.artifact, epoch(b)), true);
@@ -114,7 +137,7 @@ const operations = {
114
137
  };
115
138
  const bundleFile = (directory) => join(directory, 'ledger.json');
116
139
  /** Operations that only read the ledger; they stay available while a project is frozen for a move. */
117
- const readOperations = new Set(['context', 'projects', 'brief', 'functions', 'graph', 'events', 'history', 'timing', 'handoff', 'export', 'certify', 'ledger-digest']);
140
+ const readOperations = new Set(['context', 'list', 'show', 'brief', 'functions', 'graph', 'events', 'history', 'timing', 'handoff', 'export', 'certify', 'ledger-digest']);
118
141
  /** The ledger extension with an injectable clock; the hub measures every lease with it. */
119
142
  export function createLedgerExtension({ db, dataRoot }, clock = Date.now) {
120
143
  ledgerSchema(db);
@@ -7,7 +7,7 @@ import { CliError } from '@eyeauras/cli-factory';
7
7
  import { GHIDRA_IDLE_STOP_MS, HUB_API_VERSION, HUB_IDLE_EXIT_MS, ghidraBasePort, hubPaths } from '../core/layout.js';
8
8
  import { packageVersion } from '../package-version.js';
9
9
  import { acquireHubLock } from './lock.js';
10
- import { BlobStore, HubStore, isSha256, projectName } from './store.js';
10
+ import { BlobStore, HubStore, isSha256, projectDescription, projectName, targetTag, versionLabel } from './store.js';
11
11
  import { GhidraChild } from './ghidra.js';
12
12
  import { hubError, invalid, listenAddress, localDialHost } from './settings.js';
13
13
  import { hubExtensionFactories } from './extensions.js';
@@ -18,6 +18,20 @@ const statusOf = { 'hub.invalid': 400, 'hub.not_found': 404, 'hub.runtime_mismat
18
18
  /** Hub project ids (HubStore.newProject, bundles and legacy imports): only such path segments are looked up as projects. */
19
19
  const projectIdPattern = /^[a-f0-9]{32}$/;
20
20
  const loopback = (address) => !!address && /^(?:127\.|::1$|::ffff:127\.)/.test(address);
21
+ /** `addTags` and `removeTags` of a metadata edit, normalized by the tag rules; one change cannot add and remove a tag. */
22
+ function tagChange(b) {
23
+ const change = {};
24
+ for (const field of ['addTags', 'removeTags']) {
25
+ if (b[field] === undefined)
26
+ continue;
27
+ if (!Array.isArray(b[field]))
28
+ invalid(field + ' must be an array of tags.');
29
+ change[field] = [...new Set(b[field].map(targetTag))];
30
+ }
31
+ if (change.addTags?.some(t => change.removeTags?.includes(t)))
32
+ invalid('A tag cannot be added and removed in one change.');
33
+ return change;
34
+ }
21
35
  /** Addresses a hub on `listen` binds: the configured one and the loopback of its family, where local clients dial (settings.ts localDialHost). */
22
36
  export function hubAddresses(listen) {
23
37
  const local = localDialHost(listen);
@@ -352,6 +366,24 @@ export class Hub {
352
366
  case 'GET /projects/:/targets/:':
353
367
  gate(this, parts[1], false);
354
368
  return send(200, this.store.target(parts[1], parts[3]));
369
+ case 'PATCH /projects/:/targets/:': {
370
+ const b = await json(), change = tagChange(b);
371
+ if ('versionLabel' in b)
372
+ change.versionLabel = versionLabel(b.versionLabel);
373
+ if (!('versionLabel' in change) && !change.addTags?.length && !change.removeTags?.length)
374
+ invalid('Supply versionLabel, addTags or removeTags.');
375
+ gate(this, parts[1], true);
376
+ return send(200, this.store.updateTarget(parts[1], parts[3], change));
377
+ }
378
+ case 'PATCH /projects/:': {
379
+ const b = await json(), change = tagChange(b);
380
+ if ('description' in b)
381
+ change.description = projectDescription(b.description);
382
+ if (!('description' in change) && !change.addTags?.length && !change.removeTags?.length)
383
+ invalid('Supply description, addTags or removeTags.');
384
+ gate(this, parts[1], true);
385
+ return send(200, this.store.updateProject(parts[1], change));
386
+ }
355
387
  case 'POST /admin/:': return send(200, await this.admin(parts[1], await json(), loopback(q.socket.remoteAddress)));
356
388
  case 'POST /projects/:/targets': {
357
389
  // A `size` field of older clients is ignored: the target records the stored binary's size.
@@ -4,6 +4,27 @@ import type { HubProject, HubTarget } from './contract.js';
4
4
  export declare const isSha256: (value: unknown) => value is string;
5
5
  export declare const targetId: (projectId: string, sha256: string) => string;
6
6
  export declare const projectName: (value: unknown) => string;
7
+ /** A project description: trimmed, 1-1000 characters without control characters other than newlines; empty clears it (null). */
8
+ export declare function projectDescription(value: unknown): string | null;
9
+ /** Metadata edits of one project, with the tag rules of targets. */
10
+ export interface ProjectChange {
11
+ description?: string | null;
12
+ addTags?: string[];
13
+ removeTags?: string[];
14
+ }
15
+ /**
16
+ * A target's human-readable build version: trimmed, case kept, 1-128 printable characters; empty clears it (null).
17
+ * It names the binary's product build, not a Ghidra version.
18
+ */
19
+ export declare function versionLabel(value: unknown): string | null;
20
+ /** A target tag: trimmed and lower-cased, 1-64 of a-z 0-9 . _ - + : starting with a letter or digit. */
21
+ export declare function targetTag(value: unknown): string;
22
+ /** Metadata edits of one target; tag edits add or remove single tags, so concurrent edits of different tags all apply. */
23
+ export interface TargetChange {
24
+ versionLabel?: string | null;
25
+ addTags?: string[];
26
+ removeTags?: string[];
27
+ }
7
28
  export interface ProjectState {
8
29
  state: 'active' | 'frozen' | 'moved';
9
30
  movedTo: string | null;
@@ -26,13 +47,21 @@ export declare class HubStore {
26
47
  fingerprint: string;
27
48
  }): void;
28
49
  projects(): HubProject[];
50
+ private projectTags;
29
51
  projectByName(name: string): HubProject | undefined;
30
52
  project(id: string): HubProject;
53
+ /** Sets or clears the description and adds or removes tags of a project in one transaction. */
54
+ updateProject(id: string, change: ProjectChange): HubProject;
31
55
  /** A fresh project identity; its repository must exist before insertProject records it. */
32
56
  static newProject(name: string): HubProject;
33
57
  insertProject(p: HubProject): HubProject;
34
58
  targets(projectId: string): HubTarget[];
35
59
  target(projectId: string, id: string): HubTarget;
60
+ /**
61
+ * Sets or clears the version label and adds or removes tags in one transaction; identity, binary, Ghidra history and
62
+ * Work references are untouched. A tag added or removed by another client stays as that client left it.
63
+ */
64
+ updateTarget(projectId: string, id: string, change: TargetChange): HubTarget;
36
65
  /** State of a project, or undefined when no project has this id. */
37
66
  findProjectState(id: string): ProjectState | undefined;
38
67
  projectState(id: string): ProjectState;