@jacebenson/jsn 5.5.9 → 5.5.10-dev.230.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.
@@ -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',
@@ -1,4 +1,5 @@
1
1
  import { subscriptionsCmdDefinition } from '../command-families.js';
2
+ import { subscriptionEvidence, formatSubscriptionEvidence, evidenceLimit } from '../subscription-evidence.js';
2
3
  import { refreshSchedules } from '../schedule-cache.js';
3
4
  import { loadSchedule, scheduleCatalog, scheduleSnapshot, formatSchedule, estimateSubscription, formatEstimate } from '../subscriptions.js';
4
5
 
@@ -22,7 +23,16 @@ export function subscriptionsCmd(wrap) {
22
23
  };
23
24
  return {
24
25
  ...subscriptionsCmdDefinition,
25
- builder: y => y.command({ command: 'refresh', describe: 'Explicitly download and validate schedule catalog; retain last-good on failure', builder: b => b.option('manifest-url', { type: 'string' }), handler: wrap(async (argv, app) => {
26
+ builder: y => y.command({ command: 'evidence', describe: 'Show subscription evidence and installed-app hints (read-only)',
27
+ builder: b => b.option('limit', { type: 'number', default: 50, describe: 'Maximum observations per source (integer 1–200)' }),
28
+ handler: wrap(async (argv, app) => {
29
+ const limit = evidenceLimit(argv.limit);
30
+ app.requireInstance();
31
+ const report = await subscriptionEvidence(app.sdk, { limit });
32
+ Object.defineProperty(report, '_formatted', { value: formatSubscriptionEvidence(report) });
33
+ app.ok(report, { summary: 'Bounded instance evidence; contractual authority and completeness unverified' });
34
+ }),
35
+ }).command({ command: 'refresh', describe: 'Explicitly download and validate schedule catalog; retain last-good on failure', builder: b => b.option('manifest-url', { type: 'string' }), handler: wrap(async (argv, app) => {
26
36
  const origin = process.env.JSN_DOCS_URL || app.config?.docs?.url;
27
37
  const manifest = argv.manifestUrl || process.env.JSN_SCHEDULES_MANIFEST_URL || app.config?.docs?.schedule_manifest_url || (origin ? new URL('/subscription-schedules/v1/manifest.json', origin).href : undefined);
28
38
  const provenance = await refreshSchedules(manifest);
@@ -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' },
@@ -2,6 +2,7 @@ import { spawnSync } from 'node:child_process';
2
2
  import { declareCapabilities } from '../capabilities.js';
3
3
  import { AppError, CodeAPI, CodeNetwork } from '../errors.js';
4
4
  import { checkLatest, getReleaseChannel, getVersion } from './version.js';
5
+ import { collectUpgradePrep, prepSummary } from '../upgrade-prep.js';
5
6
 
6
7
  for (const name of ['upgrade', 'update']) {
7
8
  declareCapabilities(name, { noInstance: true, skipDailyChecks: true });
@@ -43,6 +44,17 @@ export function upgradeCmd(wrap, { version = getVersion, check = checkLatest, in
43
44
  aliases: ['update'],
44
45
  describe: 'Upgrade jsn through npm (preserves the installed release channel)',
45
46
  builder: (y) => y
47
+ .command({ command: 'prep', describe: 'Collect read-only platform and Store upgrade preparation evidence',
48
+ builder: p => p
49
+ .option('target', { type: 'string', describe: 'Optional exact offered target label/value/sys_id; never selected automatically' })
50
+ .option('related-profile', { type: 'array', string: true, describe: 'Explicit related lower-environment profiles for update-set evidence' })
51
+ .option('customizations', { type: 'string', describe: 'Existing local customization capture ID' })
52
+ .option('limit', { type: 'number', default: 50, describe: 'Maximum rows per evidence source (1–200)' }),
53
+ handler: wrap(async (argv, app) => {
54
+ const data = await collectUpgradePrep(argv, app);
55
+ app.ok(data, { summary: prepSummary(data) });
56
+ }),
57
+ })
46
58
  .option('channel', { type: 'string', choices: ['dev', 'main', 'latest'], describe: 'Choose dev or stable (main/latest)' })
47
59
  .option('dry-run', { type: 'boolean', describe: 'Show the install command without installing' })
48
60
  .option('force', { type: 'boolean', describe: 'Reinstall even when the selected version is not newer' }),
@@ -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