@jacebenson/jsn 5.5.10-dev.235.1 → 5.5.10-dev.237.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.235.1",
3
+ "version": "5.5.10-dev.237.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": {
package/src/app.js CHANGED
@@ -15,6 +15,7 @@ import { saveConfig, isTrustedCredentialDestination } from './config.js';
15
15
  import { resolveSession, applySession, contextFromSession, requireSessionInstance } from './session.js';
16
16
  import { errUsage, errAuth } from './errors.js';
17
17
  import { canPrompt, canUsePicker } from './helpers.js';
18
+ import { queryDiagnostics, invalidateAfterMutation } from './query-validate.js';
18
19
  import { guardMutationContext } from './mutation-context.js';
19
20
 
20
21
 
@@ -64,6 +65,7 @@ export class App {
64
65
  recovery: createAuthRecovery({ app: this, session }),
65
66
  canInteract: () => canUsePicker(this, this._authArgv || {}),
66
67
  });
68
+ this.sdk.afterMetadataMutation = table => invalidateAfterMutation(this, table);
67
69
  }
68
70
 
69
71
  /** Build a profile-scoped SDK without leaking auth construction to commands. */
@@ -93,6 +95,9 @@ export class App {
93
95
  }
94
96
 
95
97
  ok(data, opts = {}) {
98
+ const diagnostics = queryDiagnostics(this.queryValidation);
99
+ if (diagnostics.query_validation && data && typeof data === 'object' && !Array.isArray(data)) data = Object.assign(data, diagnostics);
100
+ else if (diagnostics.query_validation) opts = { ...opts, meta: { ...opts.meta, ...diagnostics } };
96
101
  this.output.ok(data, this.mutationContext ? { ...opts, context: { ...opts.context, mutation: this.mutationContext } } : opts);
97
102
  }
98
103
 
@@ -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
@@ -12,7 +12,7 @@ import { resolveSession, applySession } from './session.js';
12
12
  import { renderHelp, renderTips } from './help.js';
13
13
  import { isMutationCommand, refreshMutationCommands } from './mutations.js';
14
14
  import { maybeShowHome } from './welcome.js';
15
- import { isLocalPreview, noInstanceCommands, dailyCheckSkipCommands } from './capabilities.js';
15
+ import { isLocalPreview, noInstanceCommands, dailyCheckSkipCommands, collectCapabilities } from './capabilities.js';
16
16
  import { guardExit, exitWithError, AppError, CodeUsage } from './errors.js';
17
17
  import { formatCommandList } from './helpers.js';
18
18
 
@@ -116,6 +116,8 @@ export function resolveRequestedFormat(argv) {
116
116
  */
117
117
  const DISCOVERY_OWNED_ELSEWHERE = new Set(['auth', 'perf', 'skill', 'groupmembers', 'grouproles']);
118
118
 
119
+ import { validateReadQuery, assertWriteQuery } from './query-validate.js';
120
+
119
121
  function wrap(handler) {
120
122
  return async (argv) => {
121
123
  try {
@@ -124,6 +126,14 @@ function wrap(handler) {
124
126
  process.stderr.write('Error: App context not initialized.\n');
125
127
  process.exit(1);
126
128
  }
129
+ const caps = collectCapabilities().get(argv._?.[0]) || {};
130
+ app.queryValidation = null;
131
+ if (((typeof argv.query === 'string' && argv.query.trim()) || caps.filteredMutationSubcommands?.includes(argv._?.[1]))
132
+ && !caps.noInstance && caps.encodedQuery !== false) {
133
+ const target = typeof caps.queryTable === 'function' ? caps.queryTable(argv) : caps.queryTable || caps.table || argv.table;
134
+ const options = { table: target, query: argv.query, refresh: argv['refresh-metadata'] };
135
+ app.queryValidation = await (isMutationCommand(argv) ? assertWriteQuery : validateReadQuery)(app, options);
136
+ }
127
137
  await app.guardMutationContext(argv);
128
138
  await handler(argv, app);
129
139
  } catch (err) {
@@ -150,6 +160,7 @@ export function buildCLI() {
150
160
  },
151
161
  ])
152
162
  .options({
163
+ 'refresh-metadata': { type: 'boolean', describe: 'Refresh query metadata instead of reusing the five-minute cache' },
153
164
  'all-commands': { type: 'boolean', describe: 'Show the full command list, including admin and developer tools' },
154
165
 
155
166
  'expect-scope': { type: 'string', description: 'Intended customization scope, exact scope/name or sys_id' },
@@ -458,7 +469,7 @@ export function buildCLI() {
458
469
  .command(versionCmd(wrap))
459
470
  .command(upgradeCmd(wrap))
460
471
  .command(documentCmd(wrap))
461
- .command(discoverCmd(wrap, (argv) => visibleCommandRegistry(cliInstance.commandRegistry(), app.config, argv)))
472
+ .command(discoverCmd(wrap, (argv) => visibleCommandRegistry(cliInstance.commandRegistry({ details: true }), app.config, argv)))
462
473
  .demandCommand(1, 'You must specify a command')
463
474
  .onParentDiscovery((argv, { path, subcommands }) => {
464
475
  // 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
  }
@@ -13,7 +13,7 @@ export const flowsCmdDefinition = {
13
13
  aliases: ['flow'],
14
14
  describe: 'Manage Flow Designer flows',
15
15
  };
16
- declareCapabilities('flows', { transactionScopeOption: 'scope', mutationContextExemptSubcommands: ['test', 'unlock'], mutationSubcommands: ['clone', 'copy', 'create', 'update', 'edit', 'delete', 'publish', 'test', 'unlock'] });
16
+ declareCapabilities('flows', { queryTable: argv => argv._?.[1] === 'executions' ? 'sys_flow_context' : 'sys_hub_flow', transactionScopeOption: 'scope', mutationContextExemptSubcommands: ['test', 'unlock'], mutationSubcommands: ['clone', 'copy', 'create', 'update', 'edit', 'delete', 'publish', 'test', 'unlock'] });
17
17
  export const flowsCmd = wrap => ({ ...flowsCmdDefinition, load: () => require('./commands/flows.js').flowsCmd(wrap) });
18
18
 
19
19
  export const workflowsCmdDefinition = {
@@ -21,7 +21,7 @@ export const workflowsCmdDefinition = {
21
21
  aliases: ['workflow'],
22
22
  describe: 'Inspect legacy Workflow Editor workflows (read-only)',
23
23
  };
24
- declareCapabilities('workflows', { mutationSubcommands: [] });
24
+ declareCapabilities('workflows', { queryTable: 'wf_workflow', mutationSubcommands: [] });
25
25
  export const workflowsCmd = wrap => ({ ...workflowsCmdDefinition, load: () => require('./commands/workflows.js').workflowsCmd(wrap) });
26
26
 
27
27
  export const midserversCmdDefinition = {
@@ -29,7 +29,7 @@ export const midserversCmdDefinition = {
29
29
  aliases: ['midserver', 'mid'],
30
30
  describe: 'Manage ServiceNow MID Servers and run commands through them',
31
31
  };
32
- declareCapabilities('midservers', { mutationContext: 'operational', mutationSubcommands: ['add', 'remove', 'execute', 'start', 'stop', 'validate'] });
32
+ declareCapabilities('midservers', { queryTable: 'ecc_agent', mutationContext: 'operational', mutationSubcommands: ['add', 'remove', 'execute', 'start', 'stop', 'validate'] });
33
33
  export const midserversCmd = wrap => ({ ...midserversCmdDefinition, load: () => require('./commands/midservers.js').midserversCmd(wrap) });
34
34
 
35
35
  export const subscriptionsCmdDefinition = {
@@ -4,6 +4,7 @@ import { enrichRelatedLists, relatedListOptions } from '../related-lists.js';
4
4
 
5
5
  import { formatRecordForDisplay, findOmittedColumns, getStringField, buildRecordPayload, confirmDelete, interactiveList, canPrompt } from '../helpers.js';
6
6
  import { getRecord, listRecords, recordListParams, createRecord, updateRecord, deleteRecord, recordOptions } from '../records-engine.js';
7
+ import { validateReadQuery, queryDiagnostics, invalidateAfterMutation } from '../query-validate.js';
7
8
  import { unwrapSysId } from '../resolve-record.js';
8
9
  import { getCurrentUser, getCurrentApplication } from '../context.js';
9
10
  import { FormatAuto } from '../output.js';
@@ -135,6 +136,7 @@ export function buildDevCmd(name, table, aliases, defaultColumns, wrap, opts = {
135
136
  handler: wrap(async (argv, app) => {
136
137
  const query = argv.query || '';
137
138
  const constrainedQuery = constrainQuery(query, extraQuery);
139
+ const verdict = await validateReadQuery(app, { table, query, refresh: argv['refresh-metadata'] });
138
140
  const columns = argv.columns ? argv.columns.split(',') : defaultColumns;
139
141
  const limit = argv.limit;
140
142
 
@@ -186,6 +188,7 @@ export function buildDevCmd(name, table, aliases, defaultColumns, wrap, opts = {
186
188
  } : {}),
187
189
  records: argv.displayValues || opts.listProjection === 'full' ? records : records.map(r => formatRecordForDisplay(r, presentColumns)),
188
190
  context: { instance_url: app.getEffectiveInstance() },
191
+ ...queryDiagnostics(verdict),
189
192
  }, {
190
193
  summary: `${records.length} ${name}(s)`,
191
194
  breadcrumbs: buildHints(name, singular, readOnly),
@@ -243,6 +246,7 @@ export function buildDevCmd(name, table, aliases, defaultColumns, wrap, opts = {
243
246
  handler: wrap(async (argv, app) => {
244
247
  const recordData = buildRecordPayload(argv);
245
248
  const record = await createRecord(app.sdk, { table, data: recordData });
249
+ invalidateAfterMutation(app, table);
246
250
  app.ok(record, {
247
251
  summary: `Created ${singular}`,
248
252
  breadcrumbs: [
@@ -270,6 +274,7 @@ export function buildDevCmd(name, table, aliases, defaultColumns, wrap, opts = {
270
274
  const sysID = unwrapSysId(record);
271
275
  const recordData = buildRecordPayload(argv);
272
276
  const updated = await updateRecord(app.sdk, { table, record: { sys_id: sysID }, data: recordData });
277
+ invalidateAfterMutation(app, table);
273
278
  app.ok(updated, { summary: `Updated ${singular} ${id}` });
274
279
  }),
275
280
  })
@@ -290,6 +295,7 @@ export function buildDevCmd(name, table, aliases, defaultColumns, wrap, opts = {
290
295
  await confirmDelete(app, argv, `Delete ${singular} '${recordName}'`);
291
296
 
292
297
  await deleteRecord(app.sdk, { table, record: { sys_id: sysID } });
298
+ invalidateAfterMutation(app, table);
293
299
  app.ok({ name: recordName, sys_id: sysID, deleted: true }, { summary: `Deleted ${singular} '${recordName}'` });
294
300
  }),
295
301
  });
@@ -4,6 +4,7 @@ import { enrichRelatedLists, relatedListOptions } from '../related-lists.js';
4
4
 
5
5
  import { getStringField, formatRecordForDisplay, findOmittedColumns, buildQuerySuffix, resolveFieldsParam, confirmDelete, interactiveList, canPrompt, buildRecordPayload } from '../helpers.js';
6
6
  import { getRecord, listRecords, recordListParams, createRecord, updateRecord, deleteRecord, recordOptions } from '../records-engine.js';
7
+ import { validateReadQuery, queryDiagnostics, invalidateAfterMutation } from '../query-validate.js';
7
8
  import { resolveSysId } from '../resolve-record.js';
8
9
  import { FormatAuto } from '../output.js';
9
10
  import { declareCapabilities } from '../capabilities.js';
@@ -11,7 +12,7 @@ import { declareCapabilities } from '../capabilities.js';
11
12
  export function buildTicketCommands(table, displayName, alias, defaultColumns, stateMap, iconFn, wrap, opts = {}) {
12
13
  // Ticket-style CRUD: list/show are reads; create/update/delete mutate.
13
14
  // Root-level command only.
14
- declareCapabilities(displayName, { mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
15
+ declareCapabilities(displayName, { queryTable: table, mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
15
16
  return {
16
17
  command: `${displayName} [subcommand]`,
17
18
  aliases: [table, alias],
@@ -30,6 +31,7 @@ export function buildTicketCommands(table, displayName, alias, defaultColumns, s
30
31
  .option('offset', { alias: 'o', type: 'number', default: 0, describe: 'Offset for pagination' }),
31
32
  handler: wrap(async (argv, app) => {
32
33
  const query = argv.query || '';
34
+ const verdict = await validateReadQuery(app, { table, query, refresh: argv['refresh-metadata'] });
33
35
  const columns = argv.columns ? argv.columns.split(',') : defaultColumns;
34
36
  const limit = argv.limit;
35
37
  const offset = argv.offset;
@@ -125,6 +127,7 @@ export function buildTicketCommands(table, displayName, alias, defaultColumns, s
125
127
  records: displayRecords,
126
128
  pagination: { limit, offset, hasMore: records.length === limit },
127
129
  context: { instance_url: app.getEffectiveInstance() },
130
+ ...queryDiagnostics(verdict),
128
131
  }, {
129
132
  summary: `${records.length} ${table}(s)`,
130
133
  breadcrumbs,
@@ -175,6 +178,7 @@ export function buildTicketCommands(table, displayName, alias, defaultColumns, s
175
178
  throw new Error('short_description is required (use --description, -f short_description=..., or --data)');
176
179
  }
177
180
  const record = await createRecord(app.sdk, { table, data: recordData });
181
+ invalidateAfterMutation(app, table);
178
182
  app.ok(record, {
179
183
  summary: `Created ${displayName} ${getStringField(record, 'number')}`,
180
184
  breadcrumbs: [
@@ -196,6 +200,7 @@ export function buildTicketCommands(table, displayName, alias, defaultColumns, s
196
200
  const recordData = buildRecordPayload(argv);
197
201
  const sysID = await resolveSysId(app.sdk, { table, identifier: number, identifierField: argv.identifierField, displayValues: argv.displayValues ?? opts.referenceMode, matchField: opts.identifierField || 'number', resource: displayName });
198
202
  const updated = await updateRecord(app.sdk, { table, record: { sys_id: sysID }, data: recordData });
203
+ invalidateAfterMutation(app, table);
199
204
  app.ok(updated, {
200
205
  summary: `Updated ${displayName} ${number}`,
201
206
  breadcrumbs: [
@@ -213,6 +218,7 @@ export function buildTicketCommands(table, displayName, alias, defaultColumns, s
213
218
  await confirmDelete(app, argv, `Delete ${displayName} ${number}`);
214
219
  const sysID = await resolveSysId(app.sdk, { table, identifier: number, identifierField: argv.identifierField, displayValues: argv.displayValues ?? opts.referenceMode, matchField: opts.identifierField || 'number', resource: displayName });
215
220
  await deleteRecord(app.sdk, { table, record: { sys_id: sysID } });
221
+ invalidateAfterMutation(app, table);
216
222
  app.ok({ number, message: `${displayName.charAt(0).toUpperCase() + displayName.slice(1)} deleted` }, {
217
223
  summary: `Deleted ${displayName} ${number}`,
218
224
  });
@@ -25,7 +25,7 @@ import { errUsage, errNotFound } from '../errors.js';
25
25
  import { declareCapabilities } from '../capabilities.js';
26
26
 
27
27
  // approve/reject/submit change approval state on records.
28
- declareCapabilities('approvals', { mutationContext: 'operational', mutationSubcommands: ['approve', 'reject', 'submit'] });
28
+ declareCapabilities('approvals', { queryTable: 'sysapproval_approver', mutationContext: 'operational', mutationSubcommands: ['approve', 'reject', 'submit'] });
29
29
 
30
30
  // Raw sysapproval_approver.state values (verified live).
31
31
  const APPROVAL_STATES = [
@@ -27,7 +27,7 @@ import { errUsage, errNotFound } from '../errors.js';
27
27
  import { declareCapabilities } from '../capabilities.js';
28
28
 
29
29
  // run/run-suite schedule tests that act on records (top-level only).
30
- declareCapabilities('atf', { mutationContext: 'operational', mutationSubcommands: ['run', 'run-suite'] });
30
+ declareCapabilities('atf', { queryTable: argv => argv._?.[1] === 'suites' ? 'sys_atf_test_suite' : 'sys_atf_test', mutationContext: 'operational', mutationSubcommands: ['run', 'run-suite'] });
31
31
 
32
32
  // sn_cicd progress statuses (now-sdk poller.ts)
33
33
  const PROGRESS_PENDING = '0';
@@ -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', {
@@ -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
  };
@@ -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) {