@jacebenson/jsn 5.5.7 → 5.5.8

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
package/README.md CHANGED
@@ -15,7 +15,7 @@ jsn setup
15
15
 
16
16
  Setup connects a named profile to your instance. Its default preset allows writes, so enable read-only mode before exploring. See [setup and authentication](https://jsn.jace.pro/docs/setup/).
17
17
 
18
- For unreleased changes, use `npm install -g @jacebenson/jsn@dev`; see [channels and updates](https://github.com/jacebenson/jsn/blob/main/docs/releases.md).
18
+ For unreleased changes, use `npm install -g @jacebenson/jsn@dev`; see [channels and updates](https://github.com/jacebenson/jsn/blob/main/site/docs/maintainers/releases.md).
19
19
 
20
20
  ## Read and discover
21
21
 
@@ -42,6 +42,21 @@ Writes are not universally dry-run operations or confirmation prompts. Inspect e
42
42
 
43
43
  Inspect the bundled skill with `jsn skill show`, then use `jsn skill install` to select your agent or `jsn skill install --target hermes` for Hermes. Reinstall after upgrading JSN; reinstalling replaces recorded copies, including local edits. See [agent installation](https://jsn.jace.pro/docs/agents/).
44
44
 
45
+ ## Local prompt experiment
46
+
47
+ From the repository root, run `node cli/scripts/prompt-demo.mjs` in a terminal.
48
+ It uses synthetic servers only. Nothing connects to ServiceNow or changes profiles.
49
+ Type to filter, use arrows to move and Enter to select. Down past the last loaded
50
+ server fetches another page. Escape cancels. Ctrl+C or Ctrl+D exits the prompt.
51
+ The forms menu includes masked input, confirmation and a checklist. The editor
52
+ menu uses your `$VISUAL` or `$EDITOR`, falling back to `vi`.
53
+
54
+ From `cli/`, `npm ci` installs lint and test dependencies without Inquirer.
55
+ Run `npm run test:pty` for the Linux Python 3 PTY checks. `npm test` also collects
56
+ them. Mutation tooling is not part of normal installs. `npm run test:mutation`
57
+ fetches pinned Stryker 10.1.1 on demand and uses `stryker.config.json`, retaining
58
+ the offline mutation-safety tests. Its execution is separate from normal tests.
59
+
45
60
  ## Go deeper
46
61
 
47
62
  - [CLI guide and feature workflows](https://jsn.jace.pro/docs/cli-guide/)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.5.7",
3
+ "version": "5.5.8",
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": {
@@ -9,8 +9,9 @@
9
9
  "main": "src/cli.js",
10
10
  "scripts": {
11
11
  "test": "node scripts/test.mjs",
12
- "test:mutation": "stryker run",
13
- "lint": "npx eslint src/ bin/ test/",
12
+ "test:mutation": "npm exec --yes --package=@stryker-mutator/core@10.1.1 -- stryker run stryker.config.json",
13
+ "test:pty": "node --test test/pty/prompts-pty.test.js",
14
+ "lint": "eslint src/ bin/ test/",
14
15
  "start": "node bin/jsn.js"
15
16
  },
16
17
  "keywords": [
@@ -23,8 +24,6 @@
23
24
  "repository": "https://github.com/jacebenson/jsn",
24
25
  "license": "MIT",
25
26
  "dependencies": {
26
- "@inquirer/core": "^10.3.2",
27
- "@inquirer/prompts": "^7.10.1",
28
27
  "commonmark": "^0.31.2",
29
28
  "js-yaml": "^5.5.0",
30
29
  "saxes": "^6.0.0",
@@ -32,7 +31,7 @@
32
31
  },
33
32
  "devDependencies": {
34
33
  "@eslint/js": "^10.0.1",
35
- "@stryker-mutator/core": "^10.0.0",
34
+ "eslint": "^10.15.0",
36
35
  "globals": "^17.6.0"
37
36
  },
38
37
  "files": [
@@ -22,7 +22,15 @@ Discover commands with `jsn --help`, `jsn discover "search words"`, and
22
22
  For development:
23
23
 
24
24
  1. Choose or create the application scope and update set.
25
- 2. Do the work, keeping related changes together.
25
+ 2. Supply task-owned `--expect-scope <scope/name/id>` and
26
+ `--expect-update-set <name/id>` on customization writes, or explicitly save
27
+ profile-and-instance-bound `write_context` in local `.servicenow/config.json`.
28
+ Never derive intended values from current preferences. `--force` cannot bypass
29
+ missing intent, unknown context or mismatches. Domain-scoped customization
30
+ currently refuses, including `--expect-domain`, because `X-Now-Domain` does not
31
+ prove effective domain. Inspect with `auth status --context`; `--local` is offline.
32
+ Reads never print or fetch automatic context. Ordinary ticket/data edits do not
33
+ need customization expectations. Keep related development changes together.
26
34
  3. Verify the results on the instance and report where changes were captured.
27
35
  4. Offer to run relevant existing ATFs and instance scans, or create missing checks.
28
36
  5. Ask whether anything else belongs in the update set. If the user confirms
package/src/app.js CHANGED
@@ -10,14 +10,12 @@
10
10
  import { AuthManager } from './auth.js';
11
11
  import { createAuthRecovery } from './auth-recovery.js';
12
12
  import { SDKClient } from './sdk.js';
13
- import { OutputWriter, FormatAuto, FormatJSON, FormatMarkdown, FormatQuiet, FormatStyled, hyperlink } from './output.js';
13
+ import { OutputWriter, FormatAuto, FormatJSON, FormatMarkdown, FormatQuiet, FormatStyled } from './output.js';
14
14
  import { saveConfig, isTrustedCredentialDestination } from './config.js';
15
15
  import { resolveSession, applySession, contextFromSession, requireSessionInstance } from './session.js';
16
- import { getCurrentUser, getCurrentApplication, getCurrentUpdateSet } from './context.js';
17
16
  import { errUsage, errAuth } from './errors.js';
18
17
  import { canPrompt, canUsePicker } from './helpers.js';
19
18
  import { guardMutationContext } from './mutation-context.js';
20
- import process from 'node:process';
21
19
 
22
20
 
23
21
  export class App {
@@ -86,85 +84,12 @@ export class App {
86
84
  return this.session?.instance || '';
87
85
  }
88
86
 
89
- async printContextHeader(argv = {}) {
90
- if (!this.getEffectiveInstance() || !this.sdk) return;
91
- if (process.env.JSN_NO_HEADER) return;
92
- if (this.output.getFormat() === FormatJSON || this.output.getFormat() === FormatQuiet) return;
93
-
94
- // The banner is a terminal affordance, never data. `--get`/`--select`
95
- // prints an extracted JSON value while the format still reports pretty, so
96
- // a banner on stderr merged with `2>&1` landed in front of the JSON and
97
- // broke `jsn ... 2>&1 | jq` / `json.load(sys.stdin)` at character 0. Skip
98
- // it whenever an extraction was requested or stderr is not a terminal
99
- // (nobody reads it there, and it costs five HTTP requests per command:
100
- // user, application preference, update-set preference, scope, update set).
101
- if (argv.get !== undefined && argv.get !== null && argv.get !== false) return;
102
- if (process.stderr.isTTY !== true) return;
103
-
104
- let userDisplayName = 'Unknown';
105
- let userSysID = '';
106
-
107
- try {
108
- const user = await getCurrentUser(this.sdk);
109
- if (user) {
110
- userDisplayName = user.name || user.user_name;
111
- userSysID = user.sys_id;
112
- this.context.username = userDisplayName;
113
- }
114
- } catch {
115
- // ignore
116
- }
117
-
118
- let displayUserName = userDisplayName;
119
- if (displayUserName.length > 10) {
120
- displayUserName = displayUserName.slice(0, 6) + '...';
121
- }
122
-
123
- // Both lookups depend on the user, but not on one another.
124
- const [application, selectedUpdateSet] = userSysID ? await Promise.all([
125
- getCurrentApplication(this.sdk, userSysID, { unknownWhenMissing: true }).catch(() => null),
126
- getCurrentUpdateSet(this.sdk, userSysID).catch(() => null),
127
- ]) : [null, null];
128
- const scope = application?.scope || 'unknown';
129
- const updateSet = selectedUpdateSet?.name && selectedUpdateSet.name !== '-'
130
- ? selectedUpdateSet.name : 'unknown';
131
- const updateSetSysID = selectedUpdateSet?.name && selectedUpdateSet.name !== '-'
132
- ? selectedUpdateSet.sys_id : '';
133
- this.context.scope = scope;
134
- this.context.updateSet = updateSet;
135
-
136
- const instance = this.getEffectiveInstance();
137
- const instanceLink = instance;
138
- const userLink = `${instance}/sys_user_list.do?sysparm_query=sys_id=${userSysID}`;
139
- const scopeLink = `${instance}/sys_scope.do?sysparm_query=scope=${scope}`;
140
- const updateSetLink = updateSetSysID
141
- ? `${instance}/sys_update_set.do?sys_id=${updateSetSysID}`
142
- : `${instance}/sys_update_set_list.do`;
143
-
144
- const scopeFormatted = `[${scope}]`;
145
-
146
- // Terminal hyperlinks are invisible in a TTY and garbage in a pipe, so the
147
- // banner only wraps values when stderr is actually a terminal.
148
- const link = (text, url) => (process.stderr.isTTY === true ? hyperlink(text, url) : text);
149
-
150
- // Read-only profiles get a lock badge on every command run, so the
151
- // armed safety is always visible (not just in `auth status`).
152
- const roBadge = this.session?.readOnly === true ? ' 🔒' : '';
153
-
154
- process.stderr.write('# Use `jsn scopes` to change scope, `jsn updatesets set` to change updateset\n');
155
- process.stderr.write('PROFILE USER [SCOPE] UPDATE SET\n');
156
-
157
- const profileStr = `${link(String(this.context.profileName).padEnd(9), instanceLink)}${roBadge}`;
158
- const userStr = link(String(displayUserName).padEnd(9), userLink);
159
- const scopeStr = link(String(scopeFormatted).padEnd(17), scopeLink);
160
- const updateSetStr = link(String(updateSet), updateSetLink);
161
-
162
- process.stderr.write(`${profileStr} ${userStr} ${scopeStr} ${updateSetStr}\n\n`);
163
-
164
- }
87
+ // Retained for SDK consumers. Automatic context banners are retired.
88
+ async printContextHeader() {}
165
89
 
166
90
  async guardMutationContext(argv) {
167
91
  this.mutationContext = await guardMutationContext(this, argv);
92
+ if (this.sdk) this.sdk.mutationContext = this.mutationContext;
168
93
  }
169
94
 
170
95
  ok(data, opts = {}) {
@@ -0,0 +1,13 @@
1
+ // Ordered results with at most four independent reads in flight. Callers must
2
+ // finish dependency discovery before scheduling; this helper never retries.
3
+ export async function boundedReads(items, read) {
4
+ const results = new Array(items.length);
5
+ let next = 0;
6
+ await Promise.all(Array.from({ length: Math.min(4, items.length) }, async () => {
7
+ while (next < items.length) {
8
+ const index = next++;
9
+ results[index] = await read(items[index], index);
10
+ }
11
+ }));
12
+ return results;
13
+ }
@@ -8,6 +8,11 @@
8
8
  // // Subcommand verbs that mutate instance state. The mutation guard
9
9
  // // (src/mutations.js) derives its command-path list from these.
10
10
  // mutationSubcommands: ['create', 'update', 'delete'],
11
+ // // Omitted means conservative customization; operational skips capture
12
+ // // requirements, table follows sys_db_object ancestry to sys_metadata.
13
+ // mutationContext: 'table', table: 'sys_script',
14
+ // // Only declared flags are transaction overrides, not creation fields.
15
+ // transactionScopeOption: 'scope',
11
16
  // // Command runs without a configured instance (joins the middleware
12
17
  // // skip-list for the instance guard).
13
18
  // noInstance: true,
@@ -31,9 +36,9 @@
31
36
  // Note: yargs strips custom properties off command modules when it
32
37
  // registers them (only original/description/handler/builder survive in
33
38
  // getCommandHandlers()), so declarations live in this module-level map,
34
- // keyed by root command name. Declaration happens when the command module
35
- // factory runs — i.e. during cli.js's registration chain — so the registry
36
- // is complete once buildCLI() returns.
39
+ // keyed by root command name. Eager factories declare during registration;
40
+ // lazy families declare in command-families.js, never in a deferred factory.
41
+ // The registry is complete once buildCLI() returns, before path resolution.
37
42
 
38
43
  const REGISTRY = new Map();
39
44
 
@@ -1,6 +1,7 @@
1
1
  import { parseArgs } from 'node:util';
2
2
  import process from 'node:process';
3
3
  import { renderSubcommandHelp } from './help.js';
4
+ import { resolveDocLink } from './docs-links.js';
4
5
 
5
6
  const camel = (name) => name.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
6
7
  const names = (x) => typeof x === 'string' ? [x] : (x || []);
@@ -37,6 +38,12 @@ class CommandNode {
37
38
 
38
39
  build() {
39
40
  if (this.built) return;
41
+ if (this.definition.load) {
42
+ const definition = this.definition.load();
43
+ // Root identity is lightweight and authoritative. Implementations only
44
+ // supply builders/handlers; loading must not change token ownership.
45
+ this.definition = { ...definition, ...this.definition, load: undefined };
46
+ }
40
47
  this.built = true;
41
48
  if (typeof this.definition.builder === 'function') this.definition.builder(this.api());
42
49
  }
@@ -292,10 +299,10 @@ export class LocalCLI {
292
299
  * help page. Machine discovery leaves it out, so the JSON schema and bytes
293
300
  * stay unchanged.
294
301
  */
295
- commandRegistry({ summaries = false } = {}) {
302
+ commandRegistry({ summaries = false, shallow = false } = {}) {
296
303
  const visible = (node) => !node.definition.hidden;
297
304
  const serialize = (node) => {
298
- node.build();
305
+ if (!shallow) node.build();
299
306
  const entry = {
300
307
  name: node.name,
301
308
  command: node.definition.command || node.name,
@@ -398,9 +405,25 @@ export class LocalCLI {
398
405
  description: node.definition.describe,
399
406
  commands,
400
407
  options: this._optionRows(node),
401
- epilogue: node.epilogueText,
408
+ epilogue: this._docsEpilogue(node, path),
402
409
  }));
403
410
  }
411
+
412
+ /**
413
+ * Every help page names the maintained documentation for its command family.
414
+ * The family comes from the parser's canonical resolved path, so aliases
415
+ * (`jsn flow`) and nested commands (`jsn records list`) reach the same
416
+ * registered topic without a per-subcommand footer. A page whose authored
417
+ * epilogue already prints that URL keeps its own wording rather than repeating
418
+ * it, and a family with no migrated guide gains no invented URL.
419
+ */
420
+ _docsEpilogue(node, path) {
421
+ const base = node.epilogueText;
422
+ const link = path.length ? resolveDocLink(path[0]) : null;
423
+ if (!link || (base && base.includes(link))) return base;
424
+ const line = `Documentation: ${link}`;
425
+ return base ? `${base}\n${line}` : line;
426
+ }
404
427
  async parse() {
405
428
  // Reject stale installed shell snippets instead of dispatching their words
406
429
  // as ordinary commands (for example the `r` alias).
package/src/cli.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { flowsCmd, workflowsCmd, midserversCmd, subscriptionsCmd, customizationsCmd, skippedUpdatesCmd, docsCmd, perfCmd } from './command-families.js';
1
2
  import { visibleCommandRegistry } from './command-audience.js';
2
3
  // Root CLI using the local yargs-compatible adapter
3
4
 
@@ -11,8 +12,7 @@ import { resolveSession, applySession } from './session.js';
11
12
  import { renderHelp, renderTips } from './help.js';
12
13
  import { isMutationCommand, refreshMutationCommands } from './mutations.js';
13
14
  import { maybeShowHome } from './welcome.js';
14
- import { skippedUpdatesCmd } from './commands/skipped-updates.js';
15
- import { isLocalPreview, noInstanceCommands, dailyCheckSkipCommands, skipsContextHeader } from './capabilities.js';
15
+ import { isLocalPreview, noInstanceCommands, dailyCheckSkipCommands } from './capabilities.js';
16
16
  import { guardExit, exitWithError, AppError, CodeUsage } from './errors.js';
17
17
  import { formatCommandList } from './helpers.js';
18
18
 
@@ -44,7 +44,6 @@ import { versionCmd } from './commands/version.js';
44
44
  import { upgradeCmd } from './commands/upgrade.js';
45
45
  import { skillCmd, checkSkill } from './commands/skill.js';
46
46
  import { getVersion, checkLatest, getReleaseChannel, getInstallCommand } from './commands/version.js';
47
- import { docsCmd } from './commands/docs/docs.js';
48
47
 
49
48
  // Table and platform commands registered at root level for progressive disclosure
50
49
  import {
@@ -64,8 +63,6 @@ import {
64
63
  uimacrosCmd, uxlistsCmd, uxapplicabilityCmd,
65
64
  } from './commands/_simple.js';
66
65
  import { decisiontablesCmd } from './commands/decisiontables.js';
67
- import { flowsCmd } from './commands/flows.js';
68
- import { workflowsCmd } from './commands/workflows.js';
69
66
  import { formsCmd } from './commands/forms.js';
70
67
  import { listsCmd } from './commands/lists.js';
71
68
  import { updateSetsCmd } from './commands/updatesets.js';
@@ -79,10 +76,9 @@ import { b4rulesCmd } from './commands/b4rules.js';
79
76
  import { atfCmd } from './commands/atf.js';
80
77
  import { scanCmd } from './commands/scan.js';
81
78
  import { storeCmd } from './commands/store.js';
79
+ import { pluginsCmd } from './commands/plugins.js';
80
+ import { compareCmd } from './commands/compare.js';
82
81
  import { approvalsCmd } from './commands/approvals.js';
83
- import { perfCmd } from './commands/perf.js';
84
- import { customizationsCmd } from './commands/customizations.js';
85
- import { midserversCmd } from './commands/midservers.js';
86
82
  import { diffCmd } from './commands/diff.js';
87
83
  import { graphqlCmd } from './commands/graphql.js';
88
84
 
@@ -155,6 +151,9 @@ export function buildCLI() {
155
151
  .options({
156
152
  'all-commands': { type: 'boolean', describe: 'Show the full command list, including admin and developer tools' },
157
153
 
154
+ 'expect-scope': { type: 'string', description: 'Intended customization scope, exact scope/name or sys_id' },
155
+ 'expect-update-set': { type: 'string', description: 'Intended in-progress capture set, exact name or sys_id' },
156
+ 'expect-domain': { type: 'string', description: 'Intended domain; refuses writes when effective domain cannot be proven' },
158
157
  force: {
159
158
  type: 'boolean',
160
159
  description: 'Approve Global + Default mutation context only after user approval; delete commands also use this for their separate confirmation',
@@ -351,10 +350,7 @@ export function buildCLI() {
351
350
  }
352
351
  }
353
352
 
354
- // Print context header for interactive terminals
355
- if (!skipsContextHeader(argv)) {
356
- await argv.app.printContextHeader(argv);
357
- }
353
+ // Reads never probe or print runtime context. Writes use the guard result.
358
354
  })
359
355
  // CONFIGURATION
360
356
  .command(setupCmd(wrap))
@@ -444,6 +440,9 @@ export function buildCLI() {
444
440
  .command(atfCmd(wrap))
445
441
  .command(scanCmd(wrap))
446
442
  .command(storeCmd(wrap))
443
+ .command(pluginsCmd(wrap))
444
+ .command(compareCmd(wrap))
445
+ .command(subscriptionsCmd(wrap))
447
446
  .command(approvalsCmd(wrap))
448
447
  .command(skippedUpdatesCmd(wrap))
449
448
  .command(perfCmd(wrap))
@@ -548,7 +547,7 @@ export function buildCLI() {
548
547
  const welcome = maybeShowHome({ argv: formatArgv, requestedFormat, cfg: config });
549
548
  if (!welcome) {
550
549
  const registry = visibleCommandRegistry(
551
- cliInstance.commandRegistry({ summaries: true }), config, formatArgv);
550
+ cliInstance.commandRegistry({ summaries: true, shallow: true }), config, formatArgv);
552
551
  process.stdout.write(renderHelp(config, registry, { full: formatArgv?.allCommands === true }) + '\n');
553
552
  }
554
553
  process.exit(0);
@@ -574,7 +573,7 @@ export function buildCLI() {
574
573
  const options = cliInstance.parseGlobalOptions(process.argv.slice(2));
575
574
  const config = loadConfig(options);
576
575
  const registry = visibleCommandRegistry(
577
- cliInstance.commandRegistry({ summaries: true }), config, options);
576
+ cliInstance.commandRegistry({ summaries: true, shallow: true }), config, options);
578
577
  return renderHelp(config, registry, { full: options?.allCommands === true });
579
578
  };
580
579
 
@@ -0,0 +1,68 @@
1
+ // Lightweight family identity and safety declarations. Implementations reuse these
2
+ // objects: aliases, root help and mutation policy never depend on loading a handler.
3
+ import { createRequire } from 'node:module';
4
+ import { declareCapabilities } from './capabilities.js';
5
+
6
+ // Node >=24 supports synchronous require(ESM). These implementation graphs must
7
+ // remain synchronous (no top-level await); this preserves the synchronous adapter
8
+ // and complete-discovery API without pre-parsing argv or a generated catalog.
9
+ const require = createRequire(import.meta.url);
10
+
11
+ export const flowsCmdDefinition = {
12
+ command: 'flows [subcommand]',
13
+ aliases: ['flow'],
14
+ describe: 'Manage Flow Designer flows',
15
+ };
16
+ declareCapabilities('flows', { transactionScopeOption: 'scope', mutationContextExemptSubcommands: ['test', 'unlock'], mutationSubcommands: ['clone', 'copy', 'create', 'update', 'edit', 'delete', 'publish', 'test', 'unlock'] });
17
+ export const flowsCmd = wrap => ({ ...flowsCmdDefinition, load: () => require('./commands/flows.js').flowsCmd(wrap) });
18
+
19
+ export const workflowsCmdDefinition = {
20
+ command: 'workflows [subcommand]',
21
+ aliases: ['workflow'],
22
+ describe: 'Inspect legacy Workflow Editor workflows (read-only)',
23
+ };
24
+ declareCapabilities('workflows', { mutationSubcommands: [] });
25
+ export const workflowsCmd = wrap => ({ ...workflowsCmdDefinition, load: () => require('./commands/workflows.js').workflowsCmd(wrap) });
26
+
27
+ export const midserversCmdDefinition = {
28
+ command: 'midservers [subcommand]',
29
+ aliases: ['midserver', 'mid'],
30
+ describe: 'Manage ServiceNow MID Servers and run commands through them',
31
+ };
32
+ declareCapabilities('midservers', { mutationContext: 'operational', mutationSubcommands: ['add', 'remove', 'execute', 'start', 'stop', 'validate'] });
33
+ export const midserversCmd = wrap => ({ ...midserversCmdDefinition, load: () => require('./commands/midservers.js').midserversCmd(wrap) });
34
+
35
+ export const subscriptionsCmdDefinition = {
36
+ command: 'subscriptions [subcommand]', describe: 'Inspect local metering schedules and compare illustrative ITOM populations',
37
+ };
38
+ declareCapabilities('subscriptions', { noInstance: true, skipDailyChecks: true, mutationSubcommands: [] });
39
+ export const subscriptionsCmd = wrap => ({ ...subscriptionsCmdDefinition, load: () => require('./commands/subscriptions.js').subscriptionsCmd(wrap) });
40
+
41
+ export const customizationsCmdDefinition = {
42
+ command: 'customizations [subcommand]',
43
+ describe: 'Capture and compare read-only customization evidence locally',
44
+ };
45
+ declareCapabilities('customizations', { noInstance: true, skipDailyChecks: true, mutationSubcommands: [] });
46
+ export const customizationsCmd = wrap => ({ ...customizationsCmdDefinition, load: () => require('./commands/customizations.js').customizationsCmd(wrap) });
47
+
48
+ export const skippedUpdatesCmdDefinition = {
49
+ command: 'skipped-updates', describe: 'Review and process existing unresolved skipped updates across all upgrade history',
50
+ };
51
+ declareCapabilities('skipped-updates', { mutationSubcommands: ['process'] });
52
+ export const skippedUpdatesCmd = wrap => ({ ...skippedUpdatesCmdDefinition, load: () => require('./commands/skipped-updates.js').skippedUpdatesCmd(wrap) });
53
+
54
+ export const docsCmdDefinition = {
55
+ command: 'docs [query..]',
56
+ defaultPositionals: true,
57
+ describe: 'Search ServiceNow documentation (hosted by default; configure your service in setup)',
58
+ };
59
+ declareCapabilities('docs', { noInstance: true, skipDailyChecks: true });
60
+ export const docsCmd = wrap => ({ ...docsCmdDefinition, load: () => require('./commands/docs/docs.js').docsCmd(wrap) });
61
+
62
+ export const perfCmdDefinition = {
63
+ command: 'perf [subcommand]',
64
+ aliases: ['performance'],
65
+ describe: 'Capture and compare read-only ServiceNow performance summaries',
66
+ };
67
+
68
+ export const perfCmd = wrap => ({ ...perfCmdDefinition, load: () => require('./commands/perf.js').perfCmd(wrap) });
@@ -99,6 +99,7 @@ export function buildDevCmd(name, table, aliases, defaultColumns, wrap, opts = {
99
99
  const readOnly = opts.readOnly || false;
100
100
  // Capability declaration: the readOnly flag drives the mutation registry.
101
101
  declareCapabilities(name, {
102
+ mutationContext: 'table', table,
102
103
  mutationSubcommands: readOnly ? [] : ['create', 'update', 'delete'],
103
104
  });
104
105
  const scopeValidation = opts.scopeValidation || false;
@@ -11,7 +11,7 @@ import { declareCapabilities } from '../capabilities.js';
11
11
  export function buildTicketCommands(table, displayName, alias, defaultColumns, stateMap, iconFn, wrap, opts = {}) {
12
12
  // Ticket-style CRUD: list/show are reads; create/update/delete mutate.
13
13
  // Root-level command only.
14
- declareCapabilities(displayName, { mutationSubcommands: ['create', 'update', 'delete'] });
14
+ declareCapabilities(displayName, { mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
15
15
  return {
16
16
  command: `${displayName} [subcommand]`,
17
17
  aliases: [table, alias],
@@ -4,6 +4,7 @@ import { resolveRecord, unwrapSysId } from '../resolve-record.js';
4
4
  import { declareCapabilities } from '../capabilities.js';
5
5
  import { ACTION_TABLE, actionScope } from '../processflow-actions.js';
6
6
  import { errUsage } from '../errors.js';
7
+ import { assertMutationScope } from '../intended-context.js';
7
8
  import { cancelled, pickDesignerRecord, designerScope, guidedActionCreate, guidedActionEdit, guidedActionTestInputs, interactiveDesigner, hasDefinitionData, confirmDesignerMutation } from '../flow-designer-interactive.js';
8
9
 
9
10
  const ACTION_COMMANDS = [
@@ -87,7 +88,7 @@ export const actionsCmd = wrap => {
87
88
  { action: 'list', cmd: 'jsn actions list', description: 'Back to actions' },
88
89
  ],
89
90
  });
90
- declareCapabilities('actions', { mutationSubcommands: ['create', 'update', 'edit', 'delete', 'test'] });
91
+ declareCapabilities('actions', { transactionScopeOption: 'scope', mutationContextExemptSubcommands: ['test'], mutationSubcommands: ['create', 'update', 'edit', 'delete', 'test'] });
91
92
  // Retain the common wrap and output controller; domain failures get a
92
93
  // structured error envelope and nonzero exit, never a success-shaped dispatch.
93
94
  const run = handler => wrap(async (argv, app) => {
@@ -110,6 +111,7 @@ export const actionsCmd = wrap => {
110
111
  const guided = !hasDefinitionData(argv) ? await guidedActionCreate(argv, app) : undefined;
111
112
  const definition = guided?.definition ?? parseDataArg(argv);
112
113
  const scope = guided?.scope ?? await designerScope(argv, app);
114
+ assertMutationScope(app.mutationContext, scope, 'Action creation');
113
115
  const result = await app.sdk.createProcessFlowAction(scope, definition);
114
116
  app.ok(result, { summary: `Created and verified action ${result.sys_id}` });
115
117
  }),
@@ -152,9 +154,11 @@ export const actionsCmd = wrap => {
152
154
  if (!hasDefinitionData(argv) && !interactiveDesigner(argv, app)) throw errUsage('Provide --data-file or --data for the full action definition in noninteractive mode');
153
155
  const id = await actionID(argv, app);
154
156
  if (id === undefined) return;
157
+ const scope = await actionScope(app.sdk, id, app.mutationContext?.application_id ?? argv.scope);
158
+ assertMutationScope(app.mutationContext, scope, 'Action target');
155
159
  const definition = hasDefinitionData(argv) ? parseDataArg(argv)
156
- : await guidedActionEdit(argv, app, await app.sdk.getProcessFlowAction(id, await actionScope(app.sdk, id, argv.scope)));
157
- const result = await app.sdk.updateProcessFlowAction(id, argv.scope, definition);
160
+ : await guidedActionEdit(argv, app, await app.sdk.getProcessFlowAction(id, scope));
161
+ const result = await app.sdk.updateProcessFlowAction(id, scope, definition);
158
162
  app.ok(result, { summary: `Saved and verified action ${id}` });
159
163
  }),
160
164
  })
@@ -216,7 +220,8 @@ export const actionsCmd = wrap => {
216
220
  handler: run(async (argv, app) => {
217
221
  const id = await actionID(argv, app);
218
222
  if (id === undefined) return;
219
- await actionScope(app.sdk, id, argv.scope);
223
+ const scope = await actionScope(app.sdk, id, app.mutationContext?.application_id ?? argv.scope);
224
+ assertMutationScope(app.mutationContext, scope, 'Action target');
220
225
  await confirmDesignerMutation(argv, app, `Delete action '${id}'`);
221
226
  await app.sdk.delete(ACTION_TABLE, id);
222
227
  // Verify the exact target is absent. Do not interpret a 403 as deletion.
@@ -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', { mutationSubcommands: ['approve', 'reject', 'submit'] });
28
+ declareCapabilities('approvals', { 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', { mutationSubcommands: ['run', 'run-suite'] });
30
+ declareCapabilities('atf', { mutationContext: 'operational', mutationSubcommands: ['run', 'run-suite'] });
31
31
 
32
32
  // sn_cicd progress statuses (now-sdk poller.ts)
33
33
  const PROGRESS_PENDING = '0';
@@ -4,7 +4,7 @@ import { confirmDelete, getStringField } from '../helpers.js';
4
4
  import { errUsage } from '../errors.js';
5
5
  import { declareCapabilities } from '../capabilities.js';
6
6
 
7
- declareCapabilities('attachments', { mutationSubcommands: ['upload', 'add'] });
7
+ declareCapabilities('attachments', { mutationContext: 'operational', mutationSubcommands: ['upload', 'add'] });
8
8
  const identifier = value => {
9
9
  if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/.test(value)) throw errUsage('Supply a safe record or attachment sys_id.');
10
10
  return value;
@@ -894,6 +894,8 @@ Examples:
894
894
  }
895
895
 
896
896
  export async function showAuthStatus(argv, app) {
897
+ if (argv.context && !argv.profile) argv = { ...argv, profile: app.session?.profileName || app.config.activeProfile || app.config.defaultProfile };
898
+ if (argv.context && !app.config.profiles?.[argv.profile]) throw errUsage('Select a configured profile for auth status --context.');
897
899
  const configuredDefault = app.config.profiles?.[app.config.defaultProfile];
898
900
  const defaultInstance = configuredDefault?.instance_url || app.config.instanceURL || '';
899
901
 
@@ -923,6 +925,7 @@ export async function showAuthStatus(argv, app) {
923
925
  let verified = null;
924
926
  let verifiedAt = null;
925
927
  let probe;
928
+ let runtimeContext = argv.context ? { verified: false, status: 'not_attempted' } : undefined;
926
929
  if (argv.local) {
927
930
  probe = { status: 'not_attempted', code: 'not_requested', classification: 'not_checked' };
928
931
  } else if (!instance) {
@@ -942,8 +945,17 @@ export async function showAuthStatus(argv, app) {
942
945
  if (probe.status === 'succeeded' && user?.user_name) {
943
946
  verified = true;
944
947
  verifiedAt = user.user_name;
948
+ if (argv.context) {
949
+ try {
950
+ const { readWriteContext } = await import('../intended-context.js');
951
+ runtimeContext = { ...await readWriteContext(sdk), verified: true };
952
+ runtimeContext.domain.requested = profile.domain || null;
953
+ if (runtimeContext.user.user_name !== user.user_name) throw new Error('Context account mismatch');
954
+ } catch { runtimeContext = { verified: false, status: 'unavailable' }; }
955
+ }
945
956
  if (profile.username && profile.username !== user.user_name) {
946
957
  verified = false;
958
+ if (runtimeContext) runtimeContext = { verified: false, status: 'account_mismatch' };
947
959
  probe = {
948
960
  status: 'failed', code: 'account_mismatch', classification: 'account_mismatch',
949
961
  message: 'The session account does not match the configured profile account.',
@@ -966,6 +978,7 @@ export async function showAuthStatus(argv, app) {
966
978
 
967
979
  profiles.push({
968
980
  name,
981
+ ...(runtimeContext ? { context: runtimeContext } : {}),
969
982
  instance,
970
983
  username: profile.username || undefined,
971
984
  active: name === (app.session?.profileName || app.config.activeProfile || app.config.defaultProfile),
@@ -1000,8 +1013,12 @@ export async function showAuthStatus(argv, app) {
1000
1013
  const summary = `${profiles.length} ${profiles.length === 1 ? 'profile' : 'profiles'}`;
1001
1014
  // Ship the styled view as _formatted (see renderAuthStatus); the
1002
1015
  // OutputWriter prints it verbatim and suppresses the summary.
1003
- result._formatted = renderAuthStatus(result, summary, { details: argv.details === true });
1004
- if (!argv.details) {
1016
+ result._formatted = renderAuthStatus(result, summary, { details: argv.details === true || argv.context === true });
1017
+ if (argv.context) result._formatted += profiles.map(p => {
1018
+ const c = p.context;
1019
+ return `\n${p.name}: ${c?.verified ? `user ${c.user.user_name}; scope ${c.scope}; update set ${c.update_set.name} (${c.update_set.sys_id}); domain unverified${c.domain.requested ? `, requested ${c.domain.requested}` : ''}` : `context ${c?.status || 'unavailable'}`}`;
1020
+ }).join('');
1021
+ if (!argv.details && !argv.context) {
1005
1022
  delete result.default_instance;
1006
1023
  result.profiles = profiles.map(({ instance: _instance, username: _username, verified_as: _verifiedAs, ...visible }) => visible);
1007
1024
  }
@@ -1207,6 +1224,8 @@ export function authCmd(wrap) {
1207
1224
  describe: 'Show authentication status (use --details for users and instance URLs)',
1208
1225
  builder: sub => sub.option('local', {
1209
1226
  type: 'boolean', describe: 'Show saved credential state without contacting any instance',
1227
+ }).option('context', {
1228
+ type: 'boolean', describe: 'Full context for selected/default profile, including live user, scope, capture set and domain verification limits; --local makes no requests',
1210
1229
  }).option('details', {
1211
1230
  type: 'boolean', describe: 'Include users and instance URLs in status output',
1212
1231
  }),