@jacebenson/jsn 5.5.7-dev.216.1 → 5.5.7-dev.218.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/package.json +1 -1
  2. package/skills/servicenow/SKILL.md +9 -1
  3. package/src/app.js +4 -79
  4. package/src/bounded-reads.js +13 -0
  5. package/src/capabilities.js +8 -3
  6. package/src/cli-adapter.js +8 -2
  7. package/src/cli.js +8 -15
  8. package/src/command-families.js +68 -0
  9. package/src/commands/_generic.js +1 -0
  10. package/src/commands/_ticket.js +1 -1
  11. package/src/commands/actions.js +9 -4
  12. package/src/commands/approvals.js +1 -1
  13. package/src/commands/atf.js +1 -1
  14. package/src/commands/attachments.js +1 -1
  15. package/src/commands/auth.js +21 -2
  16. package/src/commands/customizations.js +3 -4
  17. package/src/commands/decisiontables.js +4 -0
  18. package/src/commands/docs/docs.js +3 -5
  19. package/src/commands/domains.js +1 -1
  20. package/src/commands/eval.js +11 -5
  21. package/src/commands/flows.js +17 -5
  22. package/src/commands/groupmembers.js +1 -1
  23. package/src/commands/grouproles.js +1 -1
  24. package/src/commands/groups.js +1 -1
  25. package/src/commands/midservers.js +3 -5
  26. package/src/commands/perf.js +2 -3
  27. package/src/commands/records.js +12 -2
  28. package/src/commands/scopes.js +1 -1
  29. package/src/commands/scrapi.js +2 -2
  30. package/src/commands/skipped-updates.js +2 -3
  31. package/src/commands/subscriptions.js +3 -3
  32. package/src/commands/tickets.js +1 -1
  33. package/src/commands/users.js +1 -1
  34. package/src/commands/workflows.js +3 -5
  35. package/src/config.js +1 -0
  36. package/src/context.js +8 -56
  37. package/src/flow-create.js +9 -0
  38. package/src/intended-context.js +68 -0
  39. package/src/mutation-context.js +69 -46
  40. package/src/output.js +1 -1
  41. package/src/records/inspect.js +30 -16
  42. package/src/records-engine.js +2 -2
  43. package/src/sdk-batch.js +2 -1
  44. package/src/sdk.js +19 -1
  45. package/src/setup-preferences.js +2 -2
@@ -2,73 +2,96 @@
2
2
  import process from 'node:process';
3
3
  import { collectCapabilities } from './capabilities.js';
4
4
  import { isMutationCommand } from './mutations.js';
5
- import { getCurrentUser, getCurrentApplication, getCurrentUpdateSet } from './context.js';
6
- import { canUsePicker, getStringField, quoteShellArg } from './helpers.js';
5
+ import { canUsePicker, quoteShellArg } from './helpers.js';
7
6
  import { confirm } from './prompts.js';
8
- import { AppError, CodeConfirmationRequired, errUsageHint } from './errors.js';
7
+ import { AppError, CodeConfirmationRequired } from './errors.js';
8
+ import { contextFailure, exactContextRecord, intendedContext, readWriteContext } from './intended-context.js';
9
9
 
10
10
  export function needsMutationContext(argv) {
11
11
  if (!isMutationCommand(argv)) return false;
12
12
  const caps = collectCapabilities().get(argv._?.[0]) || {};
13
+ if (caps.mutationContext === 'operational') return false;
13
14
  if (caps.mutationContextReadMethods?.includes(String(argv.method || 'GET').toUpperCase())) return false;
14
15
  return !caps.mutationContextExemptSubcommands?.some(sub =>
15
16
  sub.split(' ').every((part, index) => argv._?.[index + 1] === part));
16
17
  }
17
18
 
18
- function diagnostic(code, message, command, severity = 'warning') {
19
- return { code, severity, message, remediation: { command } };
19
+ // Table ancestry, not a command-name heuristic, decides generic record writes.
20
+ async function isCustomizationTable(sdk, table) {
21
+ if (!table) throw contextFailure('Cannot classify a write without its table.');
22
+ const seen = new Set();
23
+ let row = await exactContextRecord(sdk, 'sys_db_object', 'name', table);
24
+ for (let depth = 0; depth < 32; depth++) {
25
+ const name = row.name?.value ?? row.name;
26
+ if (!name || seen.has(name)) throw contextFailure('Table ancestry is incomplete or cyclic.');
27
+ if (name === 'sys_metadata') return true;
28
+ seen.add(name);
29
+ if (!Object.hasOwn(row, 'super_class')) throw contextFailure('Table ancestry is unreadable.');
30
+ const parent = row.super_class?.value ?? row.super_class;
31
+ if (!parent) return false;
32
+ row = await sdk.get('sys_db_object', parent);
33
+ if (!row) throw contextFailure('Table ancestry is unreadable.');
34
+ }
35
+ throw contextFailure('Table ancestry exceeds the verification bound.');
20
36
  }
21
37
 
22
38
  export async function guardMutationContext(app, argv, { ask = confirm, rawArgs = process.argv.slice(2) } = {}) {
23
39
  if (!needsMutationContext(argv) || !app.sdk) return null;
24
- let application, updateSet;
25
- try {
26
- const user = await getCurrentUser(app.sdk);
27
- if (user?.sys_id) [application, updateSet] = await Promise.all([
28
- getCurrentApplication(app.sdk, user.sys_id, { unknownWhenMissing: true }),
29
- getCurrentUpdateSet(app.sdk, user.sys_id),
30
- ]);
31
- } catch {
32
- // Failed reads are unknown context, never evidence of Global + Default.
40
+ const caps = collectCapabilities().get(argv._?.[0]) || {};
41
+ if (caps.mutationContext === 'table' && !await isCustomizationTable(app.sdk, caps.table || argv.table)) return null;
42
+ const expected = intendedContext(app, argv);
43
+ const interactive = canUsePicker(app, argv);
44
+ if (!interactive && (!expected.scope || !expected.update_set)) throw contextFailure('Noninteractive customization writes require intended scope and update set.');
45
+ // Header application is not an established effective-domain provider contract.
46
+ if (expected.domain !== undefined || app.session?.domain || app.session?.profile?.domain_separation || app.sdk.domain) {
47
+ throw contextFailure('Effective domain cannot be proven for customization writes. X-Now-Domain propagation does not verify domain selection; domain-scoped writes are not supported by this guard.');
48
+ }
49
+ let context;
50
+ try { context = await readWriteContext(app.sdk); }
51
+ catch (error) { throw contextFailure(`Cannot verify capture context: ${error.message}`); }
52
+ if (app.session?.username && context.user.user_name !== app.session.username) throw contextFailure('Current user differs from the selected profile.');
53
+ const fail = message => { const error = contextFailure(message); error.context = context; throw error; };
54
+ if (context.application_id !== context.update_set.application_id) fail('Selected scope and update set belong to different applications.');
55
+ if (!['in progress', 'in_progress'].includes(context.update_set.state.toLowerCase())) fail('Selected capture update set is not in progress.');
56
+ if (expected.scope !== undefined) {
57
+ const scope = await exactContextRecord(app.sdk, 'sys_scope', 'scope', expected.scope);
58
+ if ((scope.sys_id?.value ?? scope.sys_id) !== context.application_id) fail('Intended scope does not match fresh selected scope.');
33
59
  }
34
- const context = { scope: application?.scope || null, application_id: application?.appSysId || null,
35
- update_set: updateSet ? { name: updateSet.name, sys_id: updateSet.sys_id, state: updateSet.state || null } : null,
36
- diagnostics: [], approval_required: false, approved: false };
37
- if (!context.scope || !updateSet) context.diagnostics.push(diagnostic('capture_context_unknown',
38
- 'Capture context could not be determined. Identify the intended scope and update set before development changes.', 'jsn updatesets list'));
39
- const appId = getStringField(updateSet || {}, 'application');
40
- const rawAppId = updateSet?.application?.value || appId;
41
- if (application?.appSysId && rawAppId && application.appSysId !== rawAppId) {
42
- context.diagnostics.push(diagnostic('update_set_scope_mismatch',
43
- `Selected scope ${context.scope} and update set ${updateSet.name} belong to different applications; changes may not be captured in this set.`,
44
- `jsn scopes set ${quoteShellArg(rawAppId)}`));
60
+ if (caps.transactionScopeOption && argv[caps.transactionScopeOption] !== undefined) {
61
+ const scope = await exactContextRecord(app.sdk, 'sys_scope', 'scope', argv[caps.transactionScopeOption]);
62
+ if ((scope.sys_id?.value ?? scope.sys_id) !== context.application_id) fail('Command transaction scope differs from verified intended scope.');
45
63
  }
46
- if (updateSet?.state && !['in progress', 'in_progress'].includes(updateSet.state.toLowerCase())) {
47
- context.diagnostics.push(diagnostic('update_set_not_in_progress', `Selected update set ${updateSet.name} is ${updateSet.state}; select an in-progress capture set.`, 'jsn updatesets set', 'error'));
48
- const error = errUsageHint('Selected capture update set is not in progress.', 'Run: jsn updatesets set');
49
- error.context = context; throw error;
64
+ if (expected.update_set !== undefined) {
65
+ const set = await exactContextRecord(app.sdk, 'sys_update_set', 'name', expected.update_set);
66
+ if ((set.sys_id?.value ?? set.sys_id) !== context.update_set.sys_id) fail('Intended update set does not match fresh selected update set.');
50
67
  }
51
- const globalDefault = context.scope?.toLowerCase() === 'global' && updateSet?.name?.toLowerCase() === 'default';
52
- if (globalDefault) {
53
- context.approval_required = true;
54
- context.diagnostics.push(diagnostic('global_default_update_set',
55
- 'Global scope + Default update set can capture customization in the wrong place or leave changes untracked. Select or create a dedicated update set; not all record changes are update-set tracked.',
56
- 'jsn updatesets create --name "My Feature"'));
68
+ // Never align/switch a session implicitly. Persisted and effective selections
69
+ // are independent evidence; both must agree before customization can proceed.
70
+ const [scopeResponse, setResponse] = await Promise.all([
71
+ app.sdk.request(`${app.sdk.baseURL}/api/now/ui/concoursepicker/application`, { method: 'GET', readOnly: true }),
72
+ app.sdk.request(`${app.sdk.baseURL}/api/now/ui/concoursepicker/updateset`, { method: 'GET', readOnly: true }),
73
+ ]);
74
+ if (scopeResponse?.result?.current !== context.application_id || setResponse?.result?.current?.sysId !== context.update_set.sys_id) fail('Effective session context is unknown or differs from the selected preferences. No context was switched.');
75
+ context.verified = true;
76
+ if (caps.mutationContext === 'table') context.table = caps.table || argv.table;
77
+ context.source = 'fresh_preferences_and_session';
78
+ context.expected = expected;
79
+ context.diagnostics = [];
80
+ context.approval_required = context.scope.toLowerCase() === 'global' && context.update_set.name.toLowerCase() === 'default';
81
+ context.approved = false;
82
+ if (interactive && (!expected.scope || !expected.update_set) && !context.approval_required) {
83
+ if (!await ask({ message: `Confirm customization in scope ${context.scope}; update set ${context.update_set.name} (${context.update_set.sys_id})?`, default: false })) fail('Customization context was not confirmed.');
84
+ context.approved = true;
85
+ }
86
+ if (context.approval_required) {
87
+ context.diagnostics.push({ code: 'global_default_update_set', severity: 'warning', message: 'Global + Default requires approval for this exact operation.' });
57
88
  if (argv.force) context.approved = true;
58
- else if (canUsePicker(app, argv)) {
59
- context.approved = await ask({ message: `Scope: Global; update set: Default. ${context.diagnostics.at(-1).message} Approve this exact mutation: ${['jsn', ...rawArgs].map(quoteShellArg).join(' ')}?`, default: false });
60
- }
89
+ else if (interactive) context.approved = await ask({ message: `Scope: Global; update set: Default. Approve this exact mutation: ${['jsn', ...rawArgs].map(quoteShellArg).join(' ')}?`, default: false });
61
90
  if (!context.approved) {
62
- const target = app.session?.profileName ? ` --profile ${quoteShellArg(app.session.profileName)}` : '';
63
- const rerun = ['jsn', ...rawArgs.filter(arg => arg !== '--force')].map(quoteShellArg).join(' ') + (rawArgs.includes('--profile') ? '' : target);
64
- const error = new AppError(CodeConfirmationRequired, 'Mutation in Global scope + Default update set requires explicit approval.',
65
- `Select a dedicated set: jsn updatesets set; or jsn updatesets create --name "My Feature". Ask the user to approve this exact operation, then rerun: ${rerun} --force`);
91
+ const error = new AppError(CodeConfirmationRequired, 'Mutation in Global scope + Default update set requires explicit approval.', 'Select a dedicated set or obtain user approval for this exact operation, then rerun with --force and explicit expectations.');
66
92
  error.context = context; throw error;
67
93
  }
68
94
  }
69
- if (canUsePicker(app, argv)) {
70
- process.stderr.write(`Mutation context: scope ${context.scope || 'unknown'}; update set ${updateSet?.name || 'unknown'}${updateSet?.sys_id ? ` (${updateSet.sys_id})` : ''}.\n`);
71
- for (const item of context.diagnostics) process.stderr.write(`Warning (${item.code}): ${item.message} Run: ${item.remediation.command}\n`);
72
- }
95
+ if (interactive) process.stderr.write(`Mutation context: scope ${context.scope}; update set ${context.update_set.name} (${context.update_set.sys_id}); user ${context.user.user_name}.\n`);
73
96
  return context;
74
97
  }
package/src/output.js CHANGED
@@ -136,7 +136,7 @@ export class OutputWriter {
136
136
  // typo looked like a successful empty result until the next tool in the
137
137
  // pipeline failed to parse it. Present null/false/0/"" still print as-is.
138
138
  if (this.jqFilter) {
139
- const envelope = { ok: true, data, summary: opts.summary || '', breadcrumbs: opts.breadcrumbs || [] };
139
+ const envelope = { ok: true, data, summary: opts.summary || '', breadcrumbs: opts.breadcrumbs || [], ...(opts.context ? { context: opts.context } : {}) };
140
140
  const value = resolvePath(envelope, this.jqFilter);
141
141
  if (value === undefined) throw errExtractionNotFound(this.jqFilter);
142
142
  const indent = this.verbose && !this.raw ? 2 : undefined;
@@ -1,5 +1,7 @@
1
1
  import { isHexString, getStringField, assertSafeExactMatch } from '../helpers.js';
2
2
  import { discoverFlowContextFields, normalizeFlowContext } from '../flow-context.js';
3
+ import { tableReadParams } from '../table-read-params.js';
4
+ import { boundedReads } from '../bounded-reads.js';
3
5
 
4
6
  export async function resolveIdentifier(app, table, identifier) {
5
7
  // If it looks like a sys_id (32 hex chars), use it directly
@@ -86,24 +88,36 @@ async function resolveHistoryDisplayValues(app, table, history) {
86
88
  }
87
89
  }
88
90
 
89
- // Batch lookup choice labels
91
+ // Preserve each exact field/value query and its one-row limit. Batching
92
+ // changes HTTP envelopes, not the number or authorization of server reads.
90
93
  const choiceLabelMap = new Map();
91
- if (choiceLookups.size > 0) {
92
- for (const key of choiceLookups) {
93
- const [field, val] = key.split('|');
94
- const params = new URLSearchParams();
95
- params.set('sysparm_query', `name=${table}^element=${field}^value=${val}^language=en`);
96
- params.set('sysparm_limit', '1');
97
- params.set('sysparm_fields', 'value,label');
98
- params.set('sysparm_display_value', 'all');
99
- try {
100
- const choices = await app.sdk.list('sys_choice', params);
101
- if (choices.length > 0) {
102
- const label = choices[0].label?.display_value || choices[0].label;
103
- if (label) choiceLabelMap.set(key, label);
104
- }
105
- } catch { /* non-fatal */ }
94
+ const lookups = [...choiceLookups].map(key => {
95
+ const [field, val] = key.split('|');
96
+ return { key, params: new URLSearchParams({
97
+ sysparm_query: `name=${table}^element=${field}^value=${val}^language=en`,
98
+ sysparm_limit: '1', sysparm_fields: 'value,label', sysparm_display_value: 'all',
99
+ }) };
100
+ });
101
+ let choicesByLookup;
102
+ if (lookups.length > 1 && typeof app.sdk.batch === 'function') {
103
+ try {
104
+ const batch = await app.sdk.batch(lookups.map(({ params }, index) => ({
105
+ id: String(index), url: `/api/now/table/sys_choice?${tableReadParams(params, app.sdk)}`,
106
+ })));
107
+ choicesByLookup = batch.results.map(item => item.ok && Array.isArray(item.data?.result) ? item.data.result : []);
108
+ } catch {
109
+ // Existing policy: labels are optional. Never retry an ACL denial,
110
+ // malformed response or uncertain batch failure as individual reads.
111
+ choicesByLookup = lookups.map(() => []);
106
112
  }
113
+ } else {
114
+ choicesByLookup = await boundedReads(lookups, async ({ params }) => {
115
+ try { return await app.sdk.list('sys_choice', params); } catch { return []; }
116
+ });
117
+ }
118
+ for (const [index, choices] of choicesByLookup.entries()) {
119
+ const label = choices[0]?.label?.display_value || choices[0]?.label;
120
+ if (label) choiceLabelMap.set(lookups[index].key, label);
107
121
  }
108
122
 
109
123
  // Apply resolutions to history entries
@@ -20,10 +20,10 @@ export function recordListParams({ limit, offset, query, fields, displayValue: r
20
20
  return params;
21
21
  }
22
22
 
23
- export function listRecords(sdk, { table, params, displayValues, ...options }) {
23
+ export function listRecords(sdk, { table, params, displayValues, responseMetadata, ...options }) {
24
24
  const query = tableReadParams(params || recordListParams(options), sdk);
25
25
  if (displayValues !== undefined) query.set('sysparm_display_value', displayValue(displayValues));
26
- return sdk.list(table, query);
26
+ return responseMetadata ? sdk.list(table, query, { responseMetadata }) : sdk.list(table, query);
27
27
  }
28
28
 
29
29
  export function getRecord(sdk, options) {
package/src/sdk-batch.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // Optional, read-only ServiceNow Batch REST transport. No ordinary SDK call is
2
2
  // routed here implicitly; writes are deliberately outside this initial contract.
3
3
  import { randomUUID } from 'node:crypto';
4
+ import { boundedReads } from './bounded-reads.js';
4
5
  import { AppError, errAPI, errUsage } from './errors.js';
5
6
 
6
7
  const UNSUPPORTED = new Set([404, 405, 501]);
@@ -121,7 +122,7 @@ export async function batchRead(sdk, requests, { fallback = true, chunkSize = 50
121
122
  }
122
123
  if (useIndividual) {
123
124
  transports.add('individual');
124
- for (const request of chunk) results.push(await individual(sdk, request, timeout));
125
+ results.push(...await boundedReads(chunk, request => individual(sdk, request, timeout)));
125
126
  }
126
127
  }
127
128
  const successful = results.filter(item => item.ok).length;
package/src/sdk.js CHANGED
@@ -334,7 +334,7 @@ export class SDKClient {
334
334
  async request(endpoint, opts = {}) {
335
335
  // Some provider mutations are GET-shaped. Keep this local replay policy
336
336
  // out of fetch options rather than treating their HTTP method as read-only.
337
- const { timeout = this.timeout, readOnly = false, stateful = false, touchLastSeen, domain = this.domain, ...requestOptions } = opts;
337
+ const { timeout = this.timeout, readOnly = false, stateful = false, touchLastSeen, domain = this.domain, responseMetadata, ...requestOptions } = opts;
338
338
  if (readOnly && (requestOptions.method || 'GET').toUpperCase() !== 'GET') throw new Error('Read-only SDK requests require GET');
339
339
  return this._withAuthenticatedRequest(endpoint, requestOptions, {
340
340
  timeout,
@@ -350,6 +350,13 @@ export class SDKClient {
350
350
  }, async (resp) => {
351
351
  const body = await resp.text();
352
352
  if (!resp.ok) throw errAPI(resp.status, body || resp.statusText);
353
+ if (responseMetadata) {
354
+ // Invocation-local receipt, never a cache: only accept a complete safe
355
+ // integer from this exact successful response (not an empty header).
356
+ const count = resp.headers.get('X-Total-Count');
357
+ responseMetadata.total = count !== null && /^\d+$/.test(count) && Number.isSafeInteger(Number(count))
358
+ ? Number(count) : undefined;
359
+ }
353
360
  if (resp.status === 204 || body === '') return null;
354
361
 
355
362
  // Preserve read-only credential-write suppression and the existing empty-body behavior.
@@ -431,7 +438,16 @@ export class SDKClient {
431
438
  return result?.result || null;
432
439
  }
433
440
 
441
+ async _guardTableMutation(table, id, data) {
442
+ const context = this.mutationContext;
443
+ if (!context?.verified || context.table !== table) return;
444
+ const { assertMutationScope } = await import('./intended-context.js');
445
+ if (id) assertMutationScope(context, (await this.get(table, id))?.sys_scope, 'Record target');
446
+ if (data && Object.hasOwn(data, 'sys_scope')) assertMutationScope(context, data.sys_scope, 'Record payload');
447
+ }
448
+
434
449
  async create(table, data) {
450
+ await this._guardTableMutation(table, null, data);
435
451
  const endpoint = `${this.baseURL}/api/now/table/${table}`;
436
452
  const result = await this.request(endpoint, {
437
453
  method: 'POST',
@@ -441,6 +457,7 @@ export class SDKClient {
441
457
  }
442
458
 
443
459
  async update(table, sysID, data) {
460
+ await this._guardTableMutation(table, sysID, data);
444
461
  const endpoint = `${this.baseURL}/api/now/table/${table}/${sysID}`;
445
462
  const result = await this.request(endpoint, {
446
463
  method: 'PUT',
@@ -450,6 +467,7 @@ export class SDKClient {
450
467
  }
451
468
 
452
469
  async delete(table, sysID) {
470
+ await this._guardTableMutation(table, sysID);
453
471
  const endpoint = `${this.baseURL}/api/now/table/${table}/${sysID}`;
454
472
  await this.request(endpoint, { method: 'DELETE' });
455
473
  }
@@ -1,8 +1,6 @@
1
1
  import * as prompts from './prompts.js';
2
2
  const { confirm, select, input } = prompts;
3
- import { ensureLocalDocumentation } from './commands/docs/local.js';
4
3
  import { saveConfig } from './config.js';
5
- import { docsServiceUrl, DEFAULT_DOCS_URL } from './commands/docs/client.js';
6
4
 
7
5
  export function connectionPreferences(config, existing = {}, flags = {}) {
8
6
  const saved = { read_only: false, skip_confirmations: false, include_counts: true };
@@ -32,11 +30,13 @@ export async function chooseConnectionPreferences(config, flags = {}, prompts =
32
30
  }
33
31
 
34
32
  export async function configureDocumentation(config, prompts = { input, confirm }) {
33
+ const { docsServiceUrl, DEFAULT_DOCS_URL } = await import('./commands/docs/client.js');
35
34
  const current = config.docs || { source: 'hosted', url: DEFAULT_DOCS_URL };
36
35
  const hosted = await prompts.confirm({ message: 'Use JSN-hosted documentation?', default: current.source === 'hosted' });
37
36
  const next = { source: hosted ? 'hosted' : 'custom', url: DEFAULT_DOCS_URL };
38
37
  if (!hosted && await prompts.confirm({ message: 'Run a local documentation server for you?', default: current.source !== 'custom' })) {
39
38
  next.source = 'local';
39
+ const { ensureLocalDocumentation } = await import('./commands/docs/local.js');
40
40
  next.url = (await ensureLocalDocumentation()).url;
41
41
  } else if (!hosted) {
42
42
  next.url = await prompts.input({ message: 'Docs service base URL:', default: current.source === 'custom' ? current.url : 'http://127.0.0.1:3000',