@jacebenson/jsn 5.5.9-dev.222.1 → 5.5.9-dev.225.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.9-dev.222.1",
3
+ "version": "5.5.9-dev.225.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": {
@@ -18,6 +18,9 @@ Discover commands with `jsn --help`, `jsn discover "search words"`, and
18
18
  approval before using eval; avoid bypassing ServiceNow protections.
19
19
  - Honor delete confirmations. Get approval for destructive work and Global +
20
20
  Default mutations; use `--force` only for the approved operation.
21
+ - Deleting several records by filter is `jsn records delete-many`, not `eval`.
22
+ It previews without `--yes`, and a real delete requires the exact
23
+ `--expect-count` from that preview.
21
24
 
22
25
  For development:
23
26
 
@@ -46,6 +46,17 @@ function storageError(message) {
46
46
  error.code = 'credential_storage_error';
47
47
  return error;
48
48
  }
49
+ /**
50
+ * The plaintext warning belongs to the moment a credential is stored, not to
51
+ * every command that reads one back.
52
+ *
53
+ * It used to fire on the read path too, which meant once per process, which
54
+ * means once per command — every read, list, or search printed it on stderr.
55
+ * That is noise in a terminal and permanently in an agent transcript, and it
56
+ * told nobody anything they could act on at that moment. The storage mode is
57
+ * reported instead by `jsn auth status`, and the warning is emitted when the
58
+ * choice is actually made (login, setup, token save).
59
+ */
49
60
  let plaintextWarningShown = false;
50
61
  function warnPlaintext() {
51
62
  if (plaintextWarningShown) return;
@@ -251,7 +262,6 @@ export function loadCredentials(instance, username, injectedStore) {
251
262
  // Reads (including local status) never persist or migrate credentials. A
252
263
  // subsequent explicit login/save or token refresh performs verified retirement.
253
264
  if (!plaintextAllowed()) throw refusal();
254
- warnPlaintext();
255
265
  const creds = readPrivateState('credentials', key);
256
266
  return creds ? { ...creds, auth_source: 'file' } : null;
257
267
  }
@@ -278,10 +288,28 @@ export function saveCredentials(instance, creds, username, injectedStore) {
278
288
  return;
279
289
  }
280
290
  if (!plaintextAllowed()) throw secureFailure || refusal();
281
- warnPlaintext();
291
+ // Re-stamping last_seen after a successful call is bookkeeping, not a storage
292
+ // decision. Warning on it put the message on every command again, which is
293
+ // what this change is meant to stop; only a change to the secret material
294
+ // (a real login or token refresh) is worth the warning.
295
+ if (materialChanged(key, creds)) warnPlaintext();
282
296
  writePrivateState('credentials', key, creds);
283
297
  }
284
298
 
299
+ /** True when the incoming credential material differs from what is on disk. */
300
+ function materialChanged(key, creds) {
301
+ let previous;
302
+ try { previous = readPrivateState('credentials', key); } catch { return true; }
303
+ if (!previous) return true;
304
+ const material = (value) => {
305
+ // last_seen is bookkeeping; auth_source is derived by the loader and never
306
+ // part of the stored secret.
307
+ const { last_seen: _seen, auth_source: _source, ...rest } = value || {};
308
+ return JSON.stringify(rest, Object.keys(rest).sort());
309
+ };
310
+ return material(previous) !== material(creds);
311
+ }
312
+
285
313
  /**
286
314
  * Delete credentials for an instance keyed by <username>@<instance>.
287
315
  */
@@ -144,7 +144,20 @@ export class LocalCLI {
144
144
  onParentDiscovery(fn) { this.parentDiscovery = fn; return this; }
145
145
  demandCommand(count, message) { this.root.demand = { count, message }; return this; }
146
146
  help() { this.helpEnabled = true; return this; }
147
- version() { return this; }
147
+ /**
148
+ * `--version`: print the tool's version and exit.
149
+ *
150
+ * A command's own version comes from the package manifest, so the root flag
151
+ * has to be answered by the parser before dispatch. `.version(false)` (used
152
+ * by the previous `jsn --version` wiring) silently removed the flag, so the
153
+ * token was tolerated as an unknown option and the page fell through to the
154
+ * root help — a script or agent asking "what version is this?" got 2 KB of
155
+ * help text instead of a version string.
156
+ */
157
+ version(value = false) {
158
+ this.versionText = value === false ? undefined : String(value);
159
+ return this;
160
+ }
148
161
  strictCommands() { this.strictCmd = true; return this; }
149
162
  strictOptions() { return this; }
150
163
  fail(fn) { this.failHandler = fn; return this; }
@@ -443,6 +456,13 @@ export class LocalCLI {
443
456
  const node = path.at(-1) || this.root;
444
457
  node.build();
445
458
  if (commandArgs.includes('--help') || commandArgs.includes('-h')) { this._help(node, path.map((n) => n.name)); return; }
459
+ // The root `--version` flag is answered here, before any command dispatch
460
+ // or demand-command failure, so `jsn --version` is a one-line answer.
461
+ if (this.versionText !== undefined && !path.length
462
+ && (commandArgs.includes('--version') || commandArgs.includes('-V'))) {
463
+ process.stdout.write(`${this.versionText}\n`);
464
+ return;
465
+ }
446
466
  const firstWord = this.args.find((arg, index) => !discoveryConsumed.has(index) && !arg.startsWith('-'));
447
467
  if (this.strictCmd && !path.length && firstWord && !this._lookup(this.root.children, firstWord)) {
448
468
  return this._fail(`Unknown command: ${firstWord}`);
package/src/cli.js CHANGED
@@ -486,8 +486,9 @@ export function buildCLI() {
486
486
  })(argv);
487
487
  })
488
488
  .epilogue(renderTips())
489
+ .option('version', { type: 'boolean', alias: 'V', describe: 'Show the jsn version' })
489
490
  .help('help', 'Show help')
490
- .version(false)
491
+ .version(getVersion())
491
492
  .strictCommands()
492
493
  .strictOptions(false)
493
494
  .fail((msg, err) => {
@@ -65,6 +65,17 @@ export function renderAuthStatus(result, summary, { details = false } = {}) {
65
65
  if (profiles.some(profile => profile.read_only !== true)) lines.push(' Read/write: permits profile operations, subject to each command\'s guards.');
66
66
  if (profiles.some(profile => profile.skip_confirmations !== true)) lines.push(' Confirm: guarded deletes require confirmation; --force bypasses this prompt, not read-only.');
67
67
  if (profiles.some(profile => profile.skip_confirmations === true)) lines.push(' No prompt: profile skips standard delete confirmation; command-specific safeguards still apply.');
68
+ // Storage mode is a standing property of a profile, so it belongs in status
69
+ // rather than in a warning repeated on every command that reads credentials.
70
+ const plaintextProfiles = profiles.filter(profile => profile.auth_source === 'file' || profile.diagnostics?.auth_source === 'file');
71
+ if (plaintextProfiles.length) {
72
+ lines.push('', 'Credential storage:');
73
+ for (const profile of plaintextProfiles) {
74
+ const label = profile.name || 'profile';
75
+ lines.push(` ${label}: portable plaintext file; backups and copies can expose it.`
76
+ + ` Move it to the OS credential store: jsn auth login --profile ${quoteShellArg(label)}`);
77
+ }
78
+ }
68
79
  lines.push('ACCESS is a JSN profile setting, not ServiceNow ACL authorization.',
69
80
  'CREDENTIALS describes local availability; only CONNECTION Verified confirms the status probe succeeded.');
70
81
  if (profiles.some(profile => profile.diagnostics?.probe?.code === 'not_requested')) lines.push('', 'Connection not checked (--local).');
@@ -97,6 +97,7 @@ export function flowsCmd(wrap) {
97
97
  builder: y => y
98
98
  .positional('term', { type: 'string', describe: 'Case-insensitive literal text to find in readable definitions' })
99
99
  .option('refresh', { type: 'boolean', default: false, describe: 'Rebuild the decoded cache; warm searches still revalidate source access' })
100
+ .option('concurrency', { type: 'number', default: 6, describe: 'Parallel definition downloads (1 = one at a time); instance reads still happen for every visible flow' })
100
101
  .epilogue(`Example:
101
102
  jsn flows search approval
102
103
  Interactive use can pick a flow; scripts pass the term.
@@ -105,7 +106,7 @@ Documentation: ${docLink('flows')}`),
105
106
  app.requireInstance();
106
107
  const session = app.session || {};
107
108
  const result = await searchFlows({
108
- sdk: app.sdk, term: argv.term, refresh: argv.refresh,
109
+ sdk: app.sdk, term: argv.term, refresh: argv.refresh, concurrency: argv.concurrency,
109
110
  context: { profile: session.profileName, username: session.username, domain: session.domain, authMethod: session.profile?.auth_method },
110
111
  progress: message => {
111
112
  if (!argv.json && !argv.get && (!argv.format || ['auto', 'pretty', 'styled'].includes(argv.format))) process.stderr.write(`${message}\n`);
@@ -1,4 +1,4 @@
1
- import { formatCommandList, formatRecordForDisplay, findOmittedColumns, buildQuerySuffix, buildRecordPayload, getStringField, interactiveList, resolveFieldsParam, checkDerivedFields, confirmDelete, verifyWriteBack } from '../helpers.js';
1
+ import { formatCommandList, formatRecordForDisplay, findOmittedColumns, buildQuerySuffix, buildRecordPayload, getStringField, interactiveList, resolveFieldsParam, checkDerivedFields, confirmDelete, verifyWriteBack, quoteShellArg } from '../helpers.js';
2
2
  import { listRecords, recordListParams, getRecord, createRecord, updateRecord, deleteRecord } from '../records-engine.js';
3
3
  import { resolveRecord, unwrapSysId } from '../resolve-record.js';
4
4
  import { errUsage } from '../errors.js';
@@ -9,7 +9,7 @@ import { assertMutationRecordScope, assertMutationScope } from '../intended-cont
9
9
 
10
10
  declareCapabilities('records', {
11
11
  mutationContext: 'table',
12
- mutationSubcommands: ['create', 'update', 'delete', 'bulk'],
12
+ mutationSubcommands: ['create', 'update', 'delete', 'delete-many', 'bulk'],
13
13
  });
14
14
 
15
15
  const tableDefaultColumns = {
@@ -429,6 +429,80 @@ export function recordsCmd(wrap) {
429
429
  app.ok({ message: 'Record deleted', table: argv.table, sys_id: sysID }, { summary: `Deleted record from ${argv.table}` });
430
430
  }),
431
431
  })
432
+ .command({
433
+ command: 'delete-many',
434
+ describe: 'Delete records matching a filter; preview by default, verify after deletion',
435
+ builder: (y) => y
436
+ .option('table', { type: 'string', demandOption: true, describe: 'Table name' })
437
+ .option('query', { type: 'string', describe: 'Required nonempty encoded query; use records delete for a single record' })
438
+ .option('expect-count', { type: 'number', describe: 'Required for deletion: exact expected matching count' })
439
+ .option('yes', { type: 'boolean', default: false, describe: 'Confirm deletion (requires --expect-count)' })
440
+ .option('dry-run', { type: 'boolean', default: false, describe: 'Preview only, even with --yes' })
441
+ .option('limit', { type: 'number', default: 200, describe: 'Safety cap: refuse if matches exceed this count' })
442
+ .epilogue('Without --yes, reports count and up to 10 sample records without writes.\nDeletion uses per-record Table API DELETE, then re-counts the query. Concurrent changes cannot be made atomic.'),
443
+ handler: wrap(async (argv, app) => {
444
+ if (!argv.query?.trim()) throw errUsage('--query must be nonempty. Use records delete for a single record.');
445
+ if (!Number.isSafeInteger(argv.limit) || argv.limit < 1) throw errUsage('--limit must be a positive safe integer.');
446
+ const dryRun = !argv.yes || argv['dry-run'];
447
+ const expected = argv['expect-count'];
448
+ if (!dryRun && (!Number.isSafeInteger(expected) || expected < 0)) throw errUsage('Deletion requires --expect-count as a nonnegative safe integer.');
449
+ const countMatches = async () => {
450
+ const count = await app.sdk.aggregateCount(argv.table, argv.query);
451
+ if (!Number.isSafeInteger(count) || count < 0) throw new Error('Cannot verify matching count; refusing deletion.');
452
+ return count;
453
+ };
454
+ const count = await countMatches();
455
+ if (count > argv.limit) throw errUsage(`Matched ${count} records, exceeding --limit ${argv.limit}. Raise --limit explicitly to proceed.`);
456
+ if (!dryRun && count !== expected) throw errUsage(`Count mismatch: --expect-count ${expected}, live count ${count}. No records deleted.`);
457
+ const readPage = (limit, offset) => listRecords(app.sdk, { table: argv.table,
458
+ params: recordListParams({ query: argv.query, limit, offset, fields: ['sys_id', 'number'], displayValue: 'false' }) });
459
+ const rerun = ['jsn', 'records', 'delete-many', '--table', argv.table, '--query', argv.query,
460
+ '--expect-count', String(count), '--limit', String(argv.limit), '--yes'].map(quoteShellArg).join(' ');
461
+ const breadcrumbs = [{ action: 'verify', cmd: `jsn records aggregate --table ${quoteShellArg(argv.table)} --query ${quoteShellArg(argv.query)}`, description: 'Re-check matching records' }];
462
+ if (dryRun) {
463
+ const sample = count ? await readPage(Math.min(10, count), 0) : [];
464
+ return app.ok({ table: argv.table, query: argv.query, count, dry_run: true, sample, rerun }, {
465
+ summary: `Dry run: ${count} record(s) in ${argv.table} would be deleted`,
466
+ breadcrumbs: [{ action: 'delete', cmd: rerun, description: 'Delete with this exact expected count' }],
467
+ });
468
+ }
469
+ // Snapshot all targets before deleting: offset paging over a shrinking set skips rows.
470
+ const targets = [];
471
+ while (targets.length < count) {
472
+ const rows = await readPage(Math.min(1000, count - targets.length), targets.length);
473
+ if (!rows.length) break;
474
+ targets.push(...rows);
475
+ if (targets.length > count) break;
476
+ }
477
+ const ids = targets.map(unwrapSysId);
478
+ if (targets.length !== count || ids.some(id => !id) || new Set(ids).size !== count) {
479
+ throw errUsage('Enumeration differs from the counted targets or contains unreadable/duplicate sys_ids. No records deleted.');
480
+ }
481
+ if (await countMatches() !== count) throw errUsage('Matching count changed during enumeration. No records deleted.');
482
+ // Preflight all customization scopes before the first write, as bulk does.
483
+ if (app.mutationContext?.verified) {
484
+ for (const id of ids) await assertMutationRecordScope(app, argv.table, id);
485
+ }
486
+ const deleted = [];
487
+ const failed = [];
488
+ for (const record of targets) {
489
+ try { deleted.push(await deleteRecord(app.sdk, { table: argv.table, record })); }
490
+ catch (error) { failed.push({ sys_id: unwrapSysId(record), error: error.message || String(error) }); }
491
+ }
492
+ let remaining = null;
493
+ let verificationError;
494
+ try { remaining = await countMatches(); }
495
+ catch (error) { verificationError = error.message; }
496
+ const verified = failed.length === 0 && remaining === 0;
497
+ app.ok({ table: argv.table, query: argv.query, matched: count, deleted, failed, remaining,
498
+ verified, ...(verificationError ? { verification_error: verificationError } : {}) }, {
499
+ summary: verified ? `Deleted ${deleted.length} record(s) from ${argv.table}; verified zero remaining`
500
+ : `Deletion incomplete or unverified: ${deleted.length} deleted, ${failed.length} failed, ${remaining ?? 'unknown'} remaining`,
501
+ breadcrumbs,
502
+ });
503
+ if (!verified) process.exitCode = 1;
504
+ }),
505
+ })
432
506
  .command({
433
507
  command: 'aggregate',
434
508
  describe: 'Run ServiceNow Stats API aggregation with optional grouping',
@@ -700,8 +700,13 @@ export function updateSetsCmd(wrap) {
700
700
  const question = `Load "${inspection.name}" (${inspection.count} updates) into ${app.getEffectiveInstance()} as a retrieved update set? This does not commit its changes.`;
701
701
  if (!await confirmUpdateSetMutation(argv, app, question, ['updatesets', 'import', argv.file, '--yes'])) return;
702
702
  const result = await app.sdk.importUpdateSet(xml, inspection, path.basename(argv.file));
703
+ const summaryText = result.already_loaded
704
+ ? `Retrieved update set "${inspection.name}" was already loaded on this target (${result.state}); nothing was uploaded again`
705
+ : result.recovered_after_error
706
+ ? `Retrieved update set "${inspection.name}" is loaded (${result.count} updates); confirmed after a transport error, not committed`
707
+ : `Loaded retrieved update set "${inspection.name}" (${result.count} updates); not committed`;
703
708
  app.ok({ ...summary, ...result, committed: false }, {
704
- summary: `Loaded retrieved update set "${inspection.name}" (${result.count} updates); not committed`,
709
+ summary: summaryText,
705
710
  breadcrumbs: [
706
711
  { action: 'preview', cmd: `jsn updatesets preview ${quoteShellArg(result.sys_id)}`, description: 'Preview against this instance before committing' },
707
712
  { action: 'problems', cmd: `jsn updatesets problems ${quoteShellArg(result.sys_id)}`, description: 'Review preview problems' },
@@ -52,9 +52,10 @@ export function formatFlowSearch(report) {
52
52
  ].join('\n');
53
53
  }
54
54
 
55
- export async function searchFlows({ sdk, term, context = {}, refresh = false, cacheRoot, platform = process.platform, pageSize = 100, maxPages = 10000, progress = () => {} }) {
55
+ export async function searchFlows({ sdk, term, context = {}, refresh = false, cacheRoot, platform = process.platform, pageSize = 100, maxPages = 10000, concurrency = 6, progress = () => {} }) {
56
56
  if (!String(term || '').trim()) throw new Error('A nonempty literal search term is required');
57
57
  if (!Number.isInteger(pageSize) || pageSize < 1 || !Number.isInteger(maxPages) || maxPages < 1) throw new Error('Invalid flow pagination bounds');
58
+ if (!Number.isInteger(concurrency) || concurrency < 1) throw new Error('Invalid flow download concurrency');
58
59
  const instance = new URL(sdk.baseURL).origin;
59
60
  const directory = path.join(cacheRoot || process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'jsn', 'flow-search');
60
61
  // Node's Windows mode bits cannot establish a private DACL. Do not touch
@@ -109,12 +110,19 @@ export async function searchFlows({ sdk, term, context = {}, refresh = false, ca
109
110
  const flows = [];
110
111
  let downloaded = 0;
111
112
  let reused = 0;
112
- for (const row of rows.values()) {
113
+ /**
114
+ * A fresh source read is deliberately mandatory even on a cache hit. A
115
+ * profile/role fingerprint cannot detect field ACLs, impersonation or a
116
+ * revoked permission. Never release old source on a failed live read.
117
+ *
118
+ * The reads are independent, so they run through a bounded pool. Serially,
119
+ * an instance with ~370 visible flows spent minutes in this loop: one
120
+ * processflow GET at a time. Each read still happens; the bound keeps the
121
+ * instance from being flooded and keeps the failure isolation per flow.
122
+ */
123
+ const fetchDefinition = async (row) => {
113
124
  let data;
114
125
  try {
115
- // A fresh source read is deliberately mandatory even on a cache hit. A
116
- // profile/role fingerprint cannot detect field ACLs, impersonation or a
117
- // revoked permission. Never release old source on a failed live read.
118
126
  const response = await get(`/api/now/processflow/flow/${row.sys_id}`);
119
127
  const code = response?.result?.errorCode;
120
128
  if (response?.result?.errorMessage || (code != null && code !== '' && String(code) !== '0')) throw new Error('Provider refused the flow definition');
@@ -123,8 +131,7 @@ export async function searchFlows({ sdk, term, context = {}, refresh = false, ca
123
131
  if (!data || typeof data !== 'object') throw new Error('No readable ProcessFlow definition');
124
132
  downloaded++;
125
133
  } catch (error) {
126
- failures.push({ ...row, stage: 'download', message: error.status === 403 || /403|forbidden/i.test(error.message) ? 'Access denied reading definition' : 'Definition download failed or unavailable', status: error.status || null });
127
- continue;
134
+ return { failure: { ...row, stage: 'download', message: error.status === 403 || /403|forbidden/i.test(error.message) ? 'Access denied reading definition' : 'Definition download failed or unavailable', status: error.status || null } };
128
135
  }
129
136
  try {
130
137
  const sourceDigest = digest(data);
@@ -132,8 +139,26 @@ export async function searchFlows({ sdk, term, context = {}, refresh = false, ca
132
139
  const entries = cached?.source_digest === sourceDigest && Array.isArray(cached.entries) ? cached.entries : decodeFlowSearchDefinition(data);
133
140
  const unchanged = entries === cached?.entries;
134
141
  if (unchanged) reused++;
135
- flows.push({ ...row, source: `/api/now/processflow/flow/${row.sys_id}`, source_digest: sourceDigest, decoded_at: unchanged ? cached.decoded_at : new Date().toISOString(), entries });
136
- } catch (error) { failures.push({ ...row, stage: 'decode', message: error.message }); }
142
+ return { flow: { ...row, source: `/api/now/processflow/flow/${row.sys_id}`, source_digest: sourceDigest, decoded_at: unchanged ? cached.decoded_at : new Date().toISOString(), entries } };
143
+ } catch (error) { return { failure: { ...row, stage: 'decode', message: error.message } }; }
144
+ };
145
+ const rowList = [...rows.values()];
146
+ // Results are collected by inventory position, not completion order, so a
147
+ // faster flow can never reorder matches or failures between runs.
148
+ const results = new Array(rowList.length);
149
+ let nextIndex = 0;
150
+ const worker = async () => {
151
+ while (true) {
152
+ const index = nextIndex++;
153
+ if (index >= rowList.length) return;
154
+ results[index] = await fetchDefinition(rowList[index]);
155
+ }
156
+ };
157
+ const poolSize = Math.max(1, Math.min(concurrency, rowList.length));
158
+ await Promise.all(Array.from({ length: poolSize }, worker));
159
+ for (const result of results) {
160
+ if (!result || result.failure) { if (result?.failure) failures.push(result.failure); continue; }
161
+ flows.push(result.flow);
137
162
  }
138
163
  const captured = new Date().toISOString();
139
164
  if (diskCache) await writeCache(file, { schema: 1, captured_at: captured, flows });
package/src/help.js CHANGED
@@ -25,11 +25,11 @@ const CONCISE_EXAMPLES = [
25
25
  ];
26
26
 
27
27
  const CONCISE_MORE = [
28
- { label: `${SITE_ORIGIN}${ROOT_DOC_LINK}`, description: 'Guides: install, setup, safety, output, agents and feature references' },
28
+ { label: `${SITE_ORIGIN}${ROOT_DOC_LINK}`, description: 'Guides: setup, safety, output, agents, features' },
29
29
  { label: 'jsn <command> <action> --help', description: 'Options for one command or action' },
30
30
  { label: 'jsn discover <word>', description: 'Find commands by task words' },
31
31
  { label: 'jsn discover --table <table>', description: 'Find commands configured for a table' },
32
- { label: 'jsn --all-commands --help', description: 'Every registered command and global flag' },
32
+ { label: 'jsn --all-commands --help', description: 'Every command and global flag' },
33
33
  { label: 'jsn --json', description: 'Registered command surface as JSON' },
34
34
  ];
35
35
 
@@ -256,11 +256,28 @@ function renderConciseHelp(config, registry, width) {
256
256
  desc: command.summary || command.description || '',
257
257
  }));
258
258
 
259
+ const used = new Set();
260
+ const groups = Object.entries(COMMAND_GROUPS)
261
+ .map(([label, hint]) => ({
262
+ label,
263
+ description: rowsFor(hint, byName, used, config)
264
+ .filter((row) => !row.divider).map((row) => row.name).join(' '),
265
+ }))
266
+ .filter((row) => row.description);
267
+ const other = commands
268
+ .filter((command) => !used.has(command.name) && !isCapabilityHidden(command.name, config))
269
+ .map((command) => command.name);
270
+ if (other.length) groups.push({ label: 'OTHER', description: other.join(' ') });
271
+
259
272
  return [
260
273
  'Usage: jsn <command> [options]',
261
274
  '',
262
275
  'Command-line interface for ServiceNow',
263
- renderGroup('COMMON COMMANDS', common, width),
276
+ `\nCOMMON COMMANDS\n${renderRows(common.map((command) => ({ label: command.name, description: command.desc })), { width, indent: 2 })}`,
277
+ '',
278
+ 'ALL COMMANDS BY GROUP',
279
+ ...wrapText('names only; jsn --all-commands --help has descriptions and flags', { width }),
280
+ renderRows(groups, { width, indent: 2 }),
264
281
  '',
265
282
  'EXAMPLES',
266
283
  ...CONCISE_EXAMPLES.map((example) => wrapText(example, { width: width - 2, firstIndent: 2 }).join(' \\\n')),
@@ -268,12 +285,12 @@ function renderConciseHelp(config, registry, width) {
268
285
  '',
269
286
  'OUTPUT',
270
287
  ...[
271
- 'For smaller list responses, select fields with --columns and bound rows with --limit.',
272
- 'CSV and TSV avoid repeated field names; JSON preserves metadata and nested structure.',
273
- 'Use JSON for pagination metadata or both reference IDs and display labels.',
288
+ 'Bound lists with --columns and --limit.',
289
+ 'CSV/TSV save tokens; JSON preserves metadata and nesting.',
290
+ 'Use JSON for pagination or reference IDs with display labels.',
274
291
  ].flatMap(text => wrapText(text, { width, firstIndent: 2 })),
275
292
  '',
276
- 'MORE',
293
+ 'NEXT',
277
294
  renderRows(CONCISE_MORE, { width, indent: 2 }),
278
295
  '',
279
296
  ].join('\n');
@@ -1,9 +1,12 @@
1
1
  // Intent comes from the task, never from the current provider preferences.
2
2
  import { assertSafeExactMatch, getStringField } from './helpers.js';
3
3
  import { errUsageHint } from './errors.js';
4
+ import { readEffectiveUpdateSet } from './context.js';
4
5
 
5
- export function contextFailure(message) {
6
- return errUsageHint(message, 'Supply --expect-scope and --expect-update-set from the task. Select context explicitly with scopes set / updatesets set, then retry. --force never overrides missing or mismatched intent.');
6
+ const CONTEXT_HINT = 'Supply --expect-scope and --expect-update-set from the task. Select context explicitly with scopes set / updatesets set, then retry. --force never overrides missing or mismatched intent.';
7
+
8
+ export function contextFailure(message, hint = CONTEXT_HINT) {
9
+ return errUsageHint(message, hint);
7
10
  }
8
11
  const raw = (record, key) => record?.[key]?.value ?? record?.[key];
9
12
  export async function exactContextRecord(sdk, table, field, identifier) {
@@ -25,14 +28,74 @@ export async function readWriteContext(sdk) {
25
28
  }));
26
29
  if (users.length !== 1 || !raw(users[0], 'sys_id') || !getStringField(users[0], 'user_name')) throw contextFailure('Current user is unknown.');
27
30
  const user = { sys_id: raw(users[0], 'sys_id'), user_name: getStringField(users[0], 'user_name') };
28
- async function preference(name) {
29
- const rows = await sdk.list('sys_user_preference', new URLSearchParams({
30
- sysparm_query: `user=${user.sys_id}^name=${name}`, sysparm_limit: '2', sysparm_fields: 'value',
31
- }));
32
- if (rows.length !== 1 || !raw(rows[0], 'value') || raw(rows[0], 'value') === '-') throw contextFailure(`Current ${name} preference is unknown.`);
31
+ /**
32
+ * Read one persisted capture-context preference.
33
+ *
34
+ * A missing row is not the same failure as an unreadable one. On a fresh
35
+ * instance nobody has ever picked an update set, so there is genuinely
36
+ * nothing to verify a customization write against — and the old message
37
+ * ("Current sys_update_set preference is unknown") named an internal
38
+ * preference key and pointed at --expect-* flags that cannot create a
39
+ * selection. An agent following that hint retries the same dead end. Each
40
+ * branch below says what is actually wrong and names the command that fixes
41
+ * it.
42
+ */
43
+ async function preference({ key, label, remediation, sessionTruth }) {
44
+ let rows;
45
+ try {
46
+ rows = await sdk.list('sys_user_preference', new URLSearchParams({
47
+ sysparm_query: `user=${user.sys_id}^name=${key}`, sysparm_limit: '2', sysparm_fields: 'value',
48
+ }));
49
+ } catch (error) {
50
+ throw contextFailure(
51
+ `Could not read the persisted ${label} for ${user.user_name}: ${error.message}`,
52
+ `Confirm the instance is reachable and retry. Do not retry the write until the selection can be read.`,
53
+ );
54
+ }
55
+ if (rows.length === 0) {
56
+ throw contextFailure(
57
+ `No ${label} is selected for ${user.user_name}, so there is no capture context to verify this write against.${await sessionNote(sessionTruth)}`,
58
+ `Select one first, then rerun the same command: ${remediation}. --expect-scope and --expect-update-set assert an existing selection; they cannot create one.`,
59
+ );
60
+ }
61
+ if (rows.length > 1) {
62
+ throw contextFailure(
63
+ `${rows.length} persisted ${label} preferences exist for ${user.user_name}, so the capture context is ambiguous.`,
64
+ `Resolve the duplicate preferences for this user, then retry: ${remediation}`,
65
+ );
66
+ }
67
+ if (!raw(rows[0], 'value') || raw(rows[0], 'value') === '-') {
68
+ throw contextFailure(
69
+ `The ${label} for ${user.user_name} is saved but empty, so the capture context is unreadable.`,
70
+ `Select one again, then rerun the same command: ${remediation}`,
71
+ );
72
+ }
33
73
  return raw(rows[0], 'value');
34
74
  }
35
- const [scopeId, setId] = await Promise.all([preference('apps.current_app'), preference('sys_update_set')]);
75
+ // Failure-path diagnostic only: the provider's session picker is a different
76
+ // source from the persisted preference, and saying so stops an agent from
77
+ // assuming a fresh session already has a set selected.
78
+ async function sessionNote(readSession) {
79
+ if (!readSession) return '';
80
+ try {
81
+ const effective = await readSession();
82
+ if (!effective?.sys_id) return '';
83
+ return `\nThe session picker reports "${effective.label || effective.name || effective.sys_id}" (${effective.sys_id}); that selection is not persisted for this user and is not used for a customization write.`;
84
+ } catch {
85
+ return '';
86
+ }
87
+ }
88
+ const [scopeId, setId] = await Promise.all([
89
+ preference({
90
+ key: 'apps.current_app', label: 'application scope',
91
+ remediation: 'jsn scopes set "<scope value or name>"',
92
+ }),
93
+ preference({
94
+ key: 'sys_update_set', label: 'update set',
95
+ remediation: 'jsn updatesets set "<update set name>"',
96
+ sessionTruth: () => readEffectiveUpdateSet(sdk),
97
+ }),
98
+ ]);
36
99
  const [scope, set] = await Promise.all([sdk.get('sys_scope', scopeId), sdk.get('sys_update_set', setId)]);
37
100
  const applicationId = raw(set, 'application');
38
101
  if (!getStringField(scope || {}, 'scope') || !getStringField(set || {}, 'name') || !applicationId || !getStringField(set || {}, 'state')) throw contextFailure('Capture context is incomplete or unreadable.');
@@ -48,7 +48,14 @@ export async function guardMutationContext(app, argv, { ask = confirm, rawArgs =
48
48
  }
49
49
  let context;
50
50
  try { context = await readWriteContext(app.sdk); }
51
- catch (error) { throw contextFailure(`Cannot verify capture context: ${error.message}`); }
51
+ catch (error) {
52
+ // A structured failure already explains which selection is missing and
53
+ // which command fixes it. Prefixing it with "Cannot verify capture
54
+ // context" buried that remediation and replaced it with the generic
55
+ // --expect-* hint, which cannot create a selection.
56
+ if (error?.hint) throw error;
57
+ throw contextFailure(`Cannot verify capture context: ${error.message}`);
58
+ }
52
59
  if (app.session?.username && context.user.user_name !== app.session.username) throw contextFailure('Current user differs from the selected profile.');
53
60
  const fail = message => { const error = contextFailure(message); error.context = context; throw error; };
54
61
  if (context.application_id !== context.update_set.application_id) fail('Selected scope and update set belong to different applications.');
package/src/sdk.js CHANGED
@@ -21,6 +21,17 @@ import {
21
21
 
22
22
  const DEFAULT_TIMEOUT = 30000;
23
23
 
24
+ /**
25
+ * Node reports every network-layer problem as "fetch failed" and hides the
26
+ * reason in `cause`. That message cannot tell a reset from a proxy rejection or
27
+ * a timeout, so the code is appended when one is available.
28
+ */
29
+ function describeTransportError(error) {
30
+ const base = error?.message || String(error);
31
+ const code = error?.cause?.code || error?.code;
32
+ return code && !base.includes(code) ? `${base} (${code})` : base;
33
+ }
34
+
24
35
  function collectSetCookies(cookieJar, response) {
25
36
  const values = response.headers.getSetCookie?.() || [];
26
37
  const raw = Array.isArray(values) && values.length
@@ -933,15 +944,41 @@ export class SDKClient {
933
944
  });
934
945
  }
935
946
 
936
- /** Load through the native XML upload processor, then verify the exact envelope. */
947
+ /**
948
+ * Load through the native XML upload processor, then verify the exact envelope.
949
+ *
950
+ * Loading is the step that changes the instance, and it is not transactional
951
+ * with the HTTP response that reports it: `sys_upload.do` can commit the
952
+ * retrieved update set and still fail in transport. Treating any later error
953
+ * as "the import failed" made agents retry a load that had already happened,
954
+ * so every failure path now re-reads for the set before deciding, and a
955
+ * second attempt at the same XML reports what is already there instead of
956
+ * dead-ending.
957
+ */
937
958
  async importUpdateSet(xml, inspection, filename = 'update-set.xml') {
938
959
  const { sys_id: id, remote_sys_id: sourceID } = inspection;
939
960
  const params = new URLSearchParams({
940
961
  sysparm_query: `sys_id=${id}^ORremote_sys_id=${sourceID}`,
941
962
  sysparm_fields: 'sys_id,name,state', sysparm_limit: '2', sysparm_display_value: 'false',
942
963
  });
943
- if ((await this.list('sys_remote_update_set', params)).length) {
944
- throw errUsage('This retrieved update set already exists on the target; refusing to overwrite it. Inspect it before retrying.');
964
+ const existing = await this.list('sys_remote_update_set', params);
965
+ if (existing.length > 1) {
966
+ throw errUsage('More than one retrieved update set matches this XML identity; refusing to guess. Inspect Retrieved Update Sets before retrying.');
967
+ }
968
+ if (existing.length === 1) {
969
+ const name = getStringField(existing[0], 'name');
970
+ // Same XML, already loaded: an interrupted or retried attempt lands here.
971
+ // Reporting the existing set is the useful answer; refusing to overwrite
972
+ // it is only right when the identity collides with different content.
973
+ if (name === inspection.name) {
974
+ const sysID = getStringField(existing[0], 'sys_id');
975
+ const state = getStringField(existing[0], 'state');
976
+ return {
977
+ sys_id: sysID, state, count: inspection.count, already_loaded: true, members_verified: false,
978
+ link: `${this.baseURL}/sys_remote_update_set.do?sys_id=${sysID}`,
979
+ };
980
+ }
981
+ throw errUsage(`A retrieved update set for this XML identity already exists on the target as "${name}"; refusing to overwrite it. Inspect it before retrying.`);
945
982
  }
946
983
  // Native INSERT_OR_UPDATE must not move/overwrite a member belonging to another set.
947
984
  for (let offset = 0; offset < inspection.members.length; offset += 50) {
@@ -964,16 +1001,24 @@ export class SDKClient {
964
1001
  form.set('sysparm_upload_prefix', '');
965
1002
  form.set('sysparm_referring_url', 'sys_remote_update_set_list.do');
966
1003
  form.set('attachFile', new Blob([xml], { type: 'application/xml' }), filename);
1004
+ // A verification disagreement is knowledge about the instance, not a lost
1005
+ // response: the upload landed and its contents are wrong. Those must stay
1006
+ // failures, so they are tagged and exempted from post-error reconciliation.
1007
+ const mismatch = (message) => {
1008
+ const error = new Error(message);
1009
+ error.verificationMismatch = true;
1010
+ return error;
1011
+ };
967
1012
  try {
968
1013
  await this.rawRequest(`${this.baseURL}/sys_upload.do`, { method: 'POST', body: form,
969
1014
  headers: { ...(cookies ? { Cookie: cookies } : {}), 'X-UserToken': csrf, Referer: formURL },
970
1015
  });
971
1016
  const records = await this.list('sys_remote_update_set', params);
972
- if (records.length !== 1) throw new Error('Could not identify exactly one uploaded retrieved update set');
1017
+ if (records.length !== 1) throw mismatch('Could not identify exactly one uploaded retrieved update set');
973
1018
  const record = records[0];
974
1019
  const importedID = getStringField(record, 'sys_id');
975
1020
  const state = getStringField(record, 'state');
976
- if (state !== 'loaded' || getStringField(record, 'name') !== inspection.name) throw new Error('Uploaded update set name/state did not match the loaded export');
1021
+ if (state !== 'loaded' || getStringField(record, 'name') !== inspection.name) throw mismatch('Uploaded update set name/state did not match the loaded export');
977
1022
  const members = [];
978
1023
  for (let offset = 0; ; offset += 500) {
979
1024
  const page = await this.list('sys_update_xml', new URLSearchParams({
@@ -981,20 +1026,52 @@ export class SDKClient {
981
1026
  sysparm_offset: String(offset), sysparm_display_value: 'false', sysparm_fields: 'sys_id,name,action',
982
1027
  }));
983
1028
  members.push(...page);
984
- if (members.length > inspection.count) throw new Error('Uploaded update set contains unexpected extra members');
1029
+ if (members.length > inspection.count) throw mismatch('Uploaded update set contains unexpected extra members');
985
1030
  if (page.length < 500) break;
986
1031
  }
987
1032
  const actual = new Map(members.map(member => [getStringField(member, 'sys_id'), member]));
988
1033
  if (actual.size !== inspection.count || inspection.members.some(expected => {
989
1034
  const member = actual.get(expected.sys_id);
990
1035
  return !member || getStringField(member, 'name') !== expected.name || getStringField(member, 'action') !== expected.action;
991
- })) throw new Error('Uploaded update set members did not match the XML export');
1036
+ })) throw mismatch('Uploaded update set members did not match the XML export');
992
1037
  return { sys_id: importedID, state, count: members.length, link: `${this.baseURL}/sys_remote_update_set.do?sys_id=${importedID}` };
993
1038
  } catch (error) {
994
- throw new AppError(CodeAPI, `XML import could not be verified: ${error.message}. It may have partially loaded; inspect Retrieved Update Sets before retrying. No automatic retry was attempted.`, 'Inspect Retrieved Update Sets before retrying.', 0, error);
1039
+ if (error.verificationMismatch) {
1040
+ throw new AppError(CodeAPI, `XML import could not be verified: ${error.message}. It may have partially loaded; inspect Retrieved Update Sets before retrying.`, 'Inspect Retrieved Update Sets before retrying.', 0, error);
1041
+ }
1042
+ // The upload may have landed even though a request threw. Re-read for the
1043
+ // exact identity before declaring failure; an agent told "failed" retries
1044
+ // a load that already happened.
1045
+ const landed = await this.#findImportedSet(params, inspection).catch(() => null);
1046
+ if (landed) return landed;
1047
+ throw new AppError(CodeAPI, `XML import could not be verified: ${describeTransportError(error)}. It may have partially loaded, and no matching retrieved update set is visible yet.`, 'Inspect Retrieved Update Sets before retrying.', 0, error);
995
1048
  }
996
1049
  }
997
1050
 
1051
+ /**
1052
+ * Find the retrieved update set this XML would have created, and report it as
1053
+ * a successful load. Returns null when nothing matching is readable, so the
1054
+ * caller can report the original failure.
1055
+ */
1056
+ async #findImportedSet(params, inspection) {
1057
+ const records = await this.list('sys_remote_update_set', params);
1058
+ if (records.length !== 1) return null;
1059
+ const record = records[0];
1060
+ if (getStringField(record, 'name') !== inspection.name) return null;
1061
+ const sysID = getStringField(record, 'sys_id');
1062
+ const members = await this.list('sys_update_xml', new URLSearchParams({
1063
+ sysparm_query: `remote_update_set=${sysID}`, sysparm_fields: 'sys_id', sysparm_limit: String(inspection.count + 1),
1064
+ }));
1065
+ return {
1066
+ sys_id: sysID,
1067
+ state: getStringField(record, 'state'),
1068
+ count: members.length,
1069
+ link: `${this.baseURL}/sys_remote_update_set.do?sys_id=${sysID}`,
1070
+ recovered_after_error: true,
1071
+ members_match_inspection: members.length === inspection.count,
1072
+ };
1073
+ }
1074
+
998
1075
  /**
999
1076
  * Preview a loaded retrieved update set through the CICD Update Set API and
1000
1077
  * wait for its progress tracker. Does not commit and does not resolve