@jacebenson/jsn 5.5.10-dev.234.1 → 5.5.10-dev.236.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.5.10-dev.234.1",
3
+ "version": "5.5.10-dev.236.1",
4
4
  "description": "A command-line interface for ServiceNow that follows the Unix philosophy: simple, composable, and scriptable.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -312,7 +312,7 @@ export class LocalCLI {
312
312
  * help page. Machine discovery leaves it out, so the JSON schema and bytes
313
313
  * stay unchanged.
314
314
  */
315
- commandRegistry({ summaries = false, shallow = false } = {}) {
315
+ commandRegistry({ summaries = false, shallow = false, details = false } = {}) {
316
316
  const visible = (node) => !node.definition.hidden;
317
317
  const serialize = (node) => {
318
318
  if (!shallow) node.build();
@@ -333,7 +333,7 @@ export class LocalCLI {
333
333
  if (summaries) entry.summary = node.definition.summary || '';
334
334
  return entry;
335
335
  };
336
- return {
336
+ const registry = {
337
337
  commands: this.root.children.filter(visible).map(serialize),
338
338
  options: [...this.root.options.values()].map((spec) => ({
339
339
  name: spec.name,
@@ -343,6 +343,49 @@ export class LocalCLI {
343
343
  type: spec.type || 'boolean',
344
344
  })),
345
345
  };
346
+ // Opt-in action detail leaves the legacy command/group projection intact.
347
+ // Build every visible descendant, using the same option inheritance and
348
+ // signatures as dispatch. Hidden subtrees are never indexed.
349
+ if (details) {
350
+ registry.entries = [];
351
+ const visit = (node, ancestors = [], aliases = []) => {
352
+ if (!visible(node)) return;
353
+ // Dispatch resolves names as literal tokens, not positional patterns.
354
+ // A positional-headed declaration cannot yield a fixed canonical path
355
+ // after placeholder substitution. Keep it only in the legacy projection.
356
+ if (positionSpec(node.name).length) return;
357
+ node.build();
358
+ const nodes = [...ancestors, node];
359
+ const path = nodes.map(value => value.name);
360
+ const bindings = this._optionConfig(nodes);
361
+ const allOptions = [...new Set(bindings.values())];
362
+ const options = allOptions.filter(spec => !spec.hidden).map(spec => {
363
+ // An inherited alias can now belong to a different, hidden option.
364
+ // Advertise only tokens that still resolve to this visible spec.
365
+ const tokens = [...bindings].filter(([_name, bound]) => bound === spec).map(([name]) => name);
366
+ return { ...spec, token: tokens.includes(spec.name) ? spec.name : tokens[0],
367
+ alias: tokens.filter(name => name !== spec.name) };
368
+ });
369
+ const positions = positionSpec(node.definition.command || '').map(position => ({
370
+ ...position, ...node.positionals.get(position.name), name: position.name,
371
+ }));
372
+ registry.entries.push({
373
+ path, aliases: [...aliases, ...node.aliases],
374
+ description: node.definition.describe || '',
375
+ group: nodes[0].definition.describe || '',
376
+ table: nodes[0].definition.discovery?.table || '',
377
+ help: `jsn ${path.join(' ')} --help`,
378
+ parent: node.children.some(visible),
379
+ options, positions,
380
+ hiddenRequired: allOptions.some(spec => spec.hidden && spec.demandOption),
381
+ tasks: node.definition.discoveryTasks || [],
382
+ examples: node.definition.examples || [],
383
+ });
384
+ for (const child of node.children) visit(child, nodes, [...aliases, ...node.aliases]);
385
+ };
386
+ for (const node of this.root.children) visit(node);
387
+ }
388
+ return registry;
346
389
  }
347
390
 
348
391
  /** Structured child signatures for a parent node, built on demand. */
package/src/cli.js CHANGED
@@ -458,7 +458,7 @@ export function buildCLI() {
458
458
  .command(versionCmd(wrap))
459
459
  .command(upgradeCmd(wrap))
460
460
  .command(documentCmd(wrap))
461
- .command(discoverCmd(wrap, (argv) => visibleCommandRegistry(cliInstance.commandRegistry(), app.config, argv)))
461
+ .command(discoverCmd(wrap, (argv) => visibleCommandRegistry(cliInstance.commandRegistry({ details: true }), app.config, argv)))
462
462
  .demandCommand(1, 'You must specify a command')
463
463
  .onParentDiscovery((argv, { path, subcommands }) => {
464
464
  // Reached only for a parent command that declares no default handler of
@@ -34,5 +34,7 @@ export function commandAudience(config, { instance, allCommands = false } = {})
34
34
 
35
35
  export function visibleCommandRegistry(registry, config, options = {}) {
36
36
  if (commandAudience(config, options) !== 'basic') return registry;
37
- return { ...registry, commands: registry.commands.filter(command => BASIC_COMMANDS.has(command.name)) };
37
+ return { ...registry, commands: registry.commands.filter(command => BASIC_COMMANDS.has(command.name)),
38
+ ...(registry.entries ? { entries: registry.entries.filter(entry => BASIC_COMMANDS.has(entry.path[0])) } : {}),
39
+ };
38
40
  }
@@ -1277,6 +1277,12 @@ export function authCmd(wrap) {
1277
1277
  .command({
1278
1278
  command: 'status',
1279
1279
  describe: 'Show authentication status (use --details for users and instance URLs)',
1280
+ discoveryTasks: [{
1281
+ phrases: ['current update set', 'selected scope', 'capture context', 'current capture context', 'current scope', 'current application scope', 'active scope', 'selected application scope', 'active update set', 'selected update set', 'capture set', 'which scope am I in'],
1282
+ args: ['--context', '--json'],
1283
+ description: 'Read the selected profile context, including scope and current capture update set; does not select or change them',
1284
+ }],
1285
+ examples: [{ args: ['--context', '--json'], description: 'Inspect the selected scope and capture update set' }],
1280
1286
  builder: sub => sub.option('local', {
1281
1287
  type: 'boolean', describe: 'Show saved credential state without contacting any instance',
1282
1288
  }).option('context', {
@@ -16,6 +16,95 @@ export function discoverCommands(registry, { query = '', table = '' } = {}) {
16
16
  });
17
17
  }
18
18
 
19
+ const normalize = text => String(text).toLowerCase().replace(/[^a-z0-9_]+/g, ' ').trim();
20
+ const filler = new Set(['a', 'an', 'the', 'my', 'is', 'are', 'what', 'which', 'show', 'me', 'please', 'for', 'of', 'to']);
21
+ const quote = value => /^[a-zA-Z0-9_./:<>=-]+$/.test(value) && !value.includes('=<') ? value : `'${value.replaceAll("'", "'\\''")}'`;
22
+
23
+ // Task/example args are argv tokens owned by that action, never shell code.
24
+ // Fill only parser-declared required inputs, and reject stale/hidden flags.
25
+ function invocationArgs(entry, suffix) {
26
+ if (entry.parent) return suffix.length ? null : [...entry.path, '--help'];
27
+ if (entry.hiddenRequired) return null;
28
+ const options = new Map(entry.options.flatMap(spec => [spec.token || spec.name, ...(Array.isArray(spec.alias) ? spec.alias : spec.alias ? [spec.alias] : [])].map(name => [name, spec])));
29
+ const positional = [], flags = [], supplied = new Set();
30
+ for (let i = 0; i < suffix.length; i++) {
31
+ const token = suffix[i];
32
+ if (!token.startsWith('-')) { positional.push(token); continue; }
33
+ // Long options require --; the parser treats -mode as short bundles.
34
+ if (!token.startsWith('--') && !/^-[^-](?:=|$)/.test(token)) return null;
35
+ const name = token.replace(/^-+/, '').split('=')[0];
36
+ const spec = options.get(name) || (name.startsWith('no-') && options.get(name.slice(3))?.type === 'boolean' ? options.get(name.slice(3)) : null);
37
+ if (!spec) return null;
38
+ supplied.add(spec.name);
39
+ flags.push(token);
40
+ let value = token.includes('=') ? token.slice(token.indexOf('=') + 1) : undefined;
41
+ if (spec.type && spec.type !== 'boolean' && value === undefined) {
42
+ value = suffix[++i];
43
+ if (value === undefined || value.startsWith('--')) return null;
44
+ flags.push(value);
45
+ }
46
+ if (value !== undefined && !value.includes('<')) {
47
+ if (spec.choices && !spec.choices.includes(value)) return null;
48
+ if (spec.type === 'number' && (value === '' || !Number.isFinite(Number(value)))) return null;
49
+ if (spec.type === 'boolean' && !['true', 'false'].includes(value)) return null;
50
+ }
51
+ }
52
+ for (const position of entry.positions.slice(positional.length)) {
53
+ if (position.required) positional.push(`<${position.name}>`);
54
+ }
55
+ for (const spec of entry.options) {
56
+ if (spec.demandOption && !supplied.has(spec.name)) {
57
+ flags.push(`--${spec.token || spec.name}`);
58
+ if (spec.type !== 'boolean') flags.push(`<${spec.name}>`);
59
+ }
60
+ }
61
+ return [...entry.path, ...positional, ...flags];
62
+ }
63
+
64
+ export function rankedDiscoveries(registry, { query = '', table = '', limit = 5 } = {}) {
65
+ const normalized = normalize(query);
66
+ const words = normalized.split(' ').filter(word => word && !filler.has(word));
67
+ const matches = text => words.length > 0 && words.every(word => normalize(text).includes(word));
68
+ const candidates = [];
69
+ for (const entry of registry.entries || []) {
70
+ if (table && entry.table !== table) continue;
71
+ const add = (score, suffix, description, match) => {
72
+ const args = invocationArgs(entry, suffix);
73
+ if (!args) return;
74
+ const invocation = `jsn ${args.map(quote).join(' ')}`;
75
+ candidates.push({ score, invocation, args, description, help: entry.help, match,
76
+ required: [...new Set(args.flatMap(arg => arg.match(/<[^>]+>/g) || []))],
77
+ });
78
+ };
79
+ if (!normalized) {
80
+ if (entry.path.length === 1) add(1, [], entry.description, 'group');
81
+ continue;
82
+ }
83
+ for (const task of entry.tasks) {
84
+ const exact = task.phrases.some(phrase => normalize(phrase) === normalized);
85
+ if (!task.hidden && (exact || task.phrases.some(matches))) add(exact ? 400 : 350, task.args || [], task.description, 'task');
86
+ }
87
+ for (const example of entry.examples) {
88
+ if (!example.hidden && matches(`${example.description} ${(example.args || []).join(' ')}`)) {
89
+ add(275, example.args || [], example.description, 'example');
90
+ }
91
+ }
92
+ if (!entry.parent) for (const option of entry.options) {
93
+ if (matches(`${option.name} ${[].concat(option.alias || []).join(' ')} ${option.describe || option.description || ''}`)) {
94
+ add(250, [`--${option.token || option.name}`, ...(option.type && option.type !== 'boolean' ? [`<${option.name}>`] : [])],
95
+ option.describe || option.description || entry.description, 'option');
96
+ }
97
+ }
98
+ if (matches(`${entry.path.join(' ')} ${entry.aliases.join(' ')} ${entry.description}`)) {
99
+ add(entry.parent ? 100 : 200, [], entry.description, entry.parent ? 'group' : 'action');
100
+ } else if (matches(`${entry.group} ${entry.table}`)) add(50, [], entry.description, 'group');
101
+ }
102
+ candidates.sort((a, b) => b.score - a.score || (a.invocation < b.invocation ? -1 : a.invocation > b.invocation ? 1 : 0));
103
+ const seen = new Set();
104
+ return candidates.filter(result => !seen.has(result.invocation) && seen.add(result.invocation))
105
+ .slice(0, limit).map(({ score: _score, ...result }) => result);
106
+ }
107
+
19
108
  export function discoverCmd(wrap, getRegistry) {
20
109
  return {
21
110
  command: 'discover [query]',
@@ -32,12 +121,23 @@ export function discoverCmd(wrap, getRegistry) {
32
121
  ' Rich request views (attachments and variables): jsn requests show --help',
33
122
  ' Raw endpoints when needed: jsn rest --help',
34
123
  'Generic records supports any accessible table; specialized commands provide configured defaults and table-specific behavior.',
35
- 'Discovery matches registered text; try fewer words if there are no matches.',
36
- 'Use --json for structured results or --json --get data.commands for only matches.',
124
+ 'Ranked suggestions use local task phrases, action/option help and registered examples; exact task phrases rank first, with stable ties and at most 5 results.',
125
+ 'Suggestions never run commands. Replace every <placeholder> before use; discovery does not infer record IDs or authorize writes.',
126
+ 'Compatibility: data.commands retains legacy unranked group matching unchanged. Additive data.results contains ranked action suggestions.',
127
+ 'Use --json --get data.results for ranked suggestions, or --json --get data.commands for legacy matches.',
37
128
  ].join('\n')),
38
129
  handler: wrap(async (argv, app) => {
39
- const commands = discoverCommands(getRegistry(argv), { query: argv.query, table: argv.table });
40
- const lines = commands.flatMap(command => [
130
+ const registry = getRegistry(argv);
131
+ const search = { query: argv.query, table: argv.table };
132
+ const commands = discoverCommands(registry, search);
133
+ const results = rankedDiscoveries(registry, search);
134
+ const lines = results.flatMap(result => [
135
+ result.invocation,
136
+ ` ${result.description}`,
137
+ ` Help: ${result.help}${result.required.length ? `; required: ${result.required.join(', ')}` : ''}`,
138
+ ]);
139
+ // Exact-table discovery keeps its existing configured-view details.
140
+ if (argv.table) lines.push(...commands.flatMap(command => [
41
141
  `${command.name}: ${command.description}`,
42
142
  ...(command.discovery ? [
43
143
  ` Table: ${command.discovery.table}; default columns: ${command.discovery.defaultColumns.join(', ')}`,
@@ -45,10 +145,10 @@ export function discoverCmd(wrap, getRegistry) {
45
145
  ] : []),
46
146
  ` ${command.help}`,
47
147
  ...(command.actions || []).map(action => ` ${action.help} — ${action.description}`),
48
- ]);
49
- if (!commands.length) lines.push('No registered matches. Try fewer words or use generic records for any accessible table: jsn records list --help');
50
- app.ok({ commands, _formatted: lines.join('\n') }, {
51
- summary: `${commands.length} matching command(s). Use jsn discover --help for guidance by intent.`,
148
+ ]));
149
+ if (!lines.length) lines.push('No registered matches. Try fewer words or use generic records for any accessible table: jsn records list --help');
150
+ app.ok({ commands, results, _formatted: lines.join('\n') }, {
151
+ summary: `${results.length} ranked suggestion(s); ${commands.length} legacy matching command(s). Use jsn discover --help for guidance by intent.`,
52
152
  });
53
153
  }),
54
154
  };
@@ -638,6 +638,10 @@ export function recordsCmd(wrap) {
638
638
  command: 'inspect <table> <identifier>',
639
639
  aliases: ['debug', 'diag'],
640
640
  describe: 'Inspect a record: show audit history, business rules, and running flows',
641
+ discoveryTasks: [{
642
+ phrases: ['record history', 'audit history', 'record changes', 'show record history', 'who changed a record'],
643
+ args: ['--json'], description: 'Inspect audit history for the specified table and record',
644
+ }],
641
645
  builder: (y) => y
642
646
  .positional('table', { describe: 'Table name (e.g. incident)', type: 'string' })
643
647
  .positional('identifier', { describe: 'Record sys_id or number', type: 'string' }),
@@ -13,9 +13,12 @@ declareCapabilities('scan', { mutationSubcommands: [
13
13
  ] });
14
14
 
15
15
  const hint = (action, cmd, description) => ({ action, cmd, description });
16
- function report(app, argv, data, options) {
17
- const connection = argv.profile ? ` --profile ${quoteShellArg(argv.profile)}`
16
+ function connectionSuffix(argv) {
17
+ return argv.profile ? ` --profile ${quoteShellArg(argv.profile)}`
18
18
  : argv.instance ? ` --instance ${quoteShellArg(argv.instance)}` : '';
19
+ }
20
+ function report(app, argv, data, options) {
21
+ const connection = connectionSuffix(argv);
19
22
  app.ok(data, { ...options, breadcrumbs: options.breadcrumbs.map(item => ({ ...item, cmd: item.cmd + connection })) });
20
23
  }
21
24
  const rootHints = () => [hint('checks', 'jsn scan checks list', 'Browse available checks'),
@@ -32,6 +35,18 @@ const itemHints = (group, record) => {
32
35
  hint('delete', `jsn scan ${group} delete ${id}`, 'Delete this definition after confirmation')];
33
36
  };
34
37
 
38
+ // Structured recovery for a dispatched scan whose progress or results cannot be
39
+ // read. It records what was started so an operator can inspect it; resubmission
40
+ // is never recommended because the original execution may still be running.
41
+ function recoveryTarget(target = {}) {
42
+ return { kind: target.kind,
43
+ ...(target.sys_id ? { sys_id: target.sys_id } : {}),
44
+ ...(target.table ? { table: target.table } : {}),
45
+ ...(target.name ? { name: target.name } : {}),
46
+ ...(target.execution_id ? { execution_id: target.execution_id } : {}),
47
+ ...(target.combo_id ? { combo_id: target.combo_id } : {}) };
48
+ }
49
+
35
50
  function executionHints(data) {
36
51
  const id = data.execution_id;
37
52
  return [hint('status', `jsn scan status ${id}`, 'Read execution progress'),
@@ -188,6 +203,7 @@ export function scanCmd(wrap) {
188
203
  await confirmDelete(app, argv, `Start scan of ${plan.target.kind} ${plan.target.name || plan.target.sys_id || plan.target.execution_id || 'the full instance'}${plan.suite_id ? ` using suite ${plan.suite_id}` : ''}?`);
189
204
  const scheduled = await startScan(app.sdk, plan);
190
205
  let data = { ...scheduled, status: 'scheduled', terminal: false };
206
+ let phase = 'progress';
191
207
  if (argv.wait) {
192
208
  try {
193
209
  const deadline = Date.now() + argv.timeout * 1000;
@@ -199,12 +215,24 @@ export function scanCmd(wrap) {
199
215
  // The processor can return before its execution tracker is visible.
200
216
  data = { ...scheduled, status: 'scheduled', terminal: false };
201
217
  }
202
- if (data.terminal) { data = { ...scheduled, ...await scanResults(app.sdk, scheduled.execution_id) }; break; }
218
+ if (data.terminal) { phase = 'results'; data = { ...scheduled, ...await scanResults(app.sdk, scheduled.execution_id) }; break; }
203
219
  await new Promise(resolve => setTimeout(resolve, Math.min(2000, Math.max(0, deadline - Date.now()))));
204
220
  }
205
221
  if (!data.terminal) data.wait_timed_out = true;
206
222
  } catch (error) {
207
- throw errAPI(error.status || 0, `Scan ${scheduled.execution_id} was scheduled, but progress could not be read: ${error.message}. Use jsn scan status ${scheduled.execution_id}; do not resubmit automatically.`);
223
+ const id = scheduled.execution_id;
224
+ const connection = connectionSuffix(argv);
225
+ const statusCommand = `jsn scan status ${id}${connection}`;
226
+ // Provider errors may contain credentials or request payloads.
227
+ const wrapped = errAPI(error.status || 0, `Scan ${id} was scheduled, but ${phase} could not be read. Use ${statusCommand}; do not resubmit automatically.`);
228
+ // errAPI replaces the message for 401/403, so the dispatched id and
229
+ // the no-resubmit warning must also survive in the hint.
230
+ wrapped.hint = [wrapped.hint, `Scan ${id} was already dispatched; inspect it with "${statusCommand}" and do not resubmit automatically.`].filter(Boolean).join(' ');
231
+ wrapped.recovery = { execution_id: id, via: scheduled.via, phase,
232
+ target: recoveryTarget(plan.target), suite_id: scheduled.suite_id ?? null, status: 'unverified',
233
+ status_command: statusCommand,
234
+ results_command: `jsn scan results ${id}${connection}`, resubmit: 'forbidden' };
235
+ throw wrapped;
208
236
  }
209
237
  }
210
238
  const breadcrumbs = executionHints(data);
@@ -220,7 +248,14 @@ export function scanCmd(wrap) {
220
248
  builder: p => p.option('limit', { type: 'number', default: 50, describe: 'Maximum findings/check rows (1–200); truncation is reported' }),
221
249
  handler: wrap(async (argv, app) => {
222
250
  const data = await scanResults(app.sdk, argv.id, boundedLimit(argv.limit));
223
- report(app, argv, data, { summary: `Scan ${data.status}; ${data.findings_count ?? 'unknown'} findings; ${data.checks_executed ?? 'unknown'} recorded check executions${data.incomplete ? '; incomplete data' : ''}`, breadcrumbs: executionHints(data) });
251
+ const findings = data.findings_state === 'unretrieved'
252
+ ? `findings unretrieved (${data.findings_count} reported, 0 rows returned)`
253
+ : data.findings_state === 'mismatch'
254
+ ? `findings mismatch (${data.findings_count} reported, ${data.findings_retrieved} retrieved)`
255
+ : data.findings_state === 'truncated'
256
+ ? `findings truncated (${data.findings_retrieved} retrieved; count not reconciled)`
257
+ : `${data.findings_count ?? 'unknown'} findings`;
258
+ report(app, argv, data, { summary: `Scan ${data.status}; ${findings}; ${data.checks_executed ?? 'unknown'} recorded check executions${data.incomplete ? '; incomplete data' : ''}`, breadcrumbs: executionHints(data) });
224
259
  }) })
225
260
  .command({ command: 'cancel <id>', describe: 'Request cancellation of this scan after confirmation',
226
261
  handler: wrap(async (argv, app) => {
@@ -26,6 +26,11 @@ export function withTableBehavior(command, wrap) {
26
26
  command: 'behavior <table>',
27
27
  aliases: ['behaviour'],
28
28
  describe: 'Read-only inventory of tables behavior: rules, scripts, actions, policies, dictionary, notifications, ACLs, styles, views and flow triggers (inherited included)',
29
+ discoveryTasks: [{
30
+ phrases: ['inherited business rules', 'inherited rules', 'parent table business rules', 'business rules from ancestors'],
31
+ args: ['--category', 'business_rules', '--json'],
32
+ description: 'List business rules for the specified table, including inherited rules by default',
33
+ }],
29
34
  builder: (y) => y
30
35
  .positional('table', { type: 'string', describe: 'Table name (e.g. incident)' })
31
36
  .option('category', {
@@ -92,6 +92,11 @@ export function ticketsCmd(wrap) {
92
92
  .command({
93
93
  command: 'update <number>',
94
94
  describe: 'Update a ticket',
95
+ discoveryTasks: [{
96
+ phrases: ['write work note', 'write work notes', 'add work note', 'add work notes', 'append work notes', 'write a work note', 'add internal note'],
97
+ args: ['--field', 'work_notes=<text>', '--json'],
98
+ description: 'Write a work note to the specified ticket; replace the required number and text placeholders',
99
+ }],
95
100
  builder: (y) => recordOptions(y, false)
96
101
  .option('data', { type: 'string', describe: 'JSON fields' })
97
102
  .option('data-file', { type: 'string', describe: 'Read JSON payload from file' })
package/src/scan.js CHANGED
@@ -100,6 +100,34 @@ export async function scanAjax(sdk, method, parameters) {
100
100
  }
101
101
 
102
102
  const TERMINAL = new Set(['successful', 'failed', 'cancelled']);
103
+ // Execution tracker types that belong to Instance Scan. Exact matches only:
104
+ // no aliases or prefix matching, so unrelated trackers cannot be read as scans.
105
+ const SCAN_TRACKER_TYPES = new Set(['instance_scan', 'point_scan']);
106
+
107
+ // Read the execution back-reference from a result row without guessing: a
108
+ // non-empty value that is not a full sys_id is still "present, but not ours".
109
+ // Strings are checked by type so the legacy String.prototype.link is never read
110
+ // as a reference.
111
+ function hasResultBackReference(value) {
112
+ if (typeof value === 'string') return value !== '';
113
+ if (typeof value === 'object' && value !== null) return Boolean(raw(value) || value.link);
114
+ return false;
115
+ }
116
+
117
+ function resultBackReference(value) {
118
+ if (typeof value === 'object' && value !== null) return referenceId(value);
119
+ return isSysId(String(value ?? '')) ? String(value) : '';
120
+ }
121
+ // 'malformed' means a payload exists but could not be read as a reference.
122
+ // Parsing a reference is not verification: only results can verify linkage.
123
+ function resultLink(value) {
124
+ const text = raw(value);
125
+ if (!text) return { state: 'missing', id: '' };
126
+ try {
127
+ const id = referenceId(JSON.parse(text).result_id);
128
+ return id ? { state: 'linked', id } : { state: 'malformed', id: '' };
129
+ } catch { return { state: 'malformed', id: '' }; }
130
+ }
103
131
  const STATES = { '0': 'pending', '1': 'running', '2': 'successful', '3': 'failed', '4': 'cancelled',
104
132
  pending: 'pending', running: 'running', successful: 'successful', failed: 'failed',
105
133
  cancelled: 'cancelled', canceled: 'cancelled' };
@@ -108,19 +136,25 @@ export async function scanStatus(sdk, id, { allowInitializing = false } = {}) {
108
136
  requireId(id);
109
137
  const tracker = await sdk.get('sys_execution_tracker', id);
110
138
  if (!tracker) throw errNotFound('scan execution', id);
111
- if (!raw(tracker.type) && allowInitializing) return { execution_id: id, status: 'pending', terminal: false,
112
- percent_complete: null, message: 'Execution tracker is initializing', result_id: null };
113
- if (raw(tracker.type) === 'sys.instance_scan.queue') return { execution_id: id, status: 'pending', terminal: false,
114
- percent_complete: raw(tracker.percent_complete) ?? null, message: raw(tracker.message) || 'Scan is queued', result_id: null };
115
- if (raw(tracker.type) !== 'instance_scan') throw errUsage('This execution tracker is not an Instance Scan.');
139
+ // Missing or denied identity is not evidence that this is our execution.
140
+ const trackerId = tracker.sys_id === undefined || tracker.sys_id === null ? '' : String(raw(tracker.sys_id));
141
+ if (trackerId !== id) throw errUsage('The execution tracker identity does not match the requested execution.');
142
+ const type = String(raw(tracker.type) ?? '');
143
+ const link = resultLink(tracker.result);
144
+ if (!type && allowInitializing) return { execution_id: id, status: 'pending', terminal: false,
145
+ phase: 'initializing', percent_complete: null, message: 'Execution tracker is initializing', result_id: null,
146
+ execution_type: type, result_link: link.state };
147
+ if (type === 'sys.instance_scan.queue') return { execution_id: id, status: 'pending', terminal: false,
148
+ phase: 'queued', percent_complete: raw(tracker.percent_complete) ?? null, message: raw(tracker.message) || 'Scan is queued',
149
+ result_id: null, execution_type: type, result_link: link.state };
150
+ if (!SCAN_TRACKER_TYPES.has(type)) throw errUsage('This execution tracker is not an Instance Scan.');
116
151
  const state = STATES[String(raw(tracker.state)).toLowerCase()] || 'unknown';
117
- let resultId = '';
118
- if (raw(tracker.result)) {
119
- try { resultId = referenceId(JSON.parse(raw(tracker.result)).result_id); } catch { /* reported as unavailable below */ }
120
- }
121
- return { execution_id: id, status: state, terminal: TERMINAL.has(state),
152
+ // result_link only says the tracker's own result JSON parsed; a result row and
153
+ // its back-reference are verified in scanResults, never here.
154
+ return { execution_id: id, status: state, terminal: TERMINAL.has(state), phase: 'dispatched',
122
155
  percent_complete: raw(tracker.percent_complete) ?? null,
123
- message: raw(tracker.message) || '', result_id: resultId || null };
156
+ message: raw(tracker.message) || '', result_id: link.id || null,
157
+ execution_type: type, result_link: link.state };
124
158
  }
125
159
 
126
160
  async function resolveSuite(sdk, identifier) {
@@ -205,19 +239,44 @@ export async function startScan(sdk, plan) {
205
239
  export async function scanResults(sdk, id, limit = 50) {
206
240
  boundedLimit(limit);
207
241
  const status = await scanStatus(sdk, id);
208
- const data = { ...status, checks_executed: null, findings_count: null, checks: [], findings: [],
242
+ const data = { ...status, checks_executed: null, findings_count: null, findings_retrieved: null,
243
+ checks: [], findings: [], result_verified: false, back_reference: 'absent',
244
+ findings_state: 'unknown', checks_state: 'unknown',
209
245
  incomplete: !status.terminal, unavailable: [], truncated: {}, rerun_full: false, reusable_target: false };
210
246
  if (!status.result_id) { data.unavailable.push('scan_result'); data.incomplete = true; return data; }
211
247
  let result;
212
248
  try {
213
249
  result = await sdk.get('scan_result', status.result_id);
214
250
  if (!result) throw new Error('Result unavailable');
215
- data.scan_number = raw(result.number);
216
- const value = raw(result.finding_count);
217
- const count = Number(value);
218
- if ((typeof value === 'number' || (typeof value === 'string' && /^\d+$/.test(value))) && Number.isInteger(count) && count >= 0) data.findings_count = count;
219
- else { data.unavailable.push('scan_result.finding_count'); data.incomplete = true; }
251
+ // Require the exact linked identity, including when the field is denied.
252
+ const resultId = result.sys_id === undefined || result.sys_id === null ? '' : String(raw(result.sys_id));
253
+ if (resultId !== status.result_id) {
254
+ data.unavailable.push('scan_result.identity');
255
+ data.incomplete = true;
256
+ result = null;
257
+ }
220
258
  } catch { data.unavailable.push('scan_result'); data.incomplete = true; }
259
+ if (result) {
260
+ // The result row must point back to this execution. A point scan always
261
+ // records its execution id; a foreign or absent back-reference means the
262
+ // row cannot be trusted to describe this scan. Only a matching
263
+ // back-reference earns result_verified; a parsed id alone does not.
264
+ const present = hasResultBackReference(result.progress_id);
265
+ const matches = present && resultBackReference(result.progress_id) === status.execution_id;
266
+ data.back_reference = present ? (matches ? 'matched' : 'foreign') : 'absent';
267
+ if ((present && !matches) || (!present && status.execution_type === 'point_scan')) {
268
+ data.unavailable.push('scan_result.back_reference');
269
+ data.incomplete = true;
270
+ result = null;
271
+ } else {
272
+ data.result_verified = matches;
273
+ data.scan_number = raw(result.number);
274
+ const value = raw(result.finding_count);
275
+ const count = Number(value);
276
+ if ((typeof value === 'number' || (typeof value === 'string' && /^\d+$/.test(value))) && Number.isInteger(count) && count >= 0) data.findings_count = count;
277
+ else { data.unavailable.push('scan_result.finding_count'); data.incomplete = true; }
278
+ }
279
+ }
221
280
  for (const [key, table, fields] of [
222
281
  ['checks', 'scan_check_execution', ['check', 'message', 'execution_time']],
223
282
  ['findings', 'scan_finding', ['check', 'source_table', 'source', 'finding_details', 'count']],
@@ -225,11 +284,27 @@ export async function scanResults(sdk, id, limit = 50) {
225
284
  try {
226
285
  const rows = await sdk.listStrict(table, recordListParams({ limit: limit + 1,
227
286
  query: `result=${status.result_id}^ORDERBYsys_id`, fields, displayValue: 'all' }));
287
+ if (!Array.isArray(rows) || rows.some(row => !row || typeof row !== 'object' || Array.isArray(row))) {
288
+ throw new Error('Unreadable scan rows');
289
+ }
228
290
  data[key] = rows.slice(0, limit);
229
291
  data.truncated[key] = rows.length > limit;
292
+ if (key === 'findings') data.findings_retrieved = rows.length;
230
293
  if (key === 'checks' && !data.truncated[key] && status.terminal) data.checks_executed = rows.length;
231
294
  } catch { data.unavailable.push(table); data.incomplete = true; }
232
295
  }
296
+ // Reported counts must reconcile with retrieved rows. A positive count with
297
+ // nothing retrieved, or any other disagreement, is not a clean zero and its
298
+ // cause is not assumed. Truncated pages cannot be reconciled at all.
299
+ if (data.findings_count === null || data.unavailable.includes('scan_finding')) data.findings_state = 'unknown';
300
+ else if (data.truncated.findings) { data.findings_state = 'truncated'; data.incomplete = true; }
301
+ else if (data.findings_count > 0 && data.findings_retrieved === 0) { data.findings_state = 'unretrieved'; data.incomplete = true; }
302
+ else if (data.findings_count !== data.findings_retrieved) { data.findings_state = 'mismatch'; data.incomplete = true; }
303
+ else data.findings_state = 'verified';
304
+ if (data.unavailable.includes('scan_check_execution')) data.checks_state = 'unknown';
305
+ else if (data.truncated.checks) { data.checks_state = 'truncated'; data.incomplete = true; }
306
+ else if (data.checks.length === 0) data.checks_state = 'empty';
307
+ else data.checks_state = 'verified';
233
308
  const comboId = referenceId(result?.combo);
234
309
  if (comboId) {
235
310
  try { const combo = await sdk.get('scan_combo', comboId); if (combo) { data.reusable_target = true; data.rerun_full = !raw(combo.targets); } }