@jacebenson/jsn 5.5.7 → 5.5.8-dev.219.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 (63) hide show
  1. package/README.md +16 -1
  2. package/package.json +5 -6
  3. package/skills/servicenow/SKILL.md +9 -1
  4. package/src/app.js +4 -79
  5. package/src/bounded-reads.js +13 -0
  6. package/src/capabilities.js +8 -3
  7. package/src/cli-adapter.js +26 -3
  8. package/src/cli.js +13 -14
  9. package/src/command-families.js +68 -0
  10. package/src/commands/_generic.js +1 -0
  11. package/src/commands/_ticket.js +1 -1
  12. package/src/commands/actions.js +9 -4
  13. package/src/commands/approvals.js +1 -1
  14. package/src/commands/atf.js +1 -1
  15. package/src/commands/attachments.js +1 -1
  16. package/src/commands/auth.js +21 -2
  17. package/src/commands/codesearch.js +11 -2
  18. package/src/commands/compare.js +22 -0
  19. package/src/commands/customizations.js +3 -4
  20. package/src/commands/decisiontables.js +4 -0
  21. package/src/commands/docs/docs.js +5 -5
  22. package/src/commands/domains.js +1 -1
  23. package/src/commands/eval.js +11 -5
  24. package/src/commands/flows.js +24 -7
  25. package/src/commands/groupmembers.js +1 -1
  26. package/src/commands/grouproles.js +1 -1
  27. package/src/commands/groups.js +1 -1
  28. package/src/commands/midservers.js +4 -11
  29. package/src/commands/perf.js +2 -3
  30. package/src/commands/plugins.js +9 -0
  31. package/src/commands/records.js +12 -2
  32. package/src/commands/scopes.js +1 -1
  33. package/src/commands/scrapi.js +2 -2
  34. package/src/commands/setup.js +4 -34
  35. package/src/commands/skipped-updates.js +2 -3
  36. package/src/commands/store.js +4 -1
  37. package/src/commands/subscriptions.js +47 -0
  38. package/src/commands/tickets.js +1 -1
  39. package/src/commands/users.js +1 -1
  40. package/src/commands/workflows.js +3 -5
  41. package/src/config.js +1 -0
  42. package/src/context.js +8 -56
  43. package/src/docs-links.js +28 -0
  44. package/src/flow-create.js +9 -0
  45. package/src/help.js +4 -0
  46. package/src/helpers.js +17 -24
  47. package/src/instance-inventory.js +184 -0
  48. package/src/intended-context.js +68 -0
  49. package/src/mutation-context.js +69 -46
  50. package/src/output.js +1 -1
  51. package/src/paginated-search.js +146 -178
  52. package/src/picker-ui.js +20 -0
  53. package/src/prompt-engine.js +176 -0
  54. package/src/prompts.js +293 -43
  55. package/src/records/inspect.js +30 -16
  56. package/src/records-engine.js +2 -2
  57. package/src/schedule-cache.js +96 -0
  58. package/src/schedules/itom-2026-04-09.json +121 -0
  59. package/src/schedules/public-inventory.json +6224 -0
  60. package/src/sdk-batch.js +2 -1
  61. package/src/sdk.js +42 -16
  62. package/src/setup-preferences.js +2 -2
  63. package/src/subscriptions.js +176 -0
@@ -1,5 +1,6 @@
1
1
  // GraphQL read-only queries; no sn_codesearch engine or Flow downloads.
2
2
  import { searchGraphQL } from '../codesearch-graphql.js';
3
+ import { docLink } from '../docs-links.js';
3
4
 
4
5
  export function renderCodeSearch(data) {
5
6
  const out = [`${data.recordCount} record(s), ${data.fieldCount} field(s), ${data.matchCount} match(es) — ${data.status}`];
@@ -35,13 +36,21 @@ export function codesearchCmd(wrap) {
35
36
  .option('all-scopes', { type: 'boolean', default: true, describe: 'Search all scopes; false requires --scope' })
36
37
  .option('page-size', { type: 'number', default: 250, describe: 'GraphQL page window size (max 1000)' })
37
38
  .option('max-pages', { type: 'number', default: 20, describe: 'Maximum pages per table (max 1000)' })
38
- .option('max-requests', { type: 'number', default: 1000, describe: 'Data-call budget including configuration, excluding SDK auth/bootstrap (max 10000)' }),
39
+ .option('max-requests', { type: 'number', default: 1000, describe: 'Data-call budget including configuration, excluding SDK auth/bootstrap (max 10000)' })
40
+ .epilogue(`Code search is literal and read-only. Flow internals use "jsn flows search <term>".
41
+ Examples:
42
+ jsn codesearch search GlideAjax --limit 5
43
+ jsn codesearch search approval --scope x_my_app --limit 5
44
+
45
+ Full reference and coverage limits: ${docLink('codesearch')}`),
39
46
  handler: wrap(async (argv, app) => {
40
47
  const data = await searchGraphQL(app, argv);
41
48
  Object.defineProperty(data, '_formatted', { value: renderCodeSearch(data), enumerable: false });
42
49
  app.ok(data, { summary: `${data.recordCount} record(s), ${data.fieldCount} field(s), ${data.matchCount} match(es) — ${data.status}` });
43
50
  }),
44
- }).demandCommand(1, 'Specify a subcommand: search'),
51
+ }).demandCommand(1, 'Specify a subcommand: search')
52
+ .epilogue(`Code search is literal and read-only. Flow internals use "jsn flows search <term>".
53
+ Documentation: ${docLink('codesearch')}`),
45
54
  handler: () => {},
46
55
  };
47
56
  }
@@ -0,0 +1,22 @@
1
+ import { declareCapabilities } from '../capabilities.js';
2
+ import { inventoryCompareCommand, compareInstanceInventory } from '../instance-inventory.js';
3
+
4
+ declareCapabilities('compare', { skipContextHeader: true });
5
+ export const compareCmd = wrap => ({
6
+ ...inventoryCompareCommand(wrap, 'plugins'),
7
+ command: 'compare',
8
+ describe: 'Compare plugins AND Store apps; report how to align --target to desired --source (read-only)',
9
+ handler: wrap(async (argv, app) => {
10
+ const plugins = await compareInstanceInventory(argv, app, 'plugins', false);
11
+ const store = await compareInstanceInventory(argv, app, 'store', false);
12
+ const data = {
13
+ source: plugins.source, target: plugins.target, complete: plugins.complete && store.complete,
14
+ inventories: { plugins, store },
15
+ counts: Object.fromEntries(Object.keys(plugins.counts).map(key => [key, plugins.counts[key] + store.counts[key]])),
16
+ caveat: 'Distinct plugin and Store inventories can overlap. Counts are unique within each inventory, not a deduplicated product count. Recommendations are review guidance, never executable remediation.',
17
+ };
18
+ Object.defineProperty(data, '_formatted', { value: `${plugins._formatted}\n\n${store._formatted}\n\n${data.caveat}`, enumerable: false });
19
+ app.ok(data, { summary: 'Align target to source: plugins and Store applications' });
20
+ if (!data.complete) process.exitCode = 1;
21
+ }),
22
+ });
@@ -1,4 +1,4 @@
1
- import { declareCapabilities } from '../capabilities.js';
1
+ import { customizationsCmdDefinition } from '../command-families.js';
2
2
  import { errUsageHint, errUsage } from '../errors.js';
3
3
  import { canUsePicker } from '../helpers.js';
4
4
  import { paginatedSearch } from '../paginated-search.js';
@@ -7,7 +7,7 @@ import { buildActionableReport, writeCustomizationHtml } from '../customizations
7
7
  import { customizationGuidance, formatCustomizationGuidance } from '../customization-guidance.js';
8
8
 
9
9
  // Only capture needs an instance. Saved reports never need network access.
10
- declareCapabilities('customizations', { noInstance: true, skipDailyChecks: true, mutationSubcommands: [] });
10
+
11
11
  const listHint = { action: 'list', cmd: 'jsn customizations list', description: 'Browse saved customization captures' };
12
12
  const showHint = id => ({ action: 'show', cmd: `jsn customizations show ${id}`, description: 'Review this saved capture' });
13
13
  const compareHint = id => ({ action: 'compare', cmd: `jsn customizations compare ${id} OTHER_RUN_ID`, description: 'Compare captured metadata and evidence' });
@@ -30,8 +30,7 @@ function show(app, report, options = {}) {
30
30
  }
31
31
  export function customizationsCmd(wrap) {
32
32
  return {
33
- command: 'customizations [subcommand]',
34
- describe: 'Capture and compare read-only customization evidence locally',
33
+ ...customizationsCmdDefinition,
35
34
  builder: y => y
36
35
  .command({ command: 'capture', describe: 'Capture bounded read-only metadata and historical upgrade evidence',
37
36
  builder: b => b.option('label', { type: 'string', describe: 'Label for this capture' })
@@ -1,4 +1,5 @@
1
1
  import fs from 'node:fs';
2
+ import { assertMutationScope } from '../intended-context.js';
2
3
  import { getStringField, formatRecordForDisplay, interactiveList, assertSafeExactMatch, confirmDelete } from '../helpers.js';
3
4
  import { resolveRecord, unwrapSysId, isSysId } from '../resolve-record.js';
4
5
  import { inspectDecisionTable } from '../decision-table-inspection.js';
@@ -19,6 +20,7 @@ export const decisiontablesCmd = (wrap) => {
19
20
  .option('data', { type: 'string', describe: 'Complete decision-table JSON payload' })
20
21
  .option('data-file', { type: 'string', describe: 'Read complete decision-table JSON payload from a file' });
21
22
  const resolveExecutionScope = async (app) => {
23
+ if (app.mutationContext?.verified) return app.mutationContext.application_id;
22
24
  const scope = app.context?.scope;
23
25
  if (!scope) return 'global';
24
26
  const scopeSysId = await app.sdk.resolveScope(scope);
@@ -32,6 +34,7 @@ export const decisiontablesCmd = (wrap) => {
32
34
  const records = await app.sdk.list('sys_decision', params);
33
35
  if (records.length === 0) throw new Error(`Decision table not found in active scope: ${identifier}`);
34
36
  if (records.length > 1) throw new Error(`Decision table ${field} is ambiguous in active scope: ${identifier}`);
37
+ assertMutationScope(app.mutationContext, records[0].sys_scope, 'Decision table target');
35
38
  return records[0];
36
39
  };
37
40
  const resolveDecisionTableForUpdate = async (app, identifier, scopeSysId) => {
@@ -42,6 +45,7 @@ export const decisiontablesCmd = (wrap) => {
42
45
  const records = await app.sdk.list('sys_decision', params);
43
46
  if (records.length === 0) throw new Error(`Decision table not found${scopeSysId === 'global' ? '' : ' in active scope'}: ${identifier}`);
44
47
  if (records.length > 1) throw new Error(`Decision table ${field} is ambiguous: ${identifier}`);
48
+ assertMutationScope(app.mutationContext, records[0].sys_scope, 'Decision table target');
45
49
  const id = unwrapSysId(records[0]);
46
50
  if (!isSysId(id)) throw new Error(`Decision table returned an invalid identifier: ${identifier}`);
47
51
  return id;
@@ -1,13 +1,14 @@
1
+ import { docsCmdDefinition } from '../../command-families.js';
1
2
  // Documentation search always uses the same API, hosted or self-hosted.
2
3
  import { searchHostedDocs, getHostedDoc, getHostedDocsStatus, configuredDocsService } from './client.js';
3
4
  import { documentationService } from './local.js';
4
5
 
5
- import { declareCapabilities } from '../../capabilities.js';
6
+ import { docLink } from '../../docs-links.js';
6
7
  import { AppError } from '../../errors.js';
7
8
  import { resolveDocsRelease } from './db.js';
8
9
  import { listDocsReleases } from './releases.js';
9
10
 
10
- declareCapabilities('docs', { noInstance: true, skipDailyChecks: true });
11
+
11
12
 
12
13
  function presented(data, text) {
13
14
  return Object.defineProperty(data, '_formatted', { value: text, enumerable: false });
@@ -57,11 +58,10 @@ export function docsCmd(wrapHandler) {
57
58
  return handler(argv, app);
58
59
  });
59
60
  return {
60
- command: 'docs [query..]',
61
- defaultPositionals: true,
62
- describe: 'Search ServiceNow documentation (hosted by default; configure your service in setup)',
61
+ ...docsCmdDefinition,
63
62
  builder: y => y
64
63
  .usage('Usage: jsn docs "search terms" [options]')
64
+ .epilogue(`Documentation for this command: ${docLink('docs')}`)
65
65
  .positional('query', { type: 'string', describe: 'Search words (up to 200 characters)' })
66
66
  .option('release', { type: 'string', describe: 'Documentation family (docs.release config, otherwise australia)' })
67
67
 
@@ -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', { mutationSubcommands: ['set', 'session-set', 'session-reset'] });
9
+ declareCapabilities('domains', { 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
 
@@ -5,7 +5,7 @@ import { runRepl } from '../eval-repl.js';
5
5
 
6
6
  // The whole command is a mutation surface (runs arbitrary server-side JS) —
7
7
  // declared as `['']` so the root `jsn eval` command are gated.
8
- declareCapabilities('eval', { mutationSubcommands: [''] });
8
+ declareCapabilities('eval', { transactionScopeOption: 'scope', mutationSubcommands: [''] });
9
9
 
10
10
  export function evalCmd(wrap) {
11
11
  return {
@@ -13,11 +13,17 @@ export function evalCmd(wrap) {
13
13
  describe: 'Execute background scripts on the instance (--repl for interactive mode)',
14
14
  builder: (yargs) => {
15
15
  return yargs
16
+ .middleware(argv => {
17
+ if (!argv.repl) return;
18
+ const conflicts = ['script', 'file', 'stdin'].filter(key => argv[key]).map(key => `--${key}`);
19
+ if (conflicts.length) throw new Error(`--repl cannot be combined with ${conflicts.join(', ')}`);
20
+ if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error('--repl needs an interactive terminal. Use --script, --file or --stdin for scripts and agents.');
21
+ })
16
22
  .option('script', { alias: 's', type: 'string', describe: 'JavaScript code to execute (single-quote the script, double quotes inside: --script \'gs.log("Hello")\')' })
17
23
  .option('file', { alias: 'f', type: 'string', describe: 'Read script from file (avoids shell quoting issues)' })
18
24
  .option('stdin', { type: 'boolean', describe: 'Read script from stdin (pipe-friendly, e.g. cat script.js | jsn eval --stdin)' })
19
25
  .option('repl', { type: 'boolean', default: false, describe: 'Interactive mode: type a script, submit with .exec (requires a terminal)' })
20
- .option('scope', { alias: null, type: 'string', describe: 'Scope name or sys_id to run the script under (default: active scope from banner)' })
26
+ .option('scope', { alias: null, type: 'string', describe: 'Scope name or sys_id to run the script under (default: verified intended scope)' })
21
27
  // Script-mode flags (issue #177) — map to the Script Background form checkboxes
22
28
  .option('rollback', { type: 'boolean', default: true, describe: 'Record rollback context (--no-rollback to skip)' })
23
29
  .option('sandbox', { type: 'boolean', default: false, describe: 'Sandbox mode (KittyScript evaluator, single expression only — no DB writes)' })
@@ -26,12 +32,12 @@ export function evalCmd(wrap) {
26
32
  },
27
33
  handler: wrap(async (argv, app) => {
28
34
  let script;
29
- let scopeSysId = null;
35
+ let scopeSysId = app.mutationContext?.application_id || null;
30
36
 
31
37
  // Resolve execution scope: explicit --scope wins; otherwise use the
32
38
  // active scope from apps.current_app (same source as the banner);
33
39
  // fall back to global only when no active scope exists.
34
- let scope = argv.scope || '';
40
+ let scope = app.mutationContext?.scope || argv.scope || '';
35
41
  if (!scope) {
36
42
  try {
37
43
  const user = await getCurrentUser(app.sdk);
@@ -46,7 +52,7 @@ export function evalCmd(wrap) {
46
52
  }
47
53
  }
48
54
 
49
- if (scope) {
55
+ if (scope && !scopeSysId) {
50
56
  scopeSysId = await app.sdk.resolveScope(scope);
51
57
  if (!scopeSysId) {
52
58
  throw new Error(`Scope not found: ${scope}`);
@@ -1,15 +1,17 @@
1
+ import { flowsCmdDefinition } from '../command-families.js';
1
2
  import { searchFlows, formatFlowSearch } from '../flow-search.js';
2
3
  import fs from 'node:fs';
3
4
  import { prepareFlowClone, cloneFlow } from '../flow-clone.js';
4
5
  import { canUsePicker } from '../helpers.js';
5
6
  import { formatRecordForDisplay, formatCommandList, getStringField, interactiveList } from '../helpers.js';
6
7
  import { discoverFlowContextFields, normalizeFlowContext, summarizeFlowContexts, formatFlowContextSummary, aggregateFlowContextMappings, mergeFlowContextStats, buildFlowContextQuery } from '../flow-context.js';
7
- import { declareCapabilities } from '../capabilities.js';
8
+ import { docLink } from '../docs-links.js';
8
9
  import { inspectFlow } from '../flow-inspection.js';
9
10
  import { publishFlows, publishFlowLifecycle, publishDoctor, flowStatus } from '../flow-publish.js';
10
11
  import { resolveRecord, unwrapSysId } from '../resolve-record.js';
11
12
  import { createFlowFromManifest, updateFlowFromManifest, readCurrentUpdateSet, readCatalogItemVariables } from '../flow-create.js';
12
13
  import { alignUpdateSetCapture } from '../context.js';
14
+ import { assertMutationScope, assertMutationRecordScope } from '../intended-context.js';
13
15
  import { EXCLUDED_TRIGGER_TYPES, SUPPORTED_TRIGGER_TYPES, readTriggerCatalog, readTriggerInputDefinitions } from '../flow-triggers.js';
14
16
  import { testFlow } from '../flow-test.js';
15
17
  import { releaseOwnFlowSafeEdit } from '../flow-safe-edit.js';
@@ -73,7 +75,7 @@ function triggerGuidance(trigger) {
73
75
  };
74
76
  }
75
77
 
76
- declareCapabilities('flows', { mutationSubcommands: ['clone', 'copy', 'create', 'update', 'edit', 'delete', 'publish', 'test', 'unlock'] });
78
+
77
79
 
78
80
  function renderChecks(checks) {
79
81
  return checks.map((c) => {
@@ -86,9 +88,7 @@ export function flowsCmd(wrap) {
86
88
  const originalWrap = wrap;
87
89
  wrap = handler => originalWrap((argv, app) => cancelled(() => handler(argv, app)));
88
90
  return {
89
- command: 'flows [subcommand]',
90
- aliases: ['flow'],
91
- describe: 'Manage Flow Designer flows',
91
+ ...flowsCmdDefinition,
92
92
  builder: (yargs) => {
93
93
  return yargs
94
94
  .command({
@@ -96,7 +96,11 @@ export function flowsCmd(wrap) {
96
96
  describe: 'Download/decode visible flows into a private cache and search literal text (first use can be slow)',
97
97
  builder: y => y
98
98
  .positional('term', { type: 'string', describe: 'Case-insensitive literal text to find in readable definitions' })
99
- .option('refresh', { type: 'boolean', default: false, describe: 'Rebuild the decoded cache; warm searches still revalidate source access' }),
99
+ .option('refresh', { type: 'boolean', default: false, describe: 'Rebuild the decoded cache; warm searches still revalidate source access' })
100
+ .epilogue(`Example:
101
+ jsn flows search approval
102
+ Interactive use can pick a flow; scripts pass the term.
103
+ Documentation: ${docLink('flows')}`),
100
104
  handler: wrap(async (argv, app) => {
101
105
  app.requireInstance();
102
106
  const session = app.session || {};
@@ -316,6 +320,7 @@ export function flowsCmd(wrap) {
316
320
  resource: argv.action ? 'Custom action' : 'Flow',
317
321
  }));
318
322
 
323
+ await assertMutationRecordScope(app, argv.action ? 'sys_hub_action_type_definition' : 'sys_hub_flow', sysID);
319
324
  await confirmDesignerMutation(argv, app, `Publish and activate ${argv.action ? 'action' : 'flow'} ${sysID}?`);
320
325
  if (!argv.action) {
321
326
  const lifecycle = await publishFlowLifecycle(app.sdk, app.getEffectiveInstance(), sysID);
@@ -403,7 +408,12 @@ export function flowsCmd(wrap) {
403
408
  app.requireInstance();
404
409
  const identifier = await pickFlow(argv, app);
405
410
  if (identifier === undefined) return;
411
+ if (app.mutationContext?.verified) {
412
+ const source = await resolveRecord(app.sdk, { table: 'sys_hub_flow', identifier, matchField: 'name', resource: 'Flow' });
413
+ assertMutationScope(app.mutationContext, source.sys_scope, 'Flow clone source');
414
+ }
406
415
  const plan = await prepareFlowClone(app.sdk, app.getEffectiveInstance(), identifier, { ...argv, interactive: canUsePicker(app, argv) });
416
+ assertMutationScope(app.mutationContext, plan.scope, 'Flow clone');
407
417
  await confirmDesignerMutation(argv, app,
408
418
  `Clone ${plan.source.name} (${plan.source.id}) as ${JSON.stringify(plan.name)} in ${plan.scope}; inactive Draft, source unchanged`,
409
419
  ['flows', 'clone', plan.source.id, '--name', plan.name]);
@@ -432,6 +442,7 @@ export function flowsCmd(wrap) {
432
442
  } catch (error) {
433
443
  throw new Error(`Invalid flow manifest JSON: ${error.message}`, { cause: error });
434
444
  }
445
+ assertMutationScope(app.mutationContext, manifest.scope, 'Flow creation manifest');
435
446
  const result = await createFlowFromManifest(app.sdk, app.getEffectiveInstance(), manifest, {
436
447
  readUpdateSet: () => readCurrentUpdateSet(app.sdk),
437
448
  ensureCapture: intended => alignUpdateSetCapture(app.sdk, intended),
@@ -477,6 +488,11 @@ export function flowsCmd(wrap) {
477
488
  } catch (error) {
478
489
  throw new Error(`Invalid flow update manifest JSON: ${error.message}`, { cause: error });
479
490
  }
491
+ if (!argv.preview && app.mutationContext?.verified) {
492
+ const target = await resolveRecord(app.sdk, { table: 'sys_hub_flow', identifier, matchField: 'name', resource: 'Flow' });
493
+ assertMutationScope(app.mutationContext, target.sys_scope, 'Flow update target');
494
+ if (manifest.scope !== undefined) assertMutationScope(app.mutationContext, manifest.scope, 'Flow update manifest');
495
+ }
480
496
  if (!argv.preview) await confirmDesignerMutation(argv, app, `Update flow ${identifier}; unspecified components and inputs are preserved. A published flow is edited as its working definition: the published snapshot must stay unchanged.`);
481
497
  const result = await updateFlowFromManifest(app.sdk, app.getEffectiveInstance(), argv.identifier, manifest, {
482
498
  preview: argv.preview,
@@ -540,6 +556,7 @@ export function flowsCmd(wrap) {
540
556
  sysparm_limit: '1',
541
557
  }));
542
558
  if (!flow) throw errUsage(`Flow ${identifier} (${sysID}) was not found`);
559
+ assertMutationScope(app.mutationContext, flow.sys_scope, 'Flow deletion target');
543
560
  const name = getStringField(flow, 'name');
544
561
  const active = getStringField(flow, 'active') === 'true';
545
562
  const counted = async () => {
@@ -575,7 +592,7 @@ export function flowsCmd(wrap) {
575
592
  }),
576
593
  })
577
594
  .epilogue('Run "jsn flows <command> --help" for details. In a terminal you can omit the target and pick\n'
578
- + 'one; scripts use explicit identifiers and manifests.');
595
+ + `one; scripts use explicit identifiers and manifests.\nDocumentation: ${docLink('flows')}`);
579
596
  },
580
597
  handler: wrap(async (_argv, app) => {
581
598
  const summary = 'Manage Flow Designer flows from the sys_hub_flow table. Flow structure comes from the ProcessFlow API, so V1, V2 and subflow definitions all render in full.';
@@ -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', { mutationSubcommands: ['add', 'remove'] });
6
+ declareCapabilities('groupmembers', { 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', { mutationSubcommands: ['add', 'remove'] });
6
+ declareCapabilities('grouproles', { 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', { mutationSubcommands: ['create', 'update', 'delete'] });
4
+ declareCapabilities('groups', { mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
5
5
 
6
6
  export function groupsCmd(wrap) {
7
7
  return {
@@ -1,3 +1,4 @@
1
+ import { midserversCmdDefinition } from '../command-families.js';
1
2
  import fs from 'node:fs';
2
3
  import path from 'node:path';
3
4
  import process from 'node:process';
@@ -9,7 +10,6 @@ import { prepareWindowsRemoteMidServer, installWindowsRemoteMidServer, startWind
9
10
  import { prepareLinuxRemoteMidServer, installLinuxRemoteMidServer, startLinuxRemoteMidServer, stopLinuxRemoteMidServer, logsLinuxRemoteMidServer, removeLinuxRemoteMidServer } from '../midserver-linux-remote.js';
10
11
  import { downloadRemoteMidRecipe } from '../midserver-remote-recipe.js';
11
12
  import { FormatAuto } from '../output.js';
12
- import { declareCapabilities } from '../capabilities.js';
13
13
  import { resolveRecord, unwrapSysId } from '../resolve-record.js';
14
14
  import { detectDocker, defaultRun, installDockerMidServer, midInstallDirectory, normalizeMidName, validateMidCredentials } from '../midserver-install.js';
15
15
  import { detectDirectPlatform, followDirectLog, installDirectMidServer, readDirectInstallation, removeDirectInstallation, resolveDirectLogFile, runDirectInstallation } from '../midserver-direct.js';
@@ -20,7 +20,7 @@ const LIST_FIELDS = ['sys_id', 'name', 'status', 'host_name', 'ip_address', 'ver
20
20
  const DEFAULT_TIMEOUT = 120000;
21
21
  const DEFAULT_INTERVAL = 2000;
22
22
 
23
- declareCapabilities('midservers', { mutationSubcommands: ['add', 'remove', 'execute', 'start', 'stop', 'validate'] });
23
+
24
24
 
25
25
  function agentName(record) {
26
26
  const name = getStringField(record, 'name');
@@ -302,12 +302,7 @@ async function promptMidCredentials(app, argv) {
302
302
  const validation = await validateMidCredentials(app.getEffectiveInstance(), username, password);
303
303
  return { username, password, releaseName: validation.releaseName };
304
304
  } catch (error) {
305
- const answer = await input({ message: `${error.message}. Press Enter to retry or Q to quit:` });
306
- if (answer.trim().toLowerCase() === 'q') {
307
- const quit = new Error('MID Server installation cancelled');
308
- quit.code = 'cancelled';
309
- throw quit;
310
- }
305
+ await input({ message: `${error.message}. Press Enter to retry or Esc to cancel:` });
311
306
  username = argv.username || '';
312
307
  }
313
308
  }
@@ -422,9 +417,7 @@ async function showMidServerLogs(app, identifier, argv) {
422
417
 
423
418
  export function midserversCmd(wrap) {
424
419
  return {
425
- command: 'midservers [subcommand]',
426
- aliases: ['midserver', 'mid'],
427
- describe: 'Manage ServiceNow MID Servers and run commands through them',
420
+ ...midserversCmdDefinition,
428
421
  builder: (y) => y
429
422
  .command(midDiagnosticsCommand('issues', wrap))
430
423
  .command(midDiagnosticsCommand('events', wrap))
@@ -1,3 +1,4 @@
1
+ import { perfCmdDefinition } from '../command-families.js';
1
2
  import { errUsageHint, errUsage } from '../errors.js';
2
3
  import { captureRun, listRuns, getRun, compareRuns, formatRunDetailed, formatRunList, formatComparisonDetailed } from '../perf.js';
3
4
  import { topTransactionsCmd } from './transactions.js';
@@ -54,9 +55,7 @@ function compareHint(runId) {
54
55
 
55
56
  export function perfCmd(wrap) {
56
57
  return {
57
- command: 'perf [subcommand]',
58
- aliases: ['performance'],
59
- describe: 'Capture and compare read-only ServiceNow performance summaries',
58
+ ...perfCmdDefinition,
60
59
  builder: (y) => y
61
60
  .command({
62
61
  command: 'capture',
@@ -0,0 +1,9 @@
1
+ import { declareCapabilities } from '../capabilities.js';
2
+ import { inventoryCompareCommand } from '../instance-inventory.js';
3
+
4
+ declareCapabilities('plugins', { skipContextHeader: true });
5
+ export const pluginsCmd = wrap => ({
6
+ command: 'plugins', describe: 'Inspect platform plugin differences across instances',
7
+ builder: p => p.command(inventoryCompareCommand(wrap, 'plugins')),
8
+ handler: wrap(async (_argv, app) => app.ok({ commands: ['compare'] }, { summary: 'Use jsn compare --source pdi --target vendor for both inventories; jsn plugins compare --source pdi --target vendor for plugins only' })),
9
+ });
@@ -5,8 +5,10 @@ import { errUsage } from '../errors.js';
5
5
  import { AmbClient } from '../amb.js';
6
6
  import { watchRecord } from '../record-watch.js';
7
7
  import { declareCapabilities } from '../capabilities.js';
8
+ import { assertMutationRecordScope, assertMutationScope } from '../intended-context.js';
8
9
 
9
10
  declareCapabilities('records', {
11
+ mutationContext: 'table',
10
12
  mutationSubcommands: ['create', 'update', 'delete', 'bulk'],
11
13
  });
12
14
 
@@ -149,7 +151,8 @@ export function recordsCmd(wrap) {
149
151
  // Text/table fallback (or sys-id direct lookup)
150
152
  const fields = resolveFieldsParam(columns);
151
153
  const params = recordListParams({ limit: argv['sys-id'] ? 1 : argv.limit, offset: argv.offset, fields, query });
152
- const records = await listRecords(app.sdk, { table, params, displayValues: argv.displayValues });
154
+ const responseMetadata = {};
155
+ const records = await listRecords(app.sdk, { table, params, displayValues: argv.displayValues, responseMetadata });
153
156
  const missingColumns = fields ? findOmittedColumns(records, columns) : [];
154
157
  const presentColumns = missingColumns.length ? columns.filter(c => !missingColumns.includes(c)) : columns;
155
158
  const displayRecords = fields && !argv.displayValues ? records.map(r => formatRecordForDisplay(r, presentColumns)) : records;
@@ -160,7 +163,10 @@ export function recordsCmd(wrap) {
160
163
  const countsOn = argv.count !== false && profile.include_counts !== false;
161
164
  let total;
162
165
  if (countsOn && !argv['sys-id']) {
163
- try { total = await app.sdk.aggregateCount(table, query); } catch { total = undefined; }
166
+ total = responseMetadata.total;
167
+ if (total === undefined) {
168
+ try { total = await app.sdk.aggregateCount(table, query); } catch { total = undefined; }
169
+ }
164
170
  }
165
171
 
166
172
  const breadcrumbs = [
@@ -529,6 +535,10 @@ export function recordsCmd(wrap) {
529
535
  offset += recs.length;
530
536
  }
531
537
  const targets = sysIDs.slice(0, argv.limit);
538
+ if (app.mutationContext?.verified) {
539
+ if (Object.hasOwn(set, 'sys_scope')) assertMutationScope(app.mutationContext, set.sys_scope, 'Bulk payload');
540
+ for (const id of targets) await assertMutationRecordScope(app, argv.table, id);
541
+ }
532
542
  let updated = 0;
533
543
  const failures = [];
534
544
  for (const id of targets) {
@@ -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: ['create', 'set'] });
6
+ declareCapabilities('scopes', { 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', { mutationSubcommands: ['create'] });
17
+ declareCapabilities('scrapi', { transactionScopeOption: 'scope', mutationSubcommands: ['create'] });
18
18
 
19
19
  /**
20
20
  * Parse a --resource flag value of the form:
@@ -257,7 +257,7 @@ export function scrapiCmd(wrap) {
257
257
  const description = argv.description || '';
258
258
 
259
259
  // 2. Resolve scope if provided
260
- let scopeSysId = null;
260
+ let scopeSysId = app.mutationContext?.application_id || null;
261
261
  if (argv.scope) {
262
262
  scopeSysId = await app.sdk.resolveScope(argv.scope);
263
263
  if (!scopeSysId) {
@@ -41,40 +41,10 @@ const setupHelp = () => [
41
41
  'Configure settings directly: jsn setup --configure-defaults or jsn setup --configure-docs.',
42
42
  ].join('\n');
43
43
 
44
- /** The setup hub prompt; q and Escape resolve with no selected action. */
45
- export const authHubPrompt = async (...args) => {
46
- const { createPrompt, useKeypress, usePagination, useState, isDownKey, isEnterKey, isUpKey } = await import('@inquirer/core');
47
- return createPrompt((config, done) => {
48
- const [active, setActive] = useState(0);
49
- const choices = config.choices;
50
-
51
- useKeypress((key) => {
52
- if (key.name === 'q' || key.name === 'escape') {
53
- done(undefined);
54
- return;
55
- }
56
- if (isEnterKey(key)) {
57
- done(choices[active].value);
58
- return;
59
- }
60
- if (isUpKey(key) && active > 0) setActive(active - 1);
61
- if (isDownKey(key) && active < choices.length - 1) setActive(active + 1);
62
- });
63
-
64
- const page = usePagination({
65
- items: choices,
66
- active,
67
- // Pagination budgets terminal lines, including the section headings.
68
- pageSize: choices.length + new Set(choices.map(choice => choice.section)).size * 2 - 1,
69
- loop: false,
70
- renderItem: ({ item, isActive }) => {
71
- const index = choices.indexOf(item);
72
- const heading = choices[index - 1]?.section !== item.section ? `${index ? '\n' : ''} ${item.section}\n` : '';
73
- return `${heading}${isActive ? '❯' : ' '} ${item.name}`;
74
- },
75
- });
76
- return `${config.message}\n${page}\n\n↑↓ navigate • ⏎ select • q/Esc exit`;
77
- })(...args);
44
+ /** The setup hub shares searchable local menus; Escape leaves the hub. */
45
+ export const authHubPrompt = async (config = {}, context = {}) => {
46
+ const { select, escapeResult } = await import('../prompts.js');
47
+ return select({ ...config, escapeValue: escapeResult(undefined) }, context);
78
48
  };
79
49
 
80
50
  /** Interactive hub: what do you want to do? Returns an action or undefined on exit. */
@@ -1,6 +1,6 @@
1
+ import { skippedUpdatesCmdDefinition } from '../command-families.js';
1
2
  import { checkbox, select, confirm } from '../prompts.js';
2
3
  import { canUsePicker, interactiveList, getStringField } from '../helpers.js';
3
- import { declareCapabilities } from '../capabilities.js';
4
4
  import { errUsage } from '../errors.js';
5
5
  import { discoverSkippedUpdates, reviewSkippedUpdate, prepareSkippedBatch, processSkippedBatch, raw, SKIP_TABLE } from '../skipped-updates.js';
6
6
 
@@ -27,7 +27,6 @@ export function renderSkippedPreview(preview) {
27
27
  }
28
28
 
29
29
  export function skippedUpdatesCmd(wrap, ui = {}) {
30
- declareCapabilities('skipped-updates', { mutationSubcommands: ['process'] });
31
30
  const prompts = { checkbox, select, confirm, canUsePicker, interactiveList, ...ui };
32
31
  async function showReview(app, id) {
33
32
  const review = await reviewSkippedUpdate(app.sdk, id);
@@ -49,7 +48,7 @@ export function skippedUpdatesCmd(wrap, ui = {}) {
49
48
  { name: 'Return to base system, discard customization', value: 'revert' }] });
50
49
  return { ids, action, instance: app.getEffectiveInstance() };
51
50
  }
52
- return { command: 'skipped-updates', describe: 'Review and process existing unresolved skipped updates across all upgrade history',
51
+ return { ...skippedUpdatesCmdDefinition,
53
52
  builder: y => y
54
53
  .command({ command: 'list', describe: 'Discover unresolved skips instance-wide, independent of new upgrades',
55
54
  builder: y => y.option('limit', { type: 'number', default: 100, describe: 'Page size, maximum 500' })
@@ -1,3 +1,4 @@
1
+ import { inventoryCompareCommand } from '../instance-inventory.js';
1
2
  import { confirmDelete, quoteShellArg, truncateString } from '../helpers.js';
2
3
  import { declareCapabilities } from '../capabilities.js';
3
4
  import { AppError, errUsage } from '../errors.js';
@@ -16,6 +17,7 @@ import {
16
17
  // App Client, which writes installed-application state rather than capturing
17
18
  // metadata into the selected application/update set.
18
19
  declareCapabilities('store', {
20
+ skipContextHeaderSubcommands: ['compare'],
19
21
  mutationSubcommands: ['install', 'update'],
20
22
  mutationContextExemptSubcommands: ['install', 'update'],
21
23
  });
@@ -229,6 +231,7 @@ export function storeCmd(wrap) {
229
231
  command: 'store [subcommand]',
230
232
  describe: 'Discover ServiceNow Store applications, inspect versions and entitlement, and request explicit installs/updates',
231
233
  builder: y => y
234
+ .command(inventoryCompareCommand(wrap, 'store'))
232
235
  .command({
233
236
  command: 'list',
234
237
  describe: 'List Store applications for a tab (read-only)',
@@ -302,7 +305,7 @@ export function storeCmd(wrap) {
302
305
  handler: wrap(async (argv, app) => runLifecycle(argv, app, 'update')),
303
306
  }),
304
307
  handler: wrap(async (argv, app) => {
305
- report(app, argv, { commands: ['search', 'list', 'show', 'status', 'install', 'update'] }, {
308
+ report(app, argv, { commands: ['compare', 'search', 'list', 'show', 'status', 'install', 'update'] }, {
306
309
  summary: 'ServiceNow Store applications',
307
310
  breadcrumbs: [hint('list', 'jsn store list --tab installed', 'List installed applications'),
308
311
  hint('search', 'jsn store search "<term>"', 'Search applications available to this instance'),