@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
@@ -5,7 +5,7 @@ import { runRepl } from '../eval-repl.js';
5
5
 
6
6
  // The whole command is a mutation surface (runs arbitrary server-side JS) —
7
7
  // declared as `['']` so the root `jsn eval` command are gated.
8
- declareCapabilities('eval', { mutationSubcommands: [''] });
8
+ declareCapabilities('eval', { transactionScopeOption: 'scope', mutationSubcommands: [''] });
9
9
 
10
10
  export function evalCmd(wrap) {
11
11
  return {
@@ -13,11 +13,17 @@ export function evalCmd(wrap) {
13
13
  describe: 'Execute background scripts on the instance (--repl for interactive mode)',
14
14
  builder: (yargs) => {
15
15
  return yargs
16
+ .middleware(argv => {
17
+ if (!argv.repl) return;
18
+ const conflicts = ['script', 'file', 'stdin'].filter(key => argv[key]).map(key => `--${key}`);
19
+ if (conflicts.length) throw new Error(`--repl cannot be combined with ${conflicts.join(', ')}`);
20
+ if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error('--repl needs an interactive terminal. Use --script, --file or --stdin for scripts and agents.');
21
+ })
16
22
  .option('script', { alias: 's', type: 'string', describe: 'JavaScript code to execute (single-quote the script, double quotes inside: --script \'gs.log("Hello")\')' })
17
23
  .option('file', { alias: 'f', type: 'string', describe: 'Read script from file (avoids shell quoting issues)' })
18
24
  .option('stdin', { type: 'boolean', describe: 'Read script from stdin (pipe-friendly, e.g. cat script.js | jsn eval --stdin)' })
19
25
  .option('repl', { type: 'boolean', default: false, describe: 'Interactive mode: type a script, submit with .exec (requires a terminal)' })
20
- .option('scope', { alias: null, type: 'string', describe: 'Scope name or sys_id to run the script under (default: active scope from banner)' })
26
+ .option('scope', { alias: null, type: 'string', describe: 'Scope name or sys_id to run the script under (default: verified intended scope)' })
21
27
  // Script-mode flags (issue #177) — map to the Script Background form checkboxes
22
28
  .option('rollback', { type: 'boolean', default: true, describe: 'Record rollback context (--no-rollback to skip)' })
23
29
  .option('sandbox', { type: 'boolean', default: false, describe: 'Sandbox mode (KittyScript evaluator, single expression only — no DB writes)' })
@@ -26,12 +32,12 @@ export function evalCmd(wrap) {
26
32
  },
27
33
  handler: wrap(async (argv, app) => {
28
34
  let script;
29
- let scopeSysId = null;
35
+ let scopeSysId = app.mutationContext?.application_id || null;
30
36
 
31
37
  // Resolve execution scope: explicit --scope wins; otherwise use the
32
38
  // active scope from apps.current_app (same source as the banner);
33
39
  // fall back to global only when no active scope exists.
34
- let scope = argv.scope || '';
40
+ let scope = app.mutationContext?.scope || argv.scope || '';
35
41
  if (!scope) {
36
42
  try {
37
43
  const user = await getCurrentUser(app.sdk);
@@ -46,7 +52,7 @@ export function evalCmd(wrap) {
46
52
  }
47
53
  }
48
54
 
49
- if (scope) {
55
+ if (scope && !scopeSysId) {
50
56
  scopeSysId = await app.sdk.resolveScope(scope);
51
57
  if (!scopeSysId) {
52
58
  throw new Error(`Scope not found: ${scope}`);
@@ -1,16 +1,17 @@
1
+ import { flowsCmdDefinition } from '../command-families.js';
1
2
  import { searchFlows, formatFlowSearch } from '../flow-search.js';
2
3
  import fs from 'node:fs';
3
4
  import { prepareFlowClone, cloneFlow } from '../flow-clone.js';
4
5
  import { canUsePicker } from '../helpers.js';
5
6
  import { formatRecordForDisplay, formatCommandList, getStringField, interactiveList } from '../helpers.js';
6
7
  import { discoverFlowContextFields, normalizeFlowContext, summarizeFlowContexts, formatFlowContextSummary, aggregateFlowContextMappings, mergeFlowContextStats, buildFlowContextQuery } from '../flow-context.js';
7
- import { declareCapabilities } from '../capabilities.js';
8
8
  import { docLink } from '../docs-links.js';
9
9
  import { inspectFlow } from '../flow-inspection.js';
10
10
  import { publishFlows, publishFlowLifecycle, publishDoctor, flowStatus } from '../flow-publish.js';
11
11
  import { resolveRecord, unwrapSysId } from '../resolve-record.js';
12
12
  import { createFlowFromManifest, updateFlowFromManifest, readCurrentUpdateSet, readCatalogItemVariables } from '../flow-create.js';
13
13
  import { alignUpdateSetCapture } from '../context.js';
14
+ import { assertMutationScope, assertMutationRecordScope } from '../intended-context.js';
14
15
  import { EXCLUDED_TRIGGER_TYPES, SUPPORTED_TRIGGER_TYPES, readTriggerCatalog, readTriggerInputDefinitions } from '../flow-triggers.js';
15
16
  import { testFlow } from '../flow-test.js';
16
17
  import { releaseOwnFlowSafeEdit } from '../flow-safe-edit.js';
@@ -74,7 +75,7 @@ function triggerGuidance(trigger) {
74
75
  };
75
76
  }
76
77
 
77
- declareCapabilities('flows', { mutationSubcommands: ['clone', 'copy', 'create', 'update', 'edit', 'delete', 'publish', 'test', 'unlock'] });
78
+
78
79
 
79
80
  function renderChecks(checks) {
80
81
  return checks.map((c) => {
@@ -87,9 +88,7 @@ export function flowsCmd(wrap) {
87
88
  const originalWrap = wrap;
88
89
  wrap = handler => originalWrap((argv, app) => cancelled(() => handler(argv, app)));
89
90
  return {
90
- command: 'flows [subcommand]',
91
- aliases: ['flow'],
92
- describe: 'Manage Flow Designer flows',
91
+ ...flowsCmdDefinition,
93
92
  builder: (yargs) => {
94
93
  return yargs
95
94
  .command({
@@ -321,6 +320,7 @@ Documentation: ${docLink('flows')}`),
321
320
  resource: argv.action ? 'Custom action' : 'Flow',
322
321
  }));
323
322
 
323
+ await assertMutationRecordScope(app, argv.action ? 'sys_hub_action_type_definition' : 'sys_hub_flow', sysID);
324
324
  await confirmDesignerMutation(argv, app, `Publish and activate ${argv.action ? 'action' : 'flow'} ${sysID}?`);
325
325
  if (!argv.action) {
326
326
  const lifecycle = await publishFlowLifecycle(app.sdk, app.getEffectiveInstance(), sysID);
@@ -408,7 +408,12 @@ Documentation: ${docLink('flows')}`),
408
408
  app.requireInstance();
409
409
  const identifier = await pickFlow(argv, app);
410
410
  if (identifier === undefined) return;
411
+ if (app.mutationContext?.verified) {
412
+ const source = await resolveRecord(app.sdk, { table: 'sys_hub_flow', identifier, matchField: 'name', resource: 'Flow' });
413
+ assertMutationScope(app.mutationContext, source.sys_scope, 'Flow clone source');
414
+ }
411
415
  const plan = await prepareFlowClone(app.sdk, app.getEffectiveInstance(), identifier, { ...argv, interactive: canUsePicker(app, argv) });
416
+ assertMutationScope(app.mutationContext, plan.scope, 'Flow clone');
412
417
  await confirmDesignerMutation(argv, app,
413
418
  `Clone ${plan.source.name} (${plan.source.id}) as ${JSON.stringify(plan.name)} in ${plan.scope}; inactive Draft, source unchanged`,
414
419
  ['flows', 'clone', plan.source.id, '--name', plan.name]);
@@ -437,6 +442,7 @@ Documentation: ${docLink('flows')}`),
437
442
  } catch (error) {
438
443
  throw new Error(`Invalid flow manifest JSON: ${error.message}`, { cause: error });
439
444
  }
445
+ assertMutationScope(app.mutationContext, manifest.scope, 'Flow creation manifest');
440
446
  const result = await createFlowFromManifest(app.sdk, app.getEffectiveInstance(), manifest, {
441
447
  readUpdateSet: () => readCurrentUpdateSet(app.sdk),
442
448
  ensureCapture: intended => alignUpdateSetCapture(app.sdk, intended),
@@ -482,6 +488,11 @@ Documentation: ${docLink('flows')}`),
482
488
  } catch (error) {
483
489
  throw new Error(`Invalid flow update manifest JSON: ${error.message}`, { cause: error });
484
490
  }
491
+ if (!argv.preview && app.mutationContext?.verified) {
492
+ const target = await resolveRecord(app.sdk, { table: 'sys_hub_flow', identifier, matchField: 'name', resource: 'Flow' });
493
+ assertMutationScope(app.mutationContext, target.sys_scope, 'Flow update target');
494
+ if (manifest.scope !== undefined) assertMutationScope(app.mutationContext, manifest.scope, 'Flow update manifest');
495
+ }
485
496
  if (!argv.preview) await confirmDesignerMutation(argv, app, `Update flow ${identifier}; unspecified components and inputs are preserved. A published flow is edited as its working definition: the published snapshot must stay unchanged.`);
486
497
  const result = await updateFlowFromManifest(app.sdk, app.getEffectiveInstance(), argv.identifier, manifest, {
487
498
  preview: argv.preview,
@@ -545,6 +556,7 @@ Documentation: ${docLink('flows')}`),
545
556
  sysparm_limit: '1',
546
557
  }));
547
558
  if (!flow) throw errUsage(`Flow ${identifier} (${sysID}) was not found`);
559
+ assertMutationScope(app.mutationContext, flow.sys_scope, 'Flow deletion target');
548
560
  const name = getStringField(flow, 'name');
549
561
  const active = getStringField(flow, 'active') === 'true';
550
562
  const counted = async () => {
@@ -3,7 +3,7 @@ import { declareCapabilities } from '../capabilities.js';
3
3
 
4
4
  // add/remove write sys_user_grmember; the mutation guard (instance +
5
5
  // read-only profile) and the delete confirmation both key off this.
6
- declareCapabilities('groupmembers', { mutationSubcommands: ['add', 'remove'] });
6
+ declareCapabilities('groupmembers', { mutationContext: 'operational', mutationSubcommands: ['add', 'remove'] });
7
7
 
8
8
  export function groupMembersCmd(wrap) {
9
9
  return {
@@ -3,7 +3,7 @@ import { declareCapabilities } from '../capabilities.js';
3
3
 
4
4
  // add/remove write sys_group_has_role; the mutation guard (instance +
5
5
  // read-only profile) and the delete confirmation both key off this.
6
- declareCapabilities('grouproles', { mutationSubcommands: ['add', 'remove'] });
6
+ declareCapabilities('grouproles', { mutationContext: 'operational', mutationSubcommands: ['add', 'remove'] });
7
7
 
8
8
  export function groupRolesCmd(wrap) {
9
9
  return {
@@ -1,7 +1,7 @@
1
1
  import { formatRecordForDisplay, getStringField, interactiveList, resolveFieldsParam, assertSafeExactMatch, buildRecordPayload } from '../helpers.js';
2
2
  import { declareCapabilities } from '../capabilities.js';
3
3
 
4
- declareCapabilities('groups', { mutationSubcommands: ['create', 'update', 'delete'] });
4
+ declareCapabilities('groups', { mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
5
5
 
6
6
  export function groupsCmd(wrap) {
7
7
  return {
@@ -1,3 +1,4 @@
1
+ import { midserversCmdDefinition } from '../command-families.js';
1
2
  import fs from 'node:fs';
2
3
  import path from 'node:path';
3
4
  import process from 'node:process';
@@ -9,7 +10,6 @@ import { prepareWindowsRemoteMidServer, installWindowsRemoteMidServer, startWind
9
10
  import { prepareLinuxRemoteMidServer, installLinuxRemoteMidServer, startLinuxRemoteMidServer, stopLinuxRemoteMidServer, logsLinuxRemoteMidServer, removeLinuxRemoteMidServer } from '../midserver-linux-remote.js';
10
11
  import { downloadRemoteMidRecipe } from '../midserver-remote-recipe.js';
11
12
  import { FormatAuto } from '../output.js';
12
- import { declareCapabilities } from '../capabilities.js';
13
13
  import { resolveRecord, unwrapSysId } from '../resolve-record.js';
14
14
  import { detectDocker, defaultRun, installDockerMidServer, midInstallDirectory, normalizeMidName, validateMidCredentials } from '../midserver-install.js';
15
15
  import { detectDirectPlatform, followDirectLog, installDirectMidServer, readDirectInstallation, removeDirectInstallation, resolveDirectLogFile, runDirectInstallation } from '../midserver-direct.js';
@@ -20,7 +20,7 @@ const LIST_FIELDS = ['sys_id', 'name', 'status', 'host_name', 'ip_address', 'ver
20
20
  const DEFAULT_TIMEOUT = 120000;
21
21
  const DEFAULT_INTERVAL = 2000;
22
22
 
23
- declareCapabilities('midservers', { mutationSubcommands: ['add', 'remove', 'execute', 'start', 'stop', 'validate'] });
23
+
24
24
 
25
25
  function agentName(record) {
26
26
  const name = getStringField(record, 'name');
@@ -417,9 +417,7 @@ async function showMidServerLogs(app, identifier, argv) {
417
417
 
418
418
  export function midserversCmd(wrap) {
419
419
  return {
420
- command: 'midservers [subcommand]',
421
- aliases: ['midserver', 'mid'],
422
- describe: 'Manage ServiceNow MID Servers and run commands through them',
420
+ ...midserversCmdDefinition,
423
421
  builder: (y) => y
424
422
  .command(midDiagnosticsCommand('issues', wrap))
425
423
  .command(midDiagnosticsCommand('events', wrap))
@@ -1,3 +1,4 @@
1
+ import { perfCmdDefinition } from '../command-families.js';
1
2
  import { errUsageHint, errUsage } from '../errors.js';
2
3
  import { captureRun, listRuns, getRun, compareRuns, formatRunDetailed, formatRunList, formatComparisonDetailed } from '../perf.js';
3
4
  import { topTransactionsCmd } from './transactions.js';
@@ -54,9 +55,7 @@ function compareHint(runId) {
54
55
 
55
56
  export function perfCmd(wrap) {
56
57
  return {
57
- command: 'perf [subcommand]',
58
- aliases: ['performance'],
59
- describe: 'Capture and compare read-only ServiceNow performance summaries',
58
+ ...perfCmdDefinition,
60
59
  builder: (y) => y
61
60
  .command({
62
61
  command: 'capture',
@@ -5,8 +5,10 @@ import { errUsage } from '../errors.js';
5
5
  import { AmbClient } from '../amb.js';
6
6
  import { watchRecord } from '../record-watch.js';
7
7
  import { declareCapabilities } from '../capabilities.js';
8
+ import { assertMutationRecordScope, assertMutationScope } from '../intended-context.js';
8
9
 
9
10
  declareCapabilities('records', {
11
+ mutationContext: 'table',
10
12
  mutationSubcommands: ['create', 'update', 'delete', 'bulk'],
11
13
  });
12
14
 
@@ -149,7 +151,8 @@ export function recordsCmd(wrap) {
149
151
  // Text/table fallback (or sys-id direct lookup)
150
152
  const fields = resolveFieldsParam(columns);
151
153
  const params = recordListParams({ limit: argv['sys-id'] ? 1 : argv.limit, offset: argv.offset, fields, query });
152
- const records = await listRecords(app.sdk, { table, params, displayValues: argv.displayValues });
154
+ const responseMetadata = {};
155
+ const records = await listRecords(app.sdk, { table, params, displayValues: argv.displayValues, responseMetadata });
153
156
  const missingColumns = fields ? findOmittedColumns(records, columns) : [];
154
157
  const presentColumns = missingColumns.length ? columns.filter(c => !missingColumns.includes(c)) : columns;
155
158
  const displayRecords = fields && !argv.displayValues ? records.map(r => formatRecordForDisplay(r, presentColumns)) : records;
@@ -160,7 +163,10 @@ export function recordsCmd(wrap) {
160
163
  const countsOn = argv.count !== false && profile.include_counts !== false;
161
164
  let total;
162
165
  if (countsOn && !argv['sys-id']) {
163
- try { total = await app.sdk.aggregateCount(table, query); } catch { total = undefined; }
166
+ total = responseMetadata.total;
167
+ if (total === undefined) {
168
+ try { total = await app.sdk.aggregateCount(table, query); } catch { total = undefined; }
169
+ }
164
170
  }
165
171
 
166
172
  const breadcrumbs = [
@@ -529,6 +535,10 @@ export function recordsCmd(wrap) {
529
535
  offset += recs.length;
530
536
  }
531
537
  const targets = sysIDs.slice(0, argv.limit);
538
+ if (app.mutationContext?.verified) {
539
+ if (Object.hasOwn(set, 'sys_scope')) assertMutationScope(app.mutationContext, set.sys_scope, 'Bulk payload');
540
+ for (const id of targets) await assertMutationRecordScope(app, argv.table, id);
541
+ }
532
542
  let updated = 0;
533
543
  const failures = [];
534
544
  for (const id of targets) {
@@ -3,7 +3,7 @@ import { requireCurrentUserSysId, setCurrentApplication } from '../context.js';
3
3
  import { declareCapabilities } from '../capabilities.js';
4
4
  import { unwrapSysId } from '../resolve-record.js';
5
5
 
6
- declareCapabilities('scopes', { mutationSubcommands: ['create', 'set'], mutationContextExemptSubcommands: ['create', 'set'] });
6
+ declareCapabilities('scopes', { mutationSubcommands: ['create', 'set'], mutationContextExemptSubcommands: ['set'] });
7
7
 
8
8
  /**
9
9
  * Resolve a scope identifier to a single sys_scope record.
@@ -14,7 +14,7 @@ import { declareCapabilities } from '../capabilities.js';
14
14
 
15
15
  // `scrapi create` builds a full Scripted REST API in one call (list/show are
16
16
  // reads). Registered at the root.
17
- declareCapabilities('scrapi', { mutationSubcommands: ['create'] });
17
+ declareCapabilities('scrapi', { transactionScopeOption: 'scope', mutationSubcommands: ['create'] });
18
18
 
19
19
  /**
20
20
  * Parse a --resource flag value of the form:
@@ -257,7 +257,7 @@ export function scrapiCmd(wrap) {
257
257
  const description = argv.description || '';
258
258
 
259
259
  // 2. Resolve scope if provided
260
- let scopeSysId = null;
260
+ let scopeSysId = app.mutationContext?.application_id || null;
261
261
  if (argv.scope) {
262
262
  scopeSysId = await app.sdk.resolveScope(argv.scope);
263
263
  if (!scopeSysId) {
@@ -1,6 +1,6 @@
1
+ import { skippedUpdatesCmdDefinition } from '../command-families.js';
1
2
  import { checkbox, select, confirm } from '../prompts.js';
2
3
  import { canUsePicker, interactiveList, getStringField } from '../helpers.js';
3
- import { declareCapabilities } from '../capabilities.js';
4
4
  import { errUsage } from '../errors.js';
5
5
  import { discoverSkippedUpdates, reviewSkippedUpdate, prepareSkippedBatch, processSkippedBatch, raw, SKIP_TABLE } from '../skipped-updates.js';
6
6
 
@@ -27,7 +27,6 @@ export function renderSkippedPreview(preview) {
27
27
  }
28
28
 
29
29
  export function skippedUpdatesCmd(wrap, ui = {}) {
30
- declareCapabilities('skipped-updates', { mutationSubcommands: ['process'] });
31
30
  const prompts = { checkbox, select, confirm, canUsePicker, interactiveList, ...ui };
32
31
  async function showReview(app, id) {
33
32
  const review = await reviewSkippedUpdate(app.sdk, id);
@@ -49,7 +48,7 @@ export function skippedUpdatesCmd(wrap, ui = {}) {
49
48
  { name: 'Return to base system, discard customization', value: 'revert' }] });
50
49
  return { ids, action, instance: app.getEffectiveInstance() };
51
50
  }
52
- return { command: 'skipped-updates', describe: 'Review and process existing unresolved skipped updates across all upgrade history',
51
+ return { ...skippedUpdatesCmdDefinition,
53
52
  builder: y => y
54
53
  .command({ command: 'list', describe: 'Discover unresolved skips instance-wide, independent of new upgrades',
55
54
  builder: y => y.option('limit', { type: 'number', default: 100, describe: 'Page size, maximum 500' })
@@ -1,8 +1,8 @@
1
+ import { subscriptionsCmdDefinition } from '../command-families.js';
1
2
  import { refreshSchedules } from '../schedule-cache.js';
2
- import { declareCapabilities } from '../capabilities.js';
3
3
  import { loadSchedule, scheduleCatalog, scheduleSnapshot, formatSchedule, estimateSubscription, formatEstimate } from '../subscriptions.js';
4
4
 
5
- declareCapabilities('subscriptions', { noInstance: true, skipDailyChecks: true, mutationSubcommands: [] });
5
+
6
6
  export function subscriptionsCmd(wrap) {
7
7
  const local = (argv, app) => {
8
8
  const snapshot = scheduleSnapshot();
@@ -21,7 +21,7 @@ export function subscriptionsCmd(wrap) {
21
21
  app.ok(data, { summary: 'Local dated metering schedules, not purchased rights' });
22
22
  };
23
23
  return {
24
- command: 'subscriptions [subcommand]', describe: 'Inspect local metering schedules and compare illustrative ITOM populations',
24
+ ...subscriptionsCmdDefinition,
25
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
26
  const origin = process.env.JSN_DOCS_URL || app.config?.docs?.url;
27
27
  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);
@@ -4,7 +4,7 @@ import { getRecord, listRecords, recordListParams, createRecord, updateRecord, d
4
4
  import { resolveSysId } from '../resolve-record.js';
5
5
  import { declareCapabilities } from '../capabilities.js';
6
6
 
7
- declareCapabilities('tickets', { mutationSubcommands: ['create', 'update', 'delete'] });
7
+ declareCapabilities('tickets', { mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
8
8
 
9
9
  export function ticketsCmd(wrap) {
10
10
  return {
@@ -2,7 +2,7 @@ import { formatRecordForDisplay, getStringField, interactiveList, resolveFieldsP
2
2
  import { resolveRecord, resolveSysId } from '../resolve-record.js';
3
3
  import { declareCapabilities } from '../capabilities.js';
4
4
 
5
- declareCapabilities('users', { mutationSubcommands: ['create', 'update', 'delete'] });
5
+ declareCapabilities('users', { mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
6
6
 
7
7
  export function usersCmd(wrap) {
8
8
  return {
@@ -1,4 +1,4 @@
1
- import { declareCapabilities } from '../capabilities.js';
1
+ import { workflowsCmdDefinition } from '../command-families.js';
2
2
  import { errUsage } from '../errors.js';
3
3
  import {
4
4
  inspectWorkflow,
@@ -11,7 +11,7 @@ import {
11
11
  // request in workflow-inspection.js is a Table API GET. Declaring no mutation
12
12
  // subcommands keeps the mutation guard and read-only profiles aligned with
13
13
  // what the command can actually do.
14
- declareCapabilities('workflows', { mutationSubcommands: [] });
14
+
15
15
 
16
16
  // A curated human view belongs to the command; keeping it non-enumerable
17
17
  // leaves the JSON envelope free of presentation text.
@@ -42,9 +42,7 @@ export function selectWorkflowStep(data, number) {
42
42
 
43
43
  export function workflowsCmd(wrap) {
44
44
  return {
45
- command: 'workflows [subcommand]',
46
- aliases: ['workflow'],
47
- describe: 'Inspect legacy Workflow Editor workflows (read-only)',
45
+ ...workflowsCmdDefinition,
48
46
  builder: (yargs) => yargs
49
47
  .command({
50
48
  command: 'list',
package/src/config.js CHANGED
@@ -58,6 +58,7 @@ function loadFromFile(cfg, filePath, source) {
58
58
  if (fileCfg.connection_defaults && typeof fileCfg.connection_defaults === 'object') cfg.connectionDefaults = fileCfg.connection_defaults;
59
59
  if (fileCfg.docs && typeof fileCfg.docs === 'object') cfg.docs = fileCfg.docs;
60
60
  }
61
+ if (source === 'local' && Object.hasOwn(fileCfg, 'write_context')) cfg.writeContext = fileCfg.write_context;
61
62
  if (fileCfg.instance_url) {
62
63
  cfg.instanceURL = fileCfg.instance_url;
63
64
  cfg.sources.instance_url = source;
package/src/context.js CHANGED
@@ -122,62 +122,14 @@ export async function readEffectiveUpdateSet(sdk) {
122
122
  };
123
123
  }
124
124
 
125
- /**
126
- * Make the warmed session's effective capture set match the persisted choice
127
- * before content writes, and verify the result.
128
- *
129
- * A fresh CLI invocation is a fresh authenticated session; the persisted
130
- * preference is the user's intentional choice, but nothing guarantees the new
131
- * session inherited it (`jsn updatesets create`/`set` may have selected the set
132
- * in a session that has since ended). When the two disagree, re-apply the
133
- * persisted selection through the same picker contract and verify it.
134
- *
135
- * Returns a report instead of throwing when the effective selection cannot be
136
- * read at all (for example an auth mode that cannot keep a UI session). A
137
- * readable-but-unalignable mismatch throws, so a content write never proceeds
138
- * into a set the CLI would then wrongly report.
139
- */
125
+ /** Verify capture consistency without ever changing the session. */
140
126
  export async function alignUpdateSetCapture(sdk, intended) {
141
- const intendedId = intended?.sys_id || '';
142
- let effective;
143
- try {
144
- effective = await readEffectiveUpdateSet(sdk);
145
- } catch (error) {
146
- return {
147
- intended: intended || null,
148
- effective: null,
149
- aligned: null,
150
- action: 'unverified',
151
- reason: `effective session selection could not be read: ${error.message}`,
152
- };
153
- }
154
- const report = { intended: intended || null, effective, aligned: null, action: 'none' };
155
- if (!intendedId) {
156
- report.reason = 'no persisted update-set selection (Default or unreadable preference)';
157
- return report;
158
- }
159
- if (effective.sys_id === intendedId) {
160
- report.aligned = true;
161
- return report;
162
- }
163
- try {
164
- await setCurrentUpdateSet(sdk, null, intendedId);
165
- } catch (error) {
166
- const message = `Session capture context could not be aligned with the selected update set before any content write. `
167
- + `This session resolves to ${effective.sys_id || 'an empty selection'} (${effective.name || 'unknown'}), `
168
- + `but the persisted selection is ${intended?.name || intendedId} (${intendedId}). ${error.message} `
169
- + 'No content was written. Re-select explicitly with `jsn updatesets set` in an interactive session, '
170
- + 'or use an auth profile that keeps a UI session, then retry.';
171
- const failure = new Error(message, { cause: error });
172
- failure.capture_context = { ...report, aligned: false, action: 'select_failed' };
173
- throw failure;
174
- }
175
- report.previous_effective = effective;
176
- report.effective = await readEffectiveUpdateSet(sdk);
177
- report.action = 'selected';
178
- report.aligned = report.effective.sys_id === intendedId;
179
- if (!report.aligned) {
180
- report.reason = 'session still resolves to a different set after re-selection';
127
+ const effective = await readEffectiveUpdateSet(sdk);
128
+ const report = { intended: intended || null, effective, aligned: false, action: 'refused' };
129
+ if (!intended?.sys_id || effective.sys_id !== intended.sys_id) {
130
+ const error = new Error('Effective capture set differs from the persisted selection or is unknown. No context was switched; select it explicitly with jsn updatesets set.');
131
+ error.capture_context = report;
132
+ throw error;
181
133
  }
182
- return report;
134
+ return { ...report, aligned: true, action: 'none' };
183
135
  }
@@ -1914,6 +1914,10 @@ async function planManifestSteps({ manifest, beforeDefinition, existingActions,
1914
1914
  export async function createFlowFromManifest(sdk, instance, inputManifest, options = {}) {
1915
1915
  const manifest = validateFlowManifest(inputManifest);
1916
1916
  const scope = manifest.scope;
1917
+ if (sdk.mutationContext?.verified) {
1918
+ const { assertMutationScope } = await import('./intended-context.js');
1919
+ assertMutationScope(sdk.mutationContext, scope, 'Flow creation transaction');
1920
+ }
1917
1921
  const idFactory = options.idFactory || (() => randomUUID());
1918
1922
  const readUpdateSet = options.readUpdateSet || (async () => null);
1919
1923
  const snapshots = [];
@@ -2141,6 +2145,11 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
2141
2145
  const published = !lifecycle.draft;
2142
2146
  const targetScope = stringValue(target.flow.sys_scope) || stringValue(target.flow.scope);
2143
2147
  const scope = manifest.scope ?? targetScope;
2148
+ if (sdk.mutationContext?.verified) {
2149
+ const { assertMutationScope } = await import('./intended-context.js');
2150
+ assertMutationScope(sdk.mutationContext, targetScope, 'Resolved flow target');
2151
+ assertMutationScope(sdk.mutationContext, scope, 'Flow update transaction');
2152
+ }
2144
2153
  const readUpdateSet = options.readUpdateSet || (async () => null);
2145
2154
  if (!scope) throw new Error(`Flow ${flowId} has no transaction scope`);
2146
2155
  if (manifest.scope !== undefined && targetScope && manifest.scope !== targetScope) throw new Error(`Flow ${flowId} scope does not match the update manifest`);
@@ -0,0 +1,68 @@
1
+ // Intent comes from the task, never from the current provider preferences.
2
+ import { assertSafeExactMatch, getStringField } from './helpers.js';
3
+ import { errUsageHint } from './errors.js';
4
+
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.');
7
+ }
8
+ const raw = (record, key) => record?.[key]?.value ?? record?.[key];
9
+ export async function exactContextRecord(sdk, table, field, identifier) {
10
+ if (typeof identifier !== 'string' || !identifier.trim()) throw contextFailure(`Missing intended ${table} identifier.`);
11
+ assertSafeExactMatch(identifier);
12
+ const byId = /^[a-f0-9]{32}$/i.test(identifier) || identifier === 'global';
13
+ const records = await sdk.list(table, new URLSearchParams({
14
+ sysparm_query: `${byId ? 'sys_id' : field}=${identifier}${!byId && table === 'sys_scope' ? `^ORname=${identifier}` : ''}`,
15
+ sysparm_limit: '2', sysparm_display_value: 'all',
16
+ }));
17
+ if (records.length !== 1 || !raw(records[0], 'sys_id')) throw contextFailure(`Intended ${table} is missing, unreadable or ambiguous.`);
18
+ return records[0];
19
+ }
20
+
21
+ export async function readWriteContext(sdk) {
22
+ const users = await sdk.list('sys_user', new URLSearchParams({
23
+ sysparm_query: 'user_name=javascript:gs.getUserName()', sysparm_limit: '2',
24
+ sysparm_fields: 'sys_id,user_name,name', sysparm_display_value: 'all',
25
+ }));
26
+ if (users.length !== 1 || !raw(users[0], 'sys_id') || !getStringField(users[0], 'user_name')) throw contextFailure('Current user is unknown.');
27
+ 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.`);
33
+ return raw(rows[0], 'value');
34
+ }
35
+ const [scopeId, setId] = await Promise.all([preference('apps.current_app'), preference('sys_update_set')]);
36
+ const [scope, set] = await Promise.all([sdk.get('sys_scope', scopeId), sdk.get('sys_update_set', setId)]);
37
+ const applicationId = raw(set, 'application');
38
+ if (!getStringField(scope || {}, 'scope') || !getStringField(set || {}, 'name') || !applicationId || !getStringField(set || {}, 'state')) throw contextFailure('Capture context is incomplete or unreadable.');
39
+ return {
40
+ user, scope: getStringField(scope, 'scope'), application_id: scopeId,
41
+ update_set: { sys_id: setId, name: getStringField(set, 'name'), state: getStringField(set, 'state'), application_id: applicationId },
42
+ source: 'fresh_preferences', domain: { verified: false, status: 'unverified', reason: 'X-Now-Domain is a request header, not proof of effective domain.' },
43
+ };
44
+ }
45
+
46
+ export function assertMutationScope(context, value, label = 'Mutation target') {
47
+ if (!context?.verified) return;
48
+ const scope = value?.value ?? value;
49
+ if (!scope || scope !== context.application_id) throw contextFailure(`${label} scope is unknown or differs from verified intended scope.`);
50
+ }
51
+
52
+ export async function assertMutationRecordScope(app, table, id) {
53
+ if (!app.mutationContext?.verified) return;
54
+ const record = await app.sdk.get(table, id);
55
+ assertMutationScope(app.mutationContext, record?.sys_scope, 'Resolved target');
56
+ }
57
+
58
+ export function intendedContext(app, argv) {
59
+ const saved = app.config.writeContext;
60
+ if (saved !== undefined) {
61
+ if (!saved || typeof saved !== 'object' || Array.isArray(saved)
62
+ || !saved.profile || saved.profile !== app.session?.profileName
63
+ || !saved.instance_url || saved.instance_url !== app.session?.instance) {
64
+ throw contextFailure('Task-local write_context must bind the selected profile and exact instance_url.');
65
+ }
66
+ }
67
+ return { scope: argv.expectScope ?? saved?.scope, update_set: argv.expectUpdateSet ?? saved?.update_set, domain: argv.expectDomain ?? saved?.domain };
68
+ }