@jacebenson/jsn 5.5.10 → 5.5.11-dev.241.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.
Files changed (51) hide show
  1. package/README.md +25 -0
  2. package/package.json +1 -1
  3. package/src/access-analyzer.js +92 -0
  4. package/src/app.js +5 -0
  5. package/src/auth/credential-store.js +3 -3
  6. package/src/auth/windows-credential-store.ps1 +1 -1
  7. package/src/cli-adapter.js +53 -3
  8. package/src/cli.js +17 -3
  9. package/src/command-audience.js +3 -1
  10. package/src/command-families.js +10 -3
  11. package/src/commands/_generic.js +15 -5
  12. package/src/commands/_simple.js +14 -1
  13. package/src/commands/_ticket.js +7 -1
  14. package/src/commands/access-analyzer.js +37 -0
  15. package/src/commands/approvals.js +1 -1
  16. package/src/commands/atf.js +1 -1
  17. package/src/commands/auth.js +6 -0
  18. package/src/commands/cases.js +3 -0
  19. package/src/commands/catalog.js +1 -1
  20. package/src/commands/cmdb.js +3 -0
  21. package/src/commands/decisiontables.js +1 -1
  22. package/src/commands/discover.js +108 -8
  23. package/src/commands/document.js +31 -0
  24. package/src/commands/domains.js +1 -1
  25. package/src/commands/graphql.js +1 -1
  26. package/src/commands/groupmembers.js +1 -1
  27. package/src/commands/grouproles.js +1 -1
  28. package/src/commands/groups.js +1 -1
  29. package/src/commands/logs.js +3 -0
  30. package/src/commands/records.js +21 -0
  31. package/src/commands/rest.js +1 -1
  32. package/src/commands/scan.js +40 -5
  33. package/src/commands/scopes.js +1 -1
  34. package/src/commands/scrapi.js +1 -1
  35. package/src/commands/table-behavior.js +5 -0
  36. package/src/commands/tickets.js +9 -1
  37. package/src/commands/transactions.js +3 -0
  38. package/src/commands/updatesets.js +1 -1
  39. package/src/commands/users.js +1 -1
  40. package/src/context.js +19 -0
  41. package/src/help.js +3 -1
  42. package/src/instance-documentation.js +237 -0
  43. package/src/intended-context.js +30 -3
  44. package/src/output.js +15 -3
  45. package/src/query-cache.js +187 -0
  46. package/src/query-metadata.js +189 -0
  47. package/src/query-parse.js +201 -0
  48. package/src/query-validate.js +282 -0
  49. package/src/scan.js +92 -17
  50. package/src/sdk.js +3 -0
  51. package/src/table-behavior.js +1 -1
@@ -7,6 +7,7 @@
7
7
  import { AppError, CodeForbidden, errUsage, errUsageHint } from '../errors.js';
8
8
  import { buildQuerySuffix, formatCommandList, formatRecordForDisplay, getStringField, quoteShellArg, resolveFieldsParam } from '../helpers.js';
9
9
  import { getRecord, listRecords, recordListParams } from '../records-engine.js';
10
+ import { validateReadQuery, queryDiagnostics } from '../query-validate.js';
10
11
  import { declareCapabilities } from '../capabilities.js';
11
12
 
12
13
  declareCapabilities('cases', {}); // read-only: no mutating subcommands
@@ -87,6 +88,7 @@ async function resolveTable(app, argv) {
87
88
  async function listCases(app, argv, resolved, query) {
88
89
  const columns = argv.columns ? argv.columns.split(',') : DEFAULT_COLUMNS;
89
90
  const fields = resolveFieldsParam(columns);
91
+ const verdict = await validateReadQuery(app, { table: resolved.table, query });
90
92
  const ordered = query ? `${query}^ORDERBYDESCsys_updated_on` : 'ORDERBYDESCsys_updated_on';
91
93
  const params = recordListParams({ limit: argv.limit, offset: argv.offset, fields, query: ordered });
92
94
  let records;
@@ -114,6 +116,7 @@ async function listCases(app, argv, resolved, query) {
114
116
  records: displayRecords,
115
117
  pagination: { limit: argv.limit, offset: argv.offset, hasMore: records.length === argv.limit },
116
118
  context: { instance_url: app.getEffectiveInstance() },
119
+ ...queryDiagnostics(verdict),
117
120
  }, { summary: `${records.length} ${resolved.table}(s)`, breadcrumbs });
118
121
  }
119
122
 
@@ -4,7 +4,7 @@ import { resolveSysId } from '../resolve-record.js';
4
4
  import { declareCapabilities } from '../capabilities.js';
5
5
  import { enrichCatalogItem, buildCatalogFormatted } from './catalog/enrich.js';
6
6
 
7
- declareCapabilities('catalogitems', { mutationSubcommands: ['create', 'order'], mutationContextExemptSubcommands: ['order'], localPreviewSubcommands: ['order'] });
7
+ declareCapabilities('catalogitems', { queryTable: 'sc_cat_item', mutationSubcommands: ['create', 'order'], mutationContextExemptSubcommands: ['order'], localPreviewSubcommands: ['order'] });
8
8
 
9
9
  export function catalogCmd(wrap) {
10
10
  return {
@@ -15,6 +15,9 @@ import {
15
15
  resolveFieldsParam,
16
16
  } from '../helpers.js';
17
17
  import { errNotFound, errUsage } from '../errors.js';
18
+ import { declareCapabilities } from '../capabilities.js';
19
+ declareCapabilities('cmdb', { queryTable: 'cmdb_ci' });
20
+
18
21
  import { cmdbSearchCmd } from './cmdb-search.js';
19
22
 
20
23
  const SYS_ID_RE = /^[0-9a-f]{32}$/i;
@@ -9,7 +9,7 @@ import { declareCapabilities } from '../capabilities.js';
9
9
  export const decisiontablesCmd = (wrap) => {
10
10
  const name = 'decisiontables';
11
11
  const singular = 'decision table';
12
- declareCapabilities(name, { mutationSubcommands: ['create', 'update', 'delete'] });
12
+ declareCapabilities(name, { queryTable: 'sys_decision', mutationSubcommands: ['create', 'update', 'delete'] });
13
13
 
14
14
  const readData = (argv) => {
15
15
  if (argv.dataFile) return fs.readFileSync(argv.dataFile, 'utf8');
@@ -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
  };
@@ -0,0 +1,31 @@
1
+ import { declareCapabilities } from '../capabilities.js';
2
+ import { DOCUMENT_BUDGETS, collectInstanceDocumentation, renderInstanceDocumentation, writeDocumentFile } from '../instance-documentation.js';
3
+
4
+ declareCapabilities('document', { mutationSubcommands: [], skipDailyChecks: true });
5
+
6
+ export function documentCmd(wrap) {
7
+ return {
8
+ command: 'document',
9
+ describe: 'Create bounded read-only instance configuration documentation',
10
+ builder: y => y.command({
11
+ command: 'instance',
12
+ describe: 'Generate deterministic Markdown/Mermaid from safe metadata. Requires --profile.',
13
+ builder: child => {
14
+ child.option('output', { type: 'string', describe: 'New Markdown file; never overwrites. POSIX mode 0600; Windows inherits directory ACLs; use a private directory.' });
15
+ for (const [name, [fallback, min, max]] of Object.entries(DOCUMENT_BUDGETS)) {
16
+ const flag = name.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
17
+ child.option(flag, { type: 'number', default: fallback, describe: `${name} budget (${min}–${max})` });
18
+ }
19
+ return child;
20
+ },
21
+ handler: wrap(async (argv, app) => {
22
+ const data = await collectInstanceDocumentation(argv, app);
23
+ data.markdown = renderInstanceDocumentation(data);
24
+ app.output.validateExtraction(data);
25
+ if (argv.output) writeDocumentFile(argv.output, data.markdown);
26
+ const human = !app.output.jqFilter && ['styled', 'markdown'].includes(app.output.effectiveFormat());
27
+ app.output.ok(human ? data.markdown : data);
28
+ }),
29
+ }).demandCommand(1),
30
+ };
31
+ }
@@ -6,7 +6,7 @@ import { getStringField, interactiveList, assertSafeExactMatch } from '../helper
6
6
  import { declareCapabilities } from '../capabilities.js';
7
7
 
8
8
  // `domains set` writes the chosen domain into the profile config.
9
- declareCapabilities('domains', { mutationContext: 'operational', mutationSubcommands: ['set', 'session-set', 'session-reset'] });
9
+ declareCapabilities('domains', { queryTable: 'domain', mutationContext: 'operational', mutationSubcommands: ['set', 'session-set', 'session-reset'] });
10
10
 
11
11
  const DETAIL_FIELDS = 'sys_id,name,parent,sys_domain_path,description,active,sys_created_on,sys_updated_on';
12
12
 
@@ -3,7 +3,7 @@ import { declareCapabilities } from '../capabilities.js';
3
3
 
4
4
  // GraphQL documents may contain mutations. Gate the whole command so normal
5
5
  // instance/auth and read-only protections apply without attempting AST parsing.
6
- declareCapabilities('graphql', { mutationSubcommands: [''] });
6
+ declareCapabilities('graphql', { encodedQuery: false, mutationSubcommands: [''] });
7
7
 
8
8
  function readStdin() {
9
9
  return new Promise((resolve, reject) => {
@@ -3,7 +3,7 @@ import { declareCapabilities } from '../capabilities.js';
3
3
 
4
4
  // add/remove write sys_user_grmember; the mutation guard (instance +
5
5
  // read-only profile) and the delete confirmation both key off this.
6
- declareCapabilities('groupmembers', { mutationContext: 'operational', mutationSubcommands: ['add', 'remove'] });
6
+ declareCapabilities('groupmembers', { queryTable: 'sys_user_grmember', mutationContext: 'operational', mutationSubcommands: ['add', 'remove'] });
7
7
 
8
8
  export function groupMembersCmd(wrap) {
9
9
  return {
@@ -3,7 +3,7 @@ import { declareCapabilities } from '../capabilities.js';
3
3
 
4
4
  // add/remove write sys_group_has_role; the mutation guard (instance +
5
5
  // read-only profile) and the delete confirmation both key off this.
6
- declareCapabilities('grouproles', { mutationContext: 'operational', mutationSubcommands: ['add', 'remove'] });
6
+ declareCapabilities('grouproles', { queryTable: 'sys_group_has_role', mutationContext: 'operational', mutationSubcommands: ['add', 'remove'] });
7
7
 
8
8
  export function groupRolesCmd(wrap) {
9
9
  return {
@@ -1,7 +1,7 @@
1
1
  import { formatRecordForDisplay, getStringField, interactiveList, resolveFieldsParam, assertSafeExactMatch, buildRecordPayload } from '../helpers.js';
2
2
  import { declareCapabilities } from '../capabilities.js';
3
3
 
4
- declareCapabilities('groups', { mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
4
+ declareCapabilities('groups', { queryTable: 'sys_user_group', mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
5
5
 
6
6
  export function groupsCmd(wrap) {
7
7
  return {
@@ -1,3 +1,6 @@
1
+ import { declareCapabilities } from '../capabilities.js';
2
+ declareCapabilities('logs', { queryTable: 'syslog' });
3
+
1
4
  import { formatRecordForDisplay, interactiveList, getStringField } from '../helpers.js';
2
5
 
3
6
  function logIcon(level) {
@@ -6,9 +6,11 @@ import { AmbClient } from '../amb.js';
6
6
  import { watchRecord } from '../record-watch.js';
7
7
  import { declareCapabilities } from '../capabilities.js';
8
8
  import { assertMutationRecordScope, assertMutationScope } from '../intended-context.js';
9
+ import { validateReadQuery, assertWriteQuery, queryDiagnostics, invalidateAfterMutation } from '../query-validate.js';
9
10
 
10
11
  declareCapabilities('records', {
11
12
  mutationContext: 'table',
13
+ filteredMutationSubcommands: ['delete-many', 'bulk'],
12
14
  mutationSubcommands: ['create', 'update', 'delete', 'delete-many', 'bulk'],
13
15
  });
14
16
 
@@ -95,6 +97,7 @@ export function recordsCmd(wrap) {
95
97
  .option('table', { type: 'string', demandOption: true, describe: 'Table name' })
96
98
  .option('sys-id', { type: 'string', describe: 'Record sys_id (filters to a single record)' })
97
99
  .option('query', { type: 'string', describe: 'Encoded query (e.g. "nameLIKEincident" or "active=true")' })
100
+ .option('refresh-metadata', { type: 'boolean', default: false, describe: 'Refresh table metadata used to validate --query (five-minute cache)' })
98
101
  .option('columns', { alias: ['c', 'fields'], type: 'string', describe: 'Comma-separated columns (e.g. "number,short_description")' })
99
102
  .option('limit', { type: 'number', default: 20, describe: 'Max records' })
100
103
  .option('offset', { type: 'number', default: 0, describe: 'Offset' })
@@ -115,6 +118,7 @@ export function recordsCmd(wrap) {
115
118
  const table = argv.table;
116
119
  const columns = argv.columns ? argv.columns.split(',') : getDefaultColumns(table);
117
120
  let query = argv.query || '';
121
+ const verdict = await validateReadQuery(app, { table, query: argv.query || '', refresh: argv['refresh-metadata'] });
118
122
 
119
123
  // If --sys-id is provided, append it to the query
120
124
  if (argv['sys-id']) {
@@ -208,6 +212,7 @@ export function recordsCmd(wrap) {
208
212
  records: displayRecords,
209
213
  pagination: { limit: argv.limit, offset: argv.offset, ...(total != null ? { total, hasMore: argv.offset + argv.limit < total } : {}) },
210
214
  context: { instance_url: app.getEffectiveInstance() },
215
+ ...queryDiagnostics(verdict),
211
216
  }, {
212
217
  summary: `${records.length} record(s) from ${table}${total != null ? ` of ${total}` : ''}`,
213
218
  breadcrumbs,
@@ -370,6 +375,7 @@ export function recordsCmd(wrap) {
370
375
  process.stderr.write(`⚠ ${w.hint}\n`);
371
376
  }
372
377
  const record = await createRecord(app.sdk, { table: argv.table, data: recordData });
378
+ invalidateAfterMutation(app, argv.table);
373
379
  const sysID = getStringField(record, 'sys_id');
374
380
  const mismatches = await verifyWriteBack(app, argv.table, sysID, recordData);
375
381
  for (const m of mismatches) {
@@ -403,6 +409,7 @@ export function recordsCmd(wrap) {
403
409
  const lookup = recordLookup(argv);
404
410
  const resolved = await getRecord(app.sdk, lookup);
405
411
  const record = await updateRecord(app.sdk, { table: argv.table, record: resolved, data: recordData });
412
+ invalidateAfterMutation(app, argv.table);
406
413
  const mismatches = await verifyWriteBack(app, argv.table, unwrapSysId(resolved), recordData);
407
414
  for (const m of mismatches) {
408
415
  process.stderr.write(`⚠ field "${m.field}" was not persisted (sent: "${m.sent}", got: "${m.got}")\n`);
@@ -426,6 +433,7 @@ export function recordsCmd(wrap) {
426
433
  const lookup = recordLookup(argv);
427
434
  await confirmDelete(app, argv, `Delete record from ${argv.table} (${lookup.identifier})`);
428
435
  const sysID = await deleteRecord(app.sdk, lookup);
436
+ invalidateAfterMutation(app, argv.table);
429
437
  app.ok({ message: 'Record deleted', table: argv.table, sys_id: sysID }, { summary: `Deleted record from ${argv.table}` });
430
438
  }),
431
439
  })
@@ -435,6 +443,7 @@ export function recordsCmd(wrap) {
435
443
  builder: (y) => y
436
444
  .option('table', { type: 'string', demandOption: true, describe: 'Table name' })
437
445
  .option('query', { type: 'string', describe: 'Required nonempty encoded query; use records delete for a single record' })
446
+ .option('refresh-metadata', { type: 'boolean', default: false, describe: 'Refresh table metadata before validating the filter (five-minute cache)' })
438
447
  .option('expect-count', { type: 'number', describe: 'Required for deletion: exact expected matching count' })
439
448
  .option('yes', { type: 'boolean', default: false, describe: 'Confirm deletion (requires --expect-count)' })
440
449
  .option('dry-run', { type: 'boolean', default: false, describe: 'Preview only, even with --yes' })
@@ -442,6 +451,8 @@ export function recordsCmd(wrap) {
442
451
  .epilogue('Without --yes, reports count and up to 10 sample records without writes.\nDeletion uses per-record Table API DELETE, then re-counts the query. Concurrent changes cannot be made atomic.'),
443
452
  handler: wrap(async (argv, app) => {
444
453
  if (!argv.query?.trim()) throw errUsage('--query must be nonempty. Use records delete for a single record.');
454
+ // Complete original filter validated before count/enumeration/scope reads or any write.
455
+ await assertWriteQuery(app, { table: argv.table, query: argv.query, refresh: argv['refresh-metadata'] });
445
456
  if (!Number.isSafeInteger(argv.limit) || argv.limit < 1) throw errUsage('--limit must be a positive safe integer.');
446
457
  const dryRun = !argv.yes || argv['dry-run'];
447
458
  const expected = argv['expect-count'];
@@ -509,6 +520,7 @@ export function recordsCmd(wrap) {
509
520
  builder: (y) => y
510
521
  .option('table', { type: 'string', demandOption: true, describe: 'Table name' })
511
522
  .option('query', { type: 'string', describe: 'Encoded query to constrain the aggregation' })
523
+ .option('refresh-metadata', { type: 'boolean', default: false, describe: 'Refresh table metadata used to validate --query (five-minute cache)' })
512
524
  .option('group-by', { type: 'string', describe: 'Comma-separated fields to group by' })
513
525
  .option('display-values', { type: 'string', choices: ['raw', 'display', 'both'], describe: 'Reference values: raw, display or both' })
514
526
  .option('count', { type: 'boolean', default: true, describe: 'Include record counts' })
@@ -519,6 +531,7 @@ export function recordsCmd(wrap) {
519
531
  .option('order-by', { type: 'string', describe: 'Comma-separated fields to order by' }),
520
532
  handler: wrap(async (argv, app) => {
521
533
  app.requireInstance();
534
+ const verdict = await validateReadQuery(app, { table: argv.table, query: argv.query || '', refresh: argv['refresh-metadata'] });
522
535
  const split = (value) => value ? value.split(',').map(v => v.trim()).filter(Boolean) : [];
523
536
  const options = {
524
537
  query: argv.query || '',
@@ -545,6 +558,7 @@ export function recordsCmd(wrap) {
545
558
  },
546
559
  ...result,
547
560
  context: { instance_url: app.getEffectiveInstance() },
561
+ ...queryDiagnostics(verdict),
548
562
  }, { summary: `Aggregated ${argv.table}${options.groupBy.length ? ` by ${options.groupBy.join(', ')}` : ''}` });
549
563
  }),
550
564
  })
@@ -554,6 +568,7 @@ export function recordsCmd(wrap) {
554
568
  builder: (y) => y
555
569
  .option('table', { type: 'string', demandOption: true, describe: 'Table name' })
556
570
  .option('query', { type: 'string', demandOption: true, describe: 'Encoded query selecting the records to update (e.g. "priority=1^state=1")' })
571
+ .option('refresh-metadata', { type: 'boolean', default: false, describe: 'Refresh table metadata before validating the filter (five-minute cache)' })
557
572
  .option('set', { type: 'string', describe: 'JSON object of fields to set' })
558
573
  .option('field', { alias: 'f', type: 'string', array: true, describe: 'Set a field as name=value; repeatable' })
559
574
  .option('dry-run', { type: 'boolean', default: true, describe: 'Preview the count + a sample without mutating (default)' })
@@ -562,6 +577,8 @@ export function recordsCmd(wrap) {
562
577
  .option('force', { type: 'boolean', default: false, describe: 'Skip confirmation (with --execute)' }),
563
578
  handler: wrap(async (argv, app) => {
564
579
  app.requireInstance();
580
+ // Validate the complete original filter before confirmation, count or any write.
581
+ await assertWriteQuery(app, { table: argv.table, query: argv.query, refresh: argv['refresh-metadata'] });
565
582
  const set = buildRecordPayload({ ...argv, data: argv.set }, { required: true });
566
583
  if (!argv['dry-run'] && !argv.execute) {
567
584
  argv.execute = true; // explicit --no-dry-run implies execute intent
@@ -638,6 +655,10 @@ export function recordsCmd(wrap) {
638
655
  command: 'inspect <table> <identifier>',
639
656
  aliases: ['debug', 'diag'],
640
657
  describe: 'Inspect a record: show audit history, business rules, and running flows',
658
+ discoveryTasks: [{
659
+ phrases: ['record history', 'audit history', 'record changes', 'show record history', 'who changed a record'],
660
+ args: ['--json'], description: 'Inspect audit history for the specified table and record',
661
+ }],
641
662
  builder: (y) => y
642
663
  .positional('table', { describe: 'Table name (e.g. incident)', type: 'string' })
643
664
  .positional('identifier', { describe: 'Record sys_id or number', type: 'string' }),
@@ -2,7 +2,7 @@ import { declareCapabilities } from '../capabilities.js';
2
2
 
3
3
  // Raw REST passthrough — can hit any endpoint with any method, so the whole
4
4
  // command is a mutation surface on read-only profiles.
5
- declareCapabilities('rest', { mutationSubcommands: [''], mutationContextReadMethods: ['GET', 'HEAD', 'OPTIONS'] });
5
+ declareCapabilities('rest', { encodedQuery: false, mutationSubcommands: [''], mutationContextReadMethods: ['GET', 'HEAD', 'OPTIONS'] });
6
6
 
7
7
  export function restCmd(wrap) {
8
8
  return {
@@ -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) => {
@@ -3,7 +3,7 @@ import { requireCurrentUserSysId, setCurrentApplication } from '../context.js';
3
3
  import { declareCapabilities } from '../capabilities.js';
4
4
  import { unwrapSysId } from '../resolve-record.js';
5
5
 
6
- declareCapabilities('scopes', { mutationSubcommands: ['create', 'set'], mutationContextExemptSubcommands: ['set'] });
6
+ declareCapabilities('scopes', { queryTable: 'sys_scope', mutationSubcommands: ['create', 'set'], mutationContextExemptSubcommands: ['set'] });
7
7
 
8
8
  /**
9
9
  * Resolve a scope identifier to a single sys_scope record.
@@ -14,7 +14,7 @@ import { declareCapabilities } from '../capabilities.js';
14
14
 
15
15
  // `scrapi create` builds a full Scripted REST API in one call (list/show are
16
16
  // reads). Registered at the root.
17
- declareCapabilities('scrapi', { transactionScopeOption: 'scope', mutationSubcommands: ['create'] });
17
+ declareCapabilities('scrapi', { queryTable: 'sys_ws_operation', transactionScopeOption: 'scope', mutationSubcommands: ['create'] });
18
18
 
19
19
  /**
20
20
  * Parse a --resource flag value of the form:
@@ -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', {
@@ -1,10 +1,11 @@
1
1
  import { enrichRelatedLists, relatedListOptions } from '../related-lists.js';
2
2
  import { formatRecordForDisplay, findOmittedColumns, getStringField, buildQuerySuffix, resolveFieldsParam, buildRecordPayload, confirmDelete } from '../helpers.js';
3
3
  import { getRecord, listRecords, recordListParams, createRecord, updateRecord, deleteRecord, recordOptions } from '../records-engine.js';
4
+ import { validateReadQuery, queryDiagnostics } from '../query-validate.js';
4
5
  import { resolveSysId } from '../resolve-record.js';
5
6
  import { declareCapabilities } from '../capabilities.js';
6
7
 
7
- declareCapabilities('tickets', { mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
8
+ declareCapabilities('tickets', { queryTable: 'task', mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
8
9
 
9
10
  export function ticketsCmd(wrap) {
10
11
  return {
@@ -25,6 +26,7 @@ export function ticketsCmd(wrap) {
25
26
  handler: wrap(async (argv, app) => {
26
27
  const columns = argv.columns ? argv.columns.split(',') : ['number', 'short_description', 'state', 'assigned_to'];
27
28
  const fields = resolveFieldsParam(columns);
29
+ const verdict = await validateReadQuery(app, { table: 'task', query: argv.query || '' });
28
30
  const q = argv.query ? argv.query + '^ORDERBYDESCsys_updated_on' : 'ORDERBYDESCsys_updated_on';
29
31
  const params = recordListParams({ limit: argv.limit, offset: argv.offset, fields, query: q });
30
32
  const records = await listRecords(app.sdk, { table: 'task', params, displayValues: argv.displayValues });
@@ -52,6 +54,7 @@ export function ticketsCmd(wrap) {
52
54
  table: 'task',
53
55
  count: records.length,
54
56
  columns,
57
+ ...queryDiagnostics(verdict),
55
58
  ...(missingColumns.length ? {
56
59
  missing_columns: missingColumns,
57
60
  warnings: [
@@ -92,6 +95,11 @@ export function ticketsCmd(wrap) {
92
95
  .command({
93
96
  command: 'update <number>',
94
97
  describe: 'Update a ticket',
98
+ discoveryTasks: [{
99
+ phrases: ['write work note', 'write work notes', 'add work note', 'add work notes', 'append work notes', 'write a work note', 'add internal note'],
100
+ args: ['--field', 'work_notes=<text>', '--json'],
101
+ description: 'Write a work note to the specified ticket; replace the required number and text placeholders',
102
+ }],
95
103
  builder: (y) => recordOptions(y, false)
96
104
  .option('data', { type: 'string', describe: 'JSON fields' })
97
105
  .option('data-file', { type: 'string', describe: 'Read JSON payload from file' })
@@ -103,6 +103,9 @@ function formatTopTransactions(groups) {
103
103
  return `${lines.join('\\n')}\\n`;
104
104
  }
105
105
 
106
+ import { declareCapabilities } from '../capabilities.js';
107
+ declareCapabilities('transactions', { queryTable: 'syslog_transaction' });
108
+
106
109
  export function topTransactionsCmd(wrap) {
107
110
  return {
108
111
  command: 'top',
@@ -13,7 +13,7 @@ import { resolveScope } from './scopes.js';
13
13
  import { unwrapSysId } from '../resolve-record.js';
14
14
  import { assertNoUnresolvedProblems, DEFAULT_OPERATION_TIMEOUT_MS } from '../update-set-apply.js';
15
15
 
16
- declareCapabilities('updatesets', {
16
+ declareCapabilities('updatesets', { queryTable: 'sys_update_set',
17
17
  mutationSubcommands: ['create', 'set', 'complete', 'ignore', 'parent', 'import', 'reopen', 'preview', 'commit'],
18
18
  mutationContextExemptSubcommands: ['create', 'set', 'import', 'reopen', 'preview', 'commit'],
19
19
  skipContextHeaderSubcommands: ['diff'],
@@ -2,7 +2,7 @@ import { formatRecordForDisplay, getStringField, interactiveList, resolveFieldsP
2
2
  import { resolveRecord, resolveSysId } from '../resolve-record.js';
3
3
  import { declareCapabilities } from '../capabilities.js';
4
4
 
5
- declareCapabilities('users', { mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
5
+ declareCapabilities('users', { queryTable: 'sys_user', mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
6
6
 
7
7
  export function usersCmd(wrap) {
8
8
  return {