@eyeauras/insight-cli 0.8.3 → 0.8.4

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 (109) hide show
  1. package/.cli-package-build.json +1 -1
  2. package/SKILL.md +1 -1
  3. package/dist/src/administration.js +1 -1
  4. package/dist/src/archive.js +1 -1
  5. package/dist/src/artifacts.d.ts +2 -1
  6. package/dist/src/artifacts.js +6 -5
  7. package/dist/src/binary.js +1 -1
  8. package/dist/src/capture.js +3 -3
  9. package/dist/src/cli.js +17 -16
  10. package/dist/src/contexts.js +14 -17
  11. package/dist/src/cross.js +1 -1
  12. package/dist/src/debugger.js +1 -1
  13. package/dist/src/die.js +1 -1
  14. package/dist/src/dnspy.js +1 -1
  15. package/dist/src/dotnet-diagnostics.js +1 -1
  16. package/dist/src/ilspy.js +1 -1
  17. package/dist/src/lifecycle.js +5 -5
  18. package/dist/src/lldb.js +1 -1
  19. package/dist/src/llvm.js +1 -1
  20. package/dist/src/managed-heap.js +1 -1
  21. package/dist/src/managed-metadata.js +1 -1
  22. package/dist/src/mitmproxy.js +1 -1
  23. package/dist/src/model.d.ts +6 -1
  24. package/dist/src/model.js +9 -2
  25. package/dist/src/mutations.js +1 -1
  26. package/dist/src/projects.js +3 -3
  27. package/dist/src/prototype-cli.js +4 -4
  28. package/dist/src/research.js +1 -1
  29. package/dist/src/runtime-manager.d.ts +2 -2
  30. package/dist/src/runtime-manager.js +28 -4
  31. package/dist/src/sdk-files.js +3 -3
  32. package/dist/src/sdk.js +1 -1
  33. package/dist/src/server.d.ts +1 -0
  34. package/dist/src/server.js +17 -7
  35. package/dist/src/sevenzip.js +1 -1
  36. package/dist/src/strace.js +1 -1
  37. package/dist/src/sync-policy.js +4 -4
  38. package/dist/src/tool-runtime/identity.d.ts +7 -0
  39. package/dist/src/tool-runtime/identity.js +35 -0
  40. package/dist/src/tool-runtime/store.js +3 -0
  41. package/dist/src/tool-runtime/supervisor.d.ts +8 -0
  42. package/dist/src/tool-runtime/supervisor.js +58 -10
  43. package/dist/src/tshark.js +1 -1
  44. package/dist/src/ui.js +3 -3
  45. package/dist/src/version-tracking.js +2 -2
  46. package/dist/src/windbg.js +1 -1
  47. package/dist/src/work/backup.js +14 -2
  48. package/dist/src/work/commands.js +50 -13
  49. package/dist/src/work/model.d.ts +43 -1
  50. package/dist/src/work/model.js +128 -0
  51. package/dist/src/work/store.d.ts +34 -3
  52. package/dist/src/work/store.js +75 -18
  53. package/dist/src/work/timing.d.ts +9 -0
  54. package/dist/src/work/timing.js +10 -1
  55. package/package.json +1 -1
  56. package/references/native/InsightNativeCheckout.java +24 -8
  57. package/references/work-tracking.md +52 -0
  58. package/skill-bundle/insight-artifacts/SKILL.md +1 -1
  59. package/skill-bundle/insight-binary/SKILL.md +1 -1
  60. package/skill-bundle/insight-capture/SKILL.md +1 -1
  61. package/skill-bundle/insight-cli/SKILL.md +1 -1
  62. package/skill-bundle/insight-die/SKILL.md +1 -1
  63. package/skill-bundle/insight-dnspy/SKILL.md +1 -1
  64. package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
  65. package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
  66. package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
  67. package/skill-bundle/insight-frida/SKILL.md +1 -1
  68. package/skill-bundle/insight-ghidra/SKILL.md +1 -1
  69. package/skill-bundle/insight-ilspy/SKILL.md +1 -1
  70. package/skill-bundle/insight-interop/SKILL.md +1 -1
  71. package/skill-bundle/insight-lldb/SKILL.md +1 -1
  72. package/skill-bundle/insight-llvm/SKILL.md +1 -1
  73. package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
  74. package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
  75. package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
  76. package/skill-bundle/insight-overview/SKILL.md +1 -1
  77. package/skill-bundle/insight-procmon/SKILL.md +1 -1
  78. package/skill-bundle/insight-re/SKILL.md +1 -1
  79. package/skill-bundle/insight-re/references/work-tracking.md +52 -0
  80. package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
  81. package/skill-bundle/insight-strace/SKILL.md +1 -1
  82. package/skill-bundle/insight-tshark/SKILL.md +1 -1
  83. package/skill-bundle/insight-windbg/SKILL.md +1 -1
  84. package/skill-bundle/manifest.json +1 -1
  85. package/skills/insight-artifacts/SKILL.md +1 -1
  86. package/skills/insight-binary/SKILL.md +1 -1
  87. package/skills/insight-capture/SKILL.md +1 -1
  88. package/skills/insight-die/SKILL.md +1 -1
  89. package/skills/insight-dnspy/SKILL.md +1 -1
  90. package/skills/insight-dotnet-dump/SKILL.md +1 -1
  91. package/skills/insight-dotnet-stack/SKILL.md +1 -1
  92. package/skills/insight-dotnet-trace/SKILL.md +1 -1
  93. package/skills/insight-frida/SKILL.md +1 -1
  94. package/skills/insight-ghidra/SKILL.md +1 -1
  95. package/skills/insight-ilspy/SKILL.md +1 -1
  96. package/skills/insight-interop/SKILL.md +1 -1
  97. package/skills/insight-lldb/SKILL.md +1 -1
  98. package/skills/insight-llvm/SKILL.md +1 -1
  99. package/skills/insight-managed-heap/SKILL.md +1 -1
  100. package/skills/insight-managed-metadata/SKILL.md +1 -1
  101. package/skills/insight-mitmproxy/SKILL.md +1 -1
  102. package/skills/insight-overview/SKILL.md +1 -1
  103. package/skills/insight-procmon/SKILL.md +1 -1
  104. package/skills/insight-re/SKILL.md +1 -1
  105. package/skills/insight-re/references/work-tracking.md +52 -0
  106. package/skills/insight-sevenzip/SKILL.md +1 -1
  107. package/skills/insight-strace/SKILL.md +1 -1
  108. package/skills/insight-tshark/SKILL.md +1 -1
  109. package/skills/insight-windbg/SKILL.md +1 -1
@@ -1,7 +1,7 @@
1
1
  import { command, Permission } from '@eyeauras/cli-factory';
2
2
  import { basename, dirname, resolve } from 'node:path';
3
3
  import { lstat, readFile, mkdir, copyFile, writeFile } from 'node:fs/promises';
4
- import { array, fail, identifier, integer, object, parseLease, passport, rva, sha, string } from './model.js';
4
+ import { array, discoverLimits, discoverScope, fail, identifier, integer, object, parseLease, passport, rva, sha, string } from './model.js';
5
5
  import { packageVersion } from '../package-version.js';
6
6
  import { WorkStore } from './store.js';
7
7
  import { saveDashboard } from './dashboard.js';
@@ -31,18 +31,35 @@ function leaseOf(o) {
31
31
  return { task: identifier(o.task), worker: identifier(o.worker), fence: integer(o.fence, 1, Number.MAX_SAFE_INTEGER), ...(o.epoch === undefined ? {} : { epoch: identifier(o.epoch) }) };
32
32
  }
33
33
  const functionId = { flags: '--function <id>', description: 'Exact full-hash/RVA function identity', required: true };
34
+ const kindOption = { flags: '--kind <kind>', description: 'reconstruct, review or discover', defaultValue: 'reconstruct' };
35
+ /** Traversal of a discover task; --functions names its roots. */
36
+ const traversal = [
37
+ { flags: '--strategy <strategy>', description: 'discover: breadth (BFS, default) or depth (DFS)' },
38
+ { flags: '--direction <direction>', description: 'discover: callees (default), callers or both' },
39
+ { flags: '--max-depth <n>', description: `discover: deepest level, roots are 0 (default 2, at most ${discoverLimits.maxDepth})` },
40
+ { flags: '--max-functions <n>', description: `discover: most visited functions including roots (default 50, at most ${discoverLimits.maxFunctions})` }
41
+ ];
42
+ function traversalOf(o) {
43
+ const given = [o.strategy, o.direction, o.maxDepth, o.maxFunctions].some(value => value !== undefined);
44
+ if (o.kind !== 'discover') {
45
+ if (given)
46
+ fail('invalid', '--strategy, --direction, --max-depth and --max-functions apply only to --kind discover.');
47
+ return undefined;
48
+ }
49
+ return discoverScope(o);
50
+ }
34
51
  const pageLimit = { flags: '--limit <n>', description: 'Maximum rows (1..1000)', defaultValue: 100 };
35
52
  async function capture(workspace, path, max) {
36
53
  const info = await lstat(path);
37
54
  if (!info.isFile() || info.isSymbolicLink() || info.size < 1 || info.size > max)
38
55
  fail('limit', `An ordinary nonempty file of at most ${max} bytes is required.`);
39
- const artifact = await workspace.artifacts.capture(path, 'input');
56
+ const artifact = await workspace.artifacts.capture(path, 'input', max);
40
57
  if (artifact.size > max)
41
58
  fail('limit', 'Captured input exceeds this command limit.');
42
59
  return { ...artifact, name: basename(path) };
43
60
  }
44
- async function json(workspace, path) {
45
- const artifact = await capture(workspace, path, 8 * 1024 * 1024);
61
+ async function json(workspace, path, max = 8 * 1024 * 1024) {
62
+ const artifact = await capture(workspace, path, max);
46
63
  const saved = workspace.artifacts.path({ ...artifact, kind: 'input' });
47
64
  let value;
48
65
  try {
@@ -60,6 +77,15 @@ async function json(workspace, path) {
60
77
  async function materialize(w, handoff, directory) {
61
78
  await mkdir(directory, { recursive: false });
62
79
  const task = handoff.task, files = [], rows = [];
80
+ if (task.kind === 'discover') {
81
+ // A report skeleton: roots already at depth 0 with their xrefs still to be observed.
82
+ const manifest = resolve(directory, 'discovery-report.json');
83
+ await writeFile(manifest, JSON.stringify({ schema: 1, kind: 'discovery-report', task: task.id, binarySha256: handoff.project.binarySha256,
84
+ discover: task.discover, model: { source: 'ghidra', revision: null },
85
+ visited: handoff.functions.map(fn => ({ function: fn.id, name: fn.name, depth: 0, xrefs: { source: null, complete: null } })),
86
+ edges: [], frontier: [], summary: null, recommended: [] }, null, 1) + '\n', { flag: 'wx' });
87
+ return { directory, manifest, files: 0, next: 'Fill model, visited, edges, frontier and summary within discover, then: work submit --lease LEASE --file ' + manifest };
88
+ }
63
89
  for (const fn of handoff.functions) {
64
90
  const label = fn.rva.toString(16).padStart(8, '0'), folder = resolve(directory, label);
65
91
  await mkdir(folder);
@@ -202,17 +228,23 @@ export function workCommands(access) {
202
228
  { flags: '--reason <text>', description: 'Retained evidence/reason for reopening approval', required: true }], async (s, w, o, c) => ({ input: o, project: identifier(o.project),
203
229
  apply: () => s.reopenReview(identifier(o.project), string(o.function, 256), sha(o.sourceSha256), integer(o.expectVersion, 1, Number.MAX_SAFE_INTEGER), string(o.reason, 2000), o.epoch === undefined ? undefined : identifier(o.epoch)) })),
204
230
  changing('plan', 'Reserve a small nonoverlapping reconstruction or independent-review slice', [project, revision, epoch,
205
- { flags: '--count <n>', description: 'Maximum functions, 1..50', defaultValue: 10 }, { flags: '--kind <kind>', description: 'reconstruct or review', defaultValue: 'reconstruct' },
206
- { flags: '--functions <ids>', description: 'Optional comma-separated exact function IDs' },
207
- { flags: '--after-rva <hex>', description: 'Continue beyond a bounded frontier' }], async (s, w, o, c) => ({ input: o, project: identifier(o.project),
208
- apply: () => s.plan(identifier(o.project), integer(o.expectRevision, 1, Number.MAX_SAFE_INTEGER), integer(o.count, 1, 50), string(o.kind), o.functions === undefined ? undefined : string(o.functions, 16000).split(','), o.afterRva === undefined ? -1 : rva(o.afterRva), o.epoch === undefined ? undefined : identifier(o.epoch)) })),
231
+ { flags: '--count <n>', description: 'Maximum functions, 1..50', defaultValue: 10 }, kindOption,
232
+ { flags: '--functions <ids>', description: 'Optional comma-separated exact function IDs; for discover, the roots' },
233
+ { flags: '--after-rva <hex>', description: 'Continue beyond a bounded frontier' }, ...traversal], async (s, w, o, c) => {
234
+ const scope = traversalOf(o);
235
+ return { input: o, project: identifier(o.project),
236
+ apply: () => s.plan(identifier(o.project), integer(o.expectRevision, 1, Number.MAX_SAFE_INTEGER), integer(o.count, 1, 50), string(o.kind), o.functions === undefined ? undefined : string(o.functions, 16000).split(','), o.afterRva === undefined ? -1 : rva(o.afterRva), o.epoch === undefined ? undefined : identifier(o.epoch), undefined, scope) };
237
+ }),
209
238
  changing('claim', 'Claim queued or expired work and obtain a fresh fence', [task, worker, ttl], async (s, w, o, c) => ({ input: o, project: s.handoff(identifier(o.task)).project.id,
210
239
  apply: () => s.claim(identifier(o.task), identifier(o.worker), integer(o.ttl, 30, 3600)) })),
211
240
  changing('next', 'Plan and claim the next slice atomically; returns a lease token', [project, epoch,
212
241
  { flags: '--worker <id>', description: 'Cooperative worker label, not authenticated identity', required: true }, ttl,
213
- { flags: '--count <n>', description: 'Maximum functions, 1..50', defaultValue: 10 }, { flags: '--kind <kind>', description: 'reconstruct or review', defaultValue: 'reconstruct' },
214
- { flags: '--functions <ids>', description: 'Optional exact function IDs, e.g. the retry list of work.taskCancelled' }], async (s, w, o, c) => ({ input: o, project: identifier(o.project),
215
- apply: () => s.next(identifier(o.project), identifier(o.worker), integer(o.count, 1, 50), string(o.kind), integer(o.ttl, 30, 3600), o.epoch === undefined ? undefined : identifier(o.epoch), o.functions === undefined ? undefined : string(o.functions, 16000).split(',')) })),
242
+ { flags: '--count <n>', description: 'Maximum functions, 1..50', defaultValue: 10 }, kindOption,
243
+ { flags: '--functions <ids>', description: 'Optional exact function IDs, e.g. the retry list of work.taskCancelled; for discover, the roots' }, ...traversal], async (s, w, o, c) => {
244
+ const scope = traversalOf(o);
245
+ return { input: o, project: identifier(o.project),
246
+ apply: () => s.next(identifier(o.project), identifier(o.worker), integer(o.count, 1, 50), string(o.kind), integer(o.ttl, 30, 3600), o.epoch === undefined ? undefined : identifier(o.epoch), o.functions === undefined ? undefined : string(o.functions, 16000).split(','), scope) };
247
+ }),
216
248
  changing('heartbeat', 'Extend a still-current lease', [...held, ttl], async (s, w, o, c) => {
217
249
  const l = leaseOf(o);
218
250
  return { input: o, project: s.handoff(l.task).project.id,
@@ -232,8 +264,13 @@ export function workCommands(access) {
232
264
  return { ...result, materialized: await materialize(w, result, resolve(c.cwd, string(o.materialize, 4096))) };
233
265
  }), { permission: Permission.ReadOnly, options: [{ ...task, required: false }, leaseOption,
234
266
  { flags: '--materialize <dir>', description: 'New directory: retained source/contract per function plus a ready submission or review manifest' }] }),
235
- changing('submit', 'Retain exact reconstruction source and passport for the whole leased slice', [...held, file], async (s, w, o, c) => {
236
- const l = leaseOf(o), path = resolve(c.cwd, string(o.file)), manifest = await json(w, path), body = object(manifest.value);
267
+ changing('submit', 'Retain exact reconstruction source and passport for the whole leased slice, or the discovery report of a discover task', [...held, file], async (s, w, o, c) => {
268
+ const l = leaseOf(o), path = resolve(c.cwd, string(o.file)), discovery = s.handoff(l.task).task.kind === 'discover';
269
+ const manifest = await json(w, path, discovery ? discoverLimits.reportBytes : undefined), body = object(manifest.value);
270
+ if (discovery) {
271
+ return { input: { task: o.task, worker: o.worker, fence: o.fence, epoch: o.epoch, lease: o.lease, report: manifest.artifact }, project: s.handoff(l.task).project.id,
272
+ apply: () => s.submitDiscovery(l.task, l.worker, l.fence, manifest.value, manifest.artifact, l.epoch) };
273
+ }
237
274
  const entries = [];
238
275
  for (const [index, value] of array(body.functions, 50).entries()) {
239
276
  const row = object(value), sourcePath = resolve(dirname(path), string(row.source)), contractPath = resolve(dirname(path), string(row.contract));
@@ -69,7 +69,7 @@ export interface Project {
69
69
  export interface Task {
70
70
  id: string;
71
71
  project: string;
72
- kind: 'reconstruct' | 'review';
72
+ kind: TaskKind;
73
73
  status: 'queued' | 'leased' | 'submitted' | 'cancelled';
74
74
  functions: string[];
75
75
  versions: Record<string, number>;
@@ -80,7 +80,49 @@ export interface Task {
80
80
  createdAt: number;
81
81
  result?: unknown;
82
82
  epoch?: string;
83
+ /** Traversal parameters of a discover task; its functions are the roots. */
84
+ discover?: DiscoverScope;
83
85
  }
86
+ export type TaskKind = 'reconstruct' | 'review' | 'discover';
87
+ export declare const taskKinds: readonly TaskKind[];
88
+ export interface DiscoverScope {
89
+ strategy: 'breadth' | 'depth';
90
+ direction: 'callees' | 'callers' | 'both';
91
+ maxDepth: number;
92
+ maxFunctions: number;
93
+ }
94
+ export declare const discoverLimits: {
95
+ maxDepth: number;
96
+ maxFunctions: number;
97
+ edges: number;
98
+ frontier: number;
99
+ recommended: number;
100
+ reportBytes: number;
101
+ };
102
+ /** Traversal parameters; defaults are breadth-first callees, depth 2, at most 50 functions. Roots are at depth 0. */
103
+ export declare function discoverScope(value: Record<string, unknown>): DiscoverScope;
104
+ /**
105
+ * Validates a discovery report against its task. The traversal itself happened outside Work (Ghidra xrefs or a
106
+ * pinned graph inventory): this checks shape, identity and bounds, not that the graph is complete. Every visited
107
+ * function appears once, roots and only roots sit at depth 0, and each function states where its xrefs came from
108
+ * and whether that observation was complete, so an empty xref list is never read as proof of no calls.
109
+ */
110
+ export declare function discoveryReport(value: unknown, expected: {
111
+ task: string;
112
+ binarySha256: string;
113
+ roots: string[];
114
+ scope: DiscoverScope;
115
+ }): {
116
+ model: {
117
+ source: string;
118
+ revision: string;
119
+ };
120
+ visited: number;
121
+ edges: number;
122
+ frontier: number;
123
+ maxDepthReached: number;
124
+ recommended: string[];
125
+ };
84
126
  export interface Snapshot {
85
127
  project: Project;
86
128
  counts: Record<Stage, number>;
@@ -54,6 +54,134 @@ export function rva(value) {
54
54
  fail('invalid', 'String RVAs require 0x-prefixed hexadecimal.');
55
55
  return integer(value, 0, 0xffffffff);
56
56
  }
57
+ export const taskKinds = ['reconstruct', 'review', 'discover'];
58
+ export const discoverLimits = { maxDepth: 16, maxFunctions: 500, edges: 10000, frontier: 5000, recommended: 50, reportBytes: 2 * 1024 * 1024 };
59
+ /** Traversal parameters; defaults are breadth-first callees, depth 2, at most 50 functions. Roots are at depth 0. */
60
+ export function discoverScope(value) {
61
+ const strategy = value.strategy ?? 'breadth', direction = value.direction ?? 'callees';
62
+ if (strategy !== 'breadth' && strategy !== 'depth')
63
+ fail('invalid', 'Discovery strategy is breadth or depth.');
64
+ if (direction !== 'callees' && direction !== 'callers' && direction !== 'both')
65
+ fail('invalid', 'Discovery direction is callees, callers or both.');
66
+ return { strategy, direction, maxDepth: integer(value.maxDepth ?? 2, 0, discoverLimits.maxDepth), maxFunctions: integer(value.maxFunctions ?? 50, 1, discoverLimits.maxFunctions) };
67
+ }
68
+ const functionPattern = /^fn:([a-f0-9]{64}):([0-9a-f]{8})$/;
69
+ /** A full module hash plus RVA, in the form work import gives it; the module must be the project's. */
70
+ function discoveredFunction(value, binarySha, field) {
71
+ const id = string(value, 256), match = functionPattern.exec(id);
72
+ if (!match)
73
+ fail('invalid', `${field} must be fn:<full module sha256>:<8-digit rva>.`, { field });
74
+ if (match[1] !== binarySha)
75
+ fail('binding', `${field} names another module; record calls into other modules as external frontier.`, { field });
76
+ return id;
77
+ }
78
+ /**
79
+ * Validates a discovery report against its task. The traversal itself happened outside Work (Ghidra xrefs or a
80
+ * pinned graph inventory): this checks shape, identity and bounds, not that the graph is complete. Every visited
81
+ * function appears once, roots and only roots sit at depth 0, and each function states where its xrefs came from
82
+ * and whether that observation was complete, so an empty xref list is never read as proof of no calls.
83
+ */
84
+ export function discoveryReport(value, expected) {
85
+ const report = object(value);
86
+ if (report.schema !== 1 || report.kind !== 'discovery-report')
87
+ fail('invalid', 'Discovery report needs schema 1 and kind discovery-report.');
88
+ if (report.task !== expected.task)
89
+ fail('binding', 'Discovery report names another task.');
90
+ if (sha(report.binarySha256) !== expected.binarySha256)
91
+ fail('binding', 'Discovery report names another module.');
92
+ const model = object(report.model);
93
+ string(model.source, 128);
94
+ string(model.revision, 128);
95
+ const visited = array(report.visited, expected.scope.maxFunctions).map((row, i) => {
96
+ const entry = object(row), field = `visited[${i}]`, id = discoveredFunction(entry.function, expected.binarySha256, field + '.function');
97
+ const depth = integer(entry.depth, 0, expected.scope.maxDepth), xrefs = object(entry.xrefs);
98
+ string(xrefs.source, 256);
99
+ if (typeof xrefs.complete !== 'boolean')
100
+ fail('invalid', `${field}.xrefs.complete must be a JSON boolean.`, { field: field + '.xrefs.complete' });
101
+ if (entry.name !== undefined)
102
+ string(entry.name, 512);
103
+ return { id, depth };
104
+ });
105
+ const seen = new Set(visited.map(v => v.id));
106
+ if (seen.size !== visited.length)
107
+ fail('invalid', 'Each function is visited once; deduplicate by module hash and RVA.');
108
+ for (const root of expected.roots)
109
+ if (visited.find(v => v.id === root)?.depth !== 0)
110
+ fail('scope', 'Every root is visited at depth 0.', { root });
111
+ if (visited.some(v => v.depth === 0 && !expected.roots.includes(v.id)))
112
+ fail('scope', 'Only the assigned roots sit at depth 0.');
113
+ const edgeKeys = new Set();
114
+ const edges = array(report.edges, discoverLimits.edges).map((row, i) => {
115
+ const edge = object(row), field = `edges[${i}]`, source = discoveredFunction(edge.source, expected.binarySha256, field + '.source');
116
+ const target = discoveredFunction(edge.target, expected.binarySha256, field + '.target');
117
+ if (edge.kind !== 'direct' && edge.kind !== 'indirect')
118
+ fail('invalid', `${field}.kind is direct or indirect.`);
119
+ string(edge.evidence, 4000);
120
+ if (!seen.has(source) && !seen.has(target))
121
+ fail('scope', `${field} touches no visited function.`);
122
+ const key = source + '>' + target + '>' + edge.kind;
123
+ if (edgeKeys.has(key))
124
+ fail('invalid', `${field} repeats an edge.`);
125
+ edgeKeys.add(key);
126
+ return edge;
127
+ });
128
+ const reasons = ['depth-limit', 'function-limit', 'unresolved-indirect', 'external'];
129
+ const frontier = array(report.frontier, discoverLimits.frontier).map((row, i) => {
130
+ const entry = object(row), field = `frontier[${i}]`;
131
+ if (typeof entry.reason !== 'string' || !reasons.includes(entry.reason))
132
+ fail('invalid', `${field}.reason is one of ${reasons.join(', ')}.`);
133
+ const from = discoveredFunction(entry.from, expected.binarySha256, field + '.from');
134
+ if (!seen.has(from))
135
+ fail('scope', `${field}.from must be a visited function.`);
136
+ if (entry.reason === 'depth-limit' || entry.reason === 'function-limit')
137
+ discoveredFunction(entry.function, expected.binarySha256, field + '.function');
138
+ else if (entry.reason === 'external')
139
+ string(entry.function, 512);
140
+ else if (entry.function !== undefined)
141
+ string(entry.function, 512);
142
+ string(entry.evidence, 4000);
143
+ return entry;
144
+ });
145
+ // Every non-root visit is reached by a reported edge from the level above, in the assigned direction. Breadth-first
146
+ // depths are also the shortest such distance from the roots; a depth-first walk may reach a function by a longer path.
147
+ const depth = new Map(visited.map(v => [v.id, v.depth])), next = new Map();
148
+ const step = (from, to) => { if (!next.has(from))
149
+ next.set(from, []); next.get(from).push(to); };
150
+ for (const edge of edges) {
151
+ const source = String(edge.source), target = String(edge.target);
152
+ if (expected.scope.direction !== 'callers')
153
+ step(source, target);
154
+ if (expected.scope.direction !== 'callees')
155
+ step(target, source);
156
+ }
157
+ for (const v of visited)
158
+ if (v.depth > 0 && !visited.some(u => u.depth === v.depth - 1 && next.get(u.id)?.includes(v.id)))
159
+ fail('scope', `Visited ${v.id} at depth ${v.depth} is not reached by an edge from depth ${v.depth - 1} in direction ${expected.scope.direction}.`, { function: v.id });
160
+ if (expected.scope.strategy === 'breadth') {
161
+ const distance = new Map(expected.roots.map(root => [root, 0])), queue = [...expected.roots];
162
+ // Over every reported edge, also through functions the report did not visit: their edges still shorten the path.
163
+ for (let i = 0; i < queue.length; i++)
164
+ for (const to of next.get(queue[i]) ?? [])
165
+ if (!distance.has(to)) {
166
+ distance.set(to, distance.get(queue[i]) + 1);
167
+ queue.push(to);
168
+ }
169
+ for (const v of visited)
170
+ if (distance.get(v.id) !== v.depth)
171
+ fail('scope', `Breadth-first depth of ${v.id} is ${distance.get(v.id)} by the reported edges, not ${v.depth}.`, { function: v.id });
172
+ }
173
+ for (const [i, entry] of frontier.entries()) {
174
+ const field = `frontier[${i}]`;
175
+ if (entry.reason === 'depth-limit' && depth.get(String(entry.from)) !== expected.scope.maxDepth)
176
+ fail('scope', `${field}: a depth limit is reached only from depth ${expected.scope.maxDepth}.`);
177
+ if (entry.reason === 'function-limit' && visited.length !== expected.scope.maxFunctions)
178
+ fail('scope', `${field}: a function limit is reached only with ${expected.scope.maxFunctions} visited functions.`);
179
+ }
180
+ string(report.summary, 8000);
181
+ const recommended = array(report.recommended ?? [], discoverLimits.recommended).map((x, i) => discoveredFunction(x, expected.binarySha256, `recommended[${i}]`));
182
+ return { model: { source: String(model.source), revision: String(model.revision) }, visited: visited.length, edges: edges.length, frontier: frontier.length,
183
+ maxDepthReached: Math.max(...visited.map(v => v.depth)), recommended };
184
+ }
57
185
  export function functionIdentity(binarySha, at) {
58
186
  return `fn:${binarySha}:${at.toString(16).padStart(8, '0')}`;
59
187
  }
@@ -1,6 +1,6 @@
1
1
  import { DatabaseSync } from 'node:sqlite';
2
2
  import { type Workspace } from '../workspace.js';
3
- import { type Attachment, type Project, type Snapshot, type Task, type WorkFunction } from './model.js';
3
+ import { type DiscoverScope, type TaskKind, type Attachment, type Project, type Snapshot, type Task, type WorkFunction } from './model.js';
4
4
  export declare const workTableColumns: {
5
5
  readonly projects: readonly ["id", "data"];
6
6
  readonly functions: readonly ["project", "id", "rva", "stage", "data"];
@@ -41,6 +41,7 @@ export declare class WorkStore {
41
41
  private cancelled;
42
42
  private planning;
43
43
  private lease;
44
+ /** `reservations`: the cause concerns reserved packages or resources only, which a discovery never holds. */
44
45
  private invalidateTasks;
45
46
  /**
46
47
  * Only a writer edge reserves its target exclusively. Calls/reads are read dependencies: they are
@@ -114,17 +115,22 @@ export declare class WorkStore {
114
115
  private static needsRework;
115
116
  private static reviewable;
116
117
  private static readonly reworkSql;
117
- plan(projectId: string, expectedRevision: number, count: number, kind: 'reconstruct' | 'review', selected?: string[], afterRva?: number, epoch?: string, excludeAuthor?: string): {
118
+ plan(projectId: string, expectedRevision: number, count: number, kind: TaskKind, selected?: string[], afterRva?: number, epoch?: string, excludeAuthor?: string, discover?: DiscoverScope): {
118
119
  task: Task;
119
120
  revision: number;
120
121
  };
122
+ /**
123
+ * A discovery task reads the call graph around explicit roots and changes no function, so it reserves nothing:
124
+ * reconstruction and review of the same functions continue meanwhile.
125
+ */
126
+ private planDiscovery;
121
127
  claim(taskId: string, worker: string, ttl: number): {
122
128
  task: Task;
123
129
  revision: number;
124
130
  lease: string;
125
131
  };
126
132
  /** Plan and claim one slice atomically at the current state; no observed revision is needed. */
127
- next(projectId: string, worker: string, count: number, kind: 'reconstruct' | 'review', ttl: number, epoch?: string, selected?: string[]): {
133
+ next(projectId: string, worker: string, count: number, kind: TaskKind, ttl: number, epoch?: string, selected?: string[], discover?: DiscoverScope): {
128
134
  task: Task;
129
135
  revision: number;
130
136
  lease: string;
@@ -151,6 +157,15 @@ export declare class WorkStore {
151
157
  revision: number;
152
158
  accepted1to1: boolean;
153
159
  };
160
+ /**
161
+ * Retains the discovery report of a leased discover task and completes it. Function stages and packages are
162
+ * untouched; newly found functions are registered only through an explicit work import.
163
+ */
164
+ submitDiscovery(taskId: string, worker: string, fence: number, report: unknown, artifact: Attachment, epoch?: string): {
165
+ task: Task;
166
+ revision: number;
167
+ accepted1to1: boolean;
168
+ };
154
169
  review(taskId: string, worker: string, fence: number, decisions: {
155
170
  id: string;
156
171
  sourceSha256: string;
@@ -223,6 +238,15 @@ export declare class WorkStore {
223
238
  firstApprovalAt: number | null;
224
239
  };
225
240
  };
241
+ discovery: {
242
+ task: string;
243
+ status: "queued" | "cancelled" | "leased" | "submitted";
244
+ roots: number;
245
+ scope: DiscoverScope | undefined;
246
+ discoverMs: number | null;
247
+ visited: {} | null;
248
+ frontier: {} | null;
249
+ }[];
226
250
  project: {
227
251
  id: string;
228
252
  target: string;
@@ -286,10 +310,17 @@ export declare class WorkStore {
286
310
  complete: boolean;
287
311
  };
288
312
  handoff(taskId: string): {
313
+ project: Project;
314
+ task: Task;
315
+ functions: WorkFunction[];
316
+ discover: DiscoverScope | undefined;
317
+ instructions: string[];
318
+ } | {
289
319
  project: Project;
290
320
  task: Task;
291
321
  functions: WorkFunction[];
292
322
  instructions: string[];
323
+ discover?: undefined;
293
324
  };
294
325
  snapshot(projectId: string, limit?: number): Snapshot;
295
326
  /** Full work metadata only: native contexts/configuration are deliberately outside this snapshot. */
@@ -1,3 +1,4 @@
1
+ import { id as checkedId } from '../model.js';
1
2
  import { timingReport } from './timing.js';
2
3
  import { DatabaseSync } from 'node:sqlite';
3
4
  import { chmodSync, existsSync, lstatSync } from 'node:fs';
@@ -5,7 +6,7 @@ import { join } from 'node:path';
5
6
  import { randomUUID } from 'node:crypto';
6
7
  import { createHash } from 'node:crypto';
7
8
  import { openSync, writeSync, fsyncSync, closeSync, unlinkSync } from 'node:fs';
8
- import { archivedOutcomes, array, definition, digest, fail, leaseToken, identifier, integer, object, passport, sha, stable, string, reviewState } from './model.js';
9
+ import { discoverLimits, discoveryReport, taskKinds, archivedOutcomes, array, definition, digest, fail, leaseToken, identifier, integer, object, passport, sha, stable, string, reviewState } from './model.js';
9
10
  export const workTableColumns = {
10
11
  projects: ['id', 'data'], functions: ['project', 'id', 'rva', 'stage', 'data'], tasks: ['id', 'project', 'status', 'data'],
11
12
  locks: ['project', 'resource', 'task'], events: ['seq', 'project', 'revision', 'kind', 'data'], receipts: ['id', 'result'],
@@ -140,10 +141,12 @@ export class WorkStore {
140
141
  const active = this.db.prepare("SELECT data FROM tasks WHERE status IN ('queued','leased')").all();
141
142
  for (const row of active) {
142
143
  const task = JSON.parse(String(row.data));
144
+ if (task.kind === 'discover')
145
+ continue;
143
146
  const held = new Set(task.resources);
144
147
  const missing = task.functions.filter(fn => this.derivedResources(task.project, fn, 10001).some(key => !held.has(key)));
145
148
  if (missing.length)
146
- this.invalidateTasks(this.project(task.project), 'New writer evidence expanded the reserved scope', new Set(missing));
149
+ this.invalidateTasks(this.project(task.project), 'New writer evidence expanded the reserved scope', new Set(missing), true);
147
150
  }
148
151
  this.db.prepare("INSERT INTO work_metadata VALUES('writer_scope_check','1')").run();
149
152
  }, true);
@@ -213,7 +216,8 @@ export class WorkStore {
213
216
  fail('staleEpoch', 'This epoch belongs to another work incarnation; read a fresh brief.');
214
217
  }
215
218
  cancelled(task) {
216
- fail('taskCancelled', 'Task was cancelled and cannot be resumed; request new work with work next.', { task: task.id, reason: task.result, functions: task.functions, retry: `work next --kind ${task.kind} --functions ${task.functions.join(',')}` });
219
+ fail('taskCancelled', 'Task was cancelled and cannot be resumed; request new work with work next.', { task: task.id, reason: task.result, functions: task.functions, retry: `work next --kind ${task.kind} --functions ${task.functions.join(',')}` + (task.discover ?
220
+ ` --strategy ${task.discover.strategy} --direction ${task.discover.direction} --max-depth ${task.discover.maxDepth} --max-functions ${task.discover.maxFunctions}` : '') });
217
221
  }
218
222
  planning(project, expected, epoch) {
219
223
  this.checkEpoch(project, epoch);
@@ -232,17 +236,22 @@ export class WorkStore {
232
236
  if (task.status !== 'leased' || task.worker !== identifier(worker) || task.fence !== integer(fence, 1, Number.MAX_SAFE_INTEGER)
233
237
  || task.leaseUntil <= this.clock())
234
238
  fail('staleLease', 'Lease is expired, reclaimed or belongs to another worker.');
235
- for (const id of task.functions)
236
- if (this.function(task.project, id).version !== task.versions[id])
237
- fail('staleFunction', 'Assigned function changed since planning; preserve work and re-plan.');
239
+ // A discovery changes no function: reconstruction of its roots meanwhile does not make it stale.
240
+ if (task.kind !== 'discover')
241
+ for (const id of task.functions)
242
+ if (this.function(task.project, id).version !== task.versions[id])
243
+ fail('staleFunction', 'Assigned function changed since planning; preserve work and re-plan.');
238
244
  return task;
239
245
  }
240
- invalidateTasks(project, reason, functionIds) {
246
+ /** `reservations`: the cause concerns reserved packages or resources only, which a discovery never holds. */
247
+ invalidateTasks(project, reason, functionIds, reservations = false) {
241
248
  const ids = [];
242
249
  for (const row of this.db.prepare("SELECT data FROM tasks WHERE project=? AND status IN ('queued','leased') ORDER BY id").all(project.id)) {
243
250
  const task = JSON.parse(String(row.data));
244
251
  if (functionIds && !task.functions.some(id => functionIds.has(id)))
245
252
  continue;
253
+ if (reservations && task.kind === 'discover')
254
+ continue;
246
255
  const previous = { ...task };
247
256
  task.status = 'cancelled';
248
257
  task.fence = integer(task.fence + 1, 1, Number.MAX_SAFE_INTEGER);
@@ -396,7 +405,7 @@ export class WorkStore {
396
405
  }
397
406
  }
398
407
  create(projectId, targetId, name) {
399
- const id = identifier(projectId), target = this.workspace.target(targetId);
408
+ const id = identifier(projectId), target = this.workspace.target(checkedId(targetId, '--target'));
400
409
  if (this.db.prepare('SELECT 1 FROM projects WHERE id=?').get(id))
401
410
  fail('conflict', 'Project ID already exists.');
402
411
  const project = { id, target: target.id, binarySha256: target.binarySha256, name: string(name), revision: 1, planningRevision: 1, epoch: this.incarnation,
@@ -453,14 +462,18 @@ export class WorkStore {
453
462
  }
454
463
  static reworkSql = `(stage IN ('discovered','mismatch') OR stage='partial' AND (json_extract(data,'$.source') IS NULL
455
464
  OR json_extract(data,'$.invalidated') IS NOT NULL OR json_extract(data,'$.review.approved')=0))`;
456
- plan(projectId, expectedRevision, count, kind, selected, afterRva = -1, epoch, excludeAuthor) {
465
+ plan(projectId, expectedRevision, count, kind, selected, afterRva = -1, epoch, excludeAuthor, discover) {
457
466
  const project = this.project(projectId);
458
467
  this.planning(project, expectedRevision, epoch);
459
468
  count = integer(count, 1, 50);
460
- if (!['reconstruct', 'review'].includes(kind))
461
- fail('invalid', 'Task kind is reconstruct or review.');
469
+ if (!taskKinds.includes(kind))
470
+ fail('invalid', 'Task kind is reconstruct, review or discover.');
462
471
  if (selected && (!selected.length || selected.length > count || new Set(selected).size !== selected.length))
463
472
  fail('scope', 'Explicit function selection must contain 1..count unique IDs.');
473
+ if (kind === 'discover')
474
+ return this.planDiscovery(project, selected, discover);
475
+ if (discover)
476
+ fail('invalid', 'Traversal options apply only to --kind discover.');
464
477
  // Explicit reconstruct selection may rework any package that is not reviewed/reconstructed;
465
478
  // automatic selection serves new functions first, then packages that need rework.
466
479
  const eligible = (fn) => kind === 'review' ? WorkStore.reviewable(fn)
@@ -547,6 +560,25 @@ export class WorkStore {
547
560
  this.event(project, 'task.planned', { task });
548
561
  return { task, revision: project.revision };
549
562
  }
563
+ /**
564
+ * A discovery task reads the call graph around explicit roots and changes no function, so it reserves nothing:
565
+ * reconstruction and review of the same functions continue meanwhile.
566
+ */
567
+ planDiscovery(project, roots, scope) {
568
+ if (!roots)
569
+ fail('invalid', 'Discovery needs explicit root function IDs: --functions.');
570
+ if (!scope)
571
+ fail('invalid', 'Discovery needs its traversal scope.');
572
+ if (roots.length > scope.maxFunctions)
573
+ fail('scope', 'Every root is visited: --max-functions must be at least the number of roots.');
574
+ const functions = roots.map(id => this.function(project.id, id));
575
+ const task = { id: 'w_' + randomUUID(), project: project.id, kind: 'discover', status: 'queued',
576
+ functions: functions.map(f => f.id), versions: Object.fromEntries(functions.map(f => [f.id, f.version])),
577
+ resources: [], fence: 0, leaseUntil: 0, createdAt: this.clock(), epoch: project.epoch, discover: scope };
578
+ this.db.prepare('INSERT INTO tasks VALUES(?,?,?,?)').run(task.id, project.id, task.status, stable(task));
579
+ this.event(project, 'task.planned', { task });
580
+ return { task, revision: project.revision };
581
+ }
550
582
  claim(taskId, worker, ttl) {
551
583
  const task = this.task(taskId), project = this.project(task.project);
552
584
  worker = identifier(worker);
@@ -557,9 +589,10 @@ export class WorkStore {
557
589
  fail('alreadyClaimed', 'Task is submitted or has an active lease.');
558
590
  if (task.kind === 'review' && task.functions.some(id => this.function(task.project, id).author === worker))
559
591
  fail('selfReview', 'Reviewer must differ from every reconstruction author in this slice.');
560
- for (const id of task.functions)
561
- if (this.function(task.project, id).version !== task.versions[id])
562
- fail('staleFunction', 'Task inputs changed. Cancel this reservation and plan a fresh task.');
592
+ if (task.kind !== 'discover')
593
+ for (const id of task.functions)
594
+ if (this.function(task.project, id).version !== task.versions[id])
595
+ fail('staleFunction', 'Task inputs changed. Cancel this reservation and plan a fresh task.');
563
596
  task.status = 'leased';
564
597
  task.worker = worker;
565
598
  task.fence = integer(task.fence + 1, 1, Number.MAX_SAFE_INTEGER);
@@ -569,7 +602,7 @@ export class WorkStore {
569
602
  return { task, revision: project.revision, lease: leaseToken(task) };
570
603
  }
571
604
  /** Plan and claim one slice atomically at the current state; no observed revision is needed. */
572
- next(projectId, worker, count, kind, ttl, epoch, selected) {
605
+ next(projectId, worker, count, kind, ttl, epoch, selected, discover) {
573
606
  const project = this.project(projectId);
574
607
  worker = identifier(worker);
575
608
  if (selected)
@@ -579,7 +612,7 @@ export class WorkStore {
579
612
  for (const id of selected)
580
613
  if (!WorkStore.needsRework(this.function(project.id, id)))
581
614
  fail('conflict', 'Function no longer needs rework (already resubmitted or awaiting review); take plain work next.', { function: id });
582
- const planned = this.plan(project.id, project.revision, count, kind, selected, -1, epoch, worker);
615
+ const planned = this.plan(project.id, project.revision, count, kind, selected, -1, epoch, worker, discover);
583
616
  return this.claim(planned.task.id, worker, ttl);
584
617
  }
585
618
  heartbeat(taskId, worker, fence, ttl, epoch) {
@@ -615,7 +648,7 @@ export class WorkStore {
615
648
  submit(taskId, worker, fence, entries, epoch) {
616
649
  const task = this.lease(taskId, worker, fence, epoch), project = this.project(task.project);
617
650
  if (task.kind !== 'reconstruct')
618
- fail('invalid', 'Use review for a review assignment.');
651
+ fail('invalid', task.kind === 'review' ? 'Use review for a review assignment.' : 'A discover assignment takes a discovery report.');
619
652
  if (entries.length !== task.functions.length || new Set(entries.map(e => e.id)).size !== entries.length
620
653
  || entries.some(e => !task.functions.includes(e.id)))
621
654
  fail('scope', 'Submission must cover exactly the assigned slice.');
@@ -642,6 +675,24 @@ export class WorkStore {
642
675
  this.event(project, 'reconstruction.submitted', { task: task.id, worker, functions: entries.map(e => e.id) });
643
676
  return { task, revision: project.revision, accepted1to1: false };
644
677
  }
678
+ /**
679
+ * Retains the discovery report of a leased discover task and completes it. Function stages and packages are
680
+ * untouched; newly found functions are registered only through an explicit work import.
681
+ */
682
+ submitDiscovery(taskId, worker, fence, report, artifact, epoch) {
683
+ const task = this.lease(taskId, worker, fence, epoch), project = this.project(task.project);
684
+ if (task.kind !== 'discover' || !task.discover)
685
+ fail('invalid', 'Only a discover assignment takes a discovery report.');
686
+ if (integer(artifact.size, 1, Number.MAX_SAFE_INTEGER) > discoverLimits.reportBytes)
687
+ fail('limit', `A discovery report is at most ${discoverLimits.reportBytes} bytes.`);
688
+ const summary = discoveryReport(report, { task: task.id, binarySha256: project.binarySha256, roots: task.functions, scope: task.discover });
689
+ task.status = 'submitted';
690
+ task.leaseUntil = 0;
691
+ task.result = { report: artifact, ...summary, submittedAt: this.clock(), accepted1to1: false };
692
+ this.putTask(task);
693
+ this.event(project, 'discovery.submitted', { task: task.id, worker, report: artifact.sha256, visited: summary.visited, edges: summary.edges, frontier: summary.frontier });
694
+ return { task, revision: project.revision, accepted1to1: false };
695
+ }
645
696
  review(taskId, worker, fence, decisions, epoch) {
646
697
  const task = this.lease(taskId, worker, fence, epoch), project = this.project(task.project);
647
698
  if (task.kind !== 'review')
@@ -789,7 +840,7 @@ export class WorkStore {
789
840
  // assignments that froze those packages are cancelled. Nodes and rejected edges invalidate nothing.
790
841
  const invalidated = affected.size ? this.invalidatePackages(project, 'Dependency graph changed at this function', affected) : new Set();
791
842
  const replan = new Set([...invalidated, ...expanded]);
792
- const cancelled = replan.size ? this.invalidateTasks(project, 'Dependency evidence changed the package or its exclusive reservations', replan) : [];
843
+ const cancelled = replan.size ? this.invalidateTasks(project, 'Dependency evidence changed the package or its exclusive reservations', replan, true) : [];
793
844
  // Counts are exact; ID lists are bounded to the first 100 and say so.
794
845
  const ids = (values) => { const all = [...values].sort(); return { ids: all.slice(0, 100), truncated: all.length > 100 }; };
795
846
  const impact = { affectedFunctionIds: ids(affected), invalidatedPackageIds: ids(invalidated), cancelledTaskIds: ids(cancelled) };
@@ -906,6 +957,12 @@ export class WorkStore {
906
957
  handoff(taskId) {
907
958
  return this.tx(() => {
908
959
  const task = this.task(taskId), project = this.project(task.project);
960
+ if (task.kind === 'discover')
961
+ return { project, task, functions: task.functions.map(id => this.function(project.id, id)), discover: task.discover,
962
+ instructions: ['Walk the call graph from these roots yourself, through Ghidra xrefs or a pinned graph inventory, within discover.',
963
+ 'Visit each function once (module hash + RVA); roots are depth 0. Record calls you cannot resolve or that leave the depth/function limit as frontier.',
964
+ 'State for every visited function where its xrefs came from and whether that observation was complete: empty xrefs do not prove no calls.',
965
+ 'Submit one discovery-report with work submit. Register new functions only with work import. Another scope or strategy is a new task.'] };
909
966
  return { project, task, functions: task.functions.map(id => this.function(project.id, id)),
910
967
  instructions: ['Reconstruct only this assigned slice. Do not implement game/subsystems.',
911
968
  'Preserve ABI, exact effects, errors, ordering, unknowns and source evidence.',
@@ -23,4 +23,13 @@ export declare function timingReport(db: DatabaseSync, project: string, selected
23
23
  firstApprovalAt: number | null;
24
24
  };
25
25
  };
26
+ discovery: {
27
+ task: string;
28
+ status: "queued" | "cancelled" | "leased" | "submitted";
29
+ roots: number;
30
+ scope: import("./model.js").DiscoverScope | undefined;
31
+ discoverMs: number | null;
32
+ visited: {} | null;
33
+ frontier: {} | null;
34
+ }[];
26
35
  };
@@ -76,5 +76,14 @@ export function timingReport(db, project, selected) {
76
76
  byFunction.set(row.function, summary);
77
77
  }
78
78
  const queue = db.prepare("SELECT json_extract(data,'$.kind') AS kind,status,count(*) AS count FROM tasks WHERE project=? AND status IN ('queued','leased') GROUP BY kind,status ORDER BY kind,status").all(project);
79
- return { rows, queue, selectedTasks: authors.length, batchToDecisionMs: complete ? elapsed(start, end) : null, byFunction: Object.fromEntries(byFunction) };
79
+ // Discovery is timed on its own: it has no review and changes no function. Its claim comes from the indexed events
80
+ // above (the predicate stays equal to the partial index); its end is the time retained with its report.
81
+ const discovery = db.prepare("SELECT data FROM tasks WHERE project=? AND json_extract(data,'$.kind')='discover' ORDER BY rowid DESC LIMIT 10")
82
+ .all(project).reverse().map(row => {
83
+ const task = JSON.parse(String(row.data)), clock = taskClock(task.id), result = (task.result ?? {});
84
+ const submittedAt = typeof result.submittedAt === 'number' ? result.submittedAt : undefined;
85
+ return { task: task.id, status: task.status, roots: task.functions.length, scope: task.discover, discoverMs: elapsed(clock.claim, submittedAt),
86
+ visited: result.visited ?? null, frontier: result.frontier ?? null };
87
+ });
88
+ return { rows, queue, selectedTasks: authors.length, batchToDecisionMs: complete ? elapsed(start, end) : null, byFunction: Object.fromEntries(byFunction), discovery };
80
89
  }