@jacebenson/jsn 5.3.0-dev.136.1 → 5.3.0-dev.137.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.3.0-dev.136.1",
3
+ "version": "5.3.0-dev.137.1",
4
4
  "description": "A command-line interface for ServiceNow that follows the Unix philosophy: simple, composable, and scriptable.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -6,6 +6,7 @@ import { inspectFlow } from '../flow-inspection.js';
6
6
  import { publishFlows, publishFlowLifecycle, publishDoctor, flowStatus } from '../flow-publish.js';
7
7
  import { resolveRecord, unwrapSysId } from '../resolve-record.js';
8
8
  import { createFlowFromManifest, updateFlowFromManifest, readCurrentUpdateSet } from '../flow-create.js';
9
+ import { alignUpdateSetCapture } from '../context.js';
9
10
  import { EXCLUDED_TRIGGER_TYPES, SUPPORTED_TRIGGER_TYPES, readTriggerCatalog, readTriggerInputDefinitions } from '../flow-triggers.js';
10
11
  import { testFlow } from '../flow-test.js';
11
12
  import { errUsage } from '../errors.js';
@@ -331,6 +332,7 @@ export function flowsCmd(wrap) {
331
332
  }
332
333
  const result = await createFlowFromManifest(app.sdk, app.getEffectiveInstance(), manifest, {
333
334
  readUpdateSet: () => readCurrentUpdateSet(app.sdk),
335
+ ensureCapture: intended => alignUpdateSetCapture(app.sdk, intended),
334
336
  });
335
337
  app.ok({ ...result, trigger_guidance: triggerGuidance(result.trigger) }, {
336
338
  summary: `Created draft flow "${result.flow.name}" (${result.flow.id}) with trigger ${result.trigger?.type ?? 'unknown'} (${result.trigger?.id ?? 'no trigger id'}) without activation`,
@@ -368,6 +370,7 @@ export function flowsCmd(wrap) {
368
370
  const result = await updateFlowFromManifest(app.sdk, app.getEffectiveInstance(), argv.identifier, manifest, {
369
371
  preview: argv.preview,
370
372
  readUpdateSet: () => readCurrentUpdateSet(app.sdk),
373
+ ensureCapture: intended => alignUpdateSetCapture(app.sdk, intended),
371
374
  });
372
375
  const diff = result.changes.map(change => `${change.component}${change.order ? ` ${change.order}` : ''}.${change.input}: ${JSON.stringify(change.before)} -> ${JSON.stringify(change.after)}`).join('\n');
373
376
  const state = `${result.flow.status}${result.flow.active ? ', active' : ''}`;
package/src/context.js CHANGED
@@ -98,3 +98,86 @@ export async function setCurrentApplication(sdk, _userSysID, scopeSysID) {
98
98
  export async function setCurrentUpdateSet(sdk, _userSysID, updateSetSysID) {
99
99
  await selectContext(sdk, 'updateset', { sysId: updateSetSysID }, updateSetSysID);
100
100
  }
101
+
102
+ /**
103
+ * Read the update set this authenticated session will actually capture into.
104
+ *
105
+ * `sys_user_preference:user=<user>^name=sys_update_set` is the persisted
106
+ * choice; this endpoint reports the session's effective picker selection. They
107
+ * are different sources and can disagree in a freshly-warmed session, so the
108
+ * preference alone must not be treated as the provider's capture context.
109
+ */
110
+ export async function readEffectiveUpdateSet(sdk) {
111
+ const endpoint = `${sdk.baseURL}/api/now/ui/concoursepicker/updateset`;
112
+ const response = await sdk.request(endpoint, { method: 'GET', readOnly: true });
113
+ const current = response?.result?.current;
114
+ if (!current || typeof current !== 'object') {
115
+ throw new Error('Invalid update-set picker response: expected result.current.');
116
+ }
117
+ const sysId = typeof current.sysId === 'string' ? current.sysId : '';
118
+ return {
119
+ sys_id: sysId,
120
+ name: typeof current.name === 'string' ? current.name : '',
121
+ label: current.displayValue || current.name || sysId,
122
+ };
123
+ }
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
+ */
140
+ 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';
181
+ }
182
+ return report;
183
+ }
@@ -794,13 +794,23 @@ function unavailableCapture(reason) {
794
794
  return { available: false, status: 'unavailable', reason };
795
795
  }
796
796
 
797
+ // Reporting reads the persisted preference, but the provider captures into the
798
+ // session's effective selection. Reconcile the two before the first content
799
+ // write and carry the result into the payload so a save can never claim a set
800
+ // it did not use.
801
+ async function resolveCaptureContext(options, readUpdateSet) {
802
+ if (!options.ensureCapture) return undefined;
803
+ const intended = await readUpdateSet();
804
+ return options.ensureCapture(intended);
805
+ }
806
+
797
807
  async function addPostMutationCapture(snapshot, sdk, readUpdateSet, flowId) {
798
808
  const updateSet = await readUpdateSet();
799
809
  snapshot.after = updateSet;
800
810
  snapshot.capture_after = await readUpdateSetCapture(sdk, updateSet, flowId);
801
811
  }
802
812
 
803
- export async function readUpdateSetCapture(sdk, updateSet, flowId) {
813
+ export async function readUpdateSetCapture(sdk, updateSet, flowId, { locateElsewhere = false } = {}) {
804
814
  const updateSetId = idValue(updateSet?.sys_id || updateSet?.sysId);
805
815
  if (!updateSetId) return unavailableCapture('current update set has no selected sys_id (likely Default)');
806
816
  const rows = await sdk.list('sys_update_xml', new URLSearchParams({
@@ -810,13 +820,67 @@ export async function readUpdateSetCapture(sdk, updateSet, flowId) {
810
820
  sysparm_fields: 'sys_id,name,type,action,target_name,update_set,payload,xml',
811
821
  }));
812
822
  const matches = rows.filter(row => JSON.stringify(row).includes(flowId));
813
- return {
823
+ const capture = {
814
824
  available: true,
815
825
  status: matches.length ? 'captured' : 'missing',
816
826
  update_set: updateSet,
817
827
  count: matches.length,
818
828
  records: matches,
819
829
  };
830
+ if (!matches.length && locateElsewhere) {
831
+ capture.elsewhere = await findCaptureElsewhere(sdk, flowId, updateSetId);
832
+ const destinations = capture.elsewhere.update_sets || [];
833
+ capture.diagnosis = destinations.length
834
+ ? `Content was saved, but no update XML for this flow is in ${updateSet?.name || updateSetId}. `
835
+ + `${destinations.reduce((sum, set) => sum + set.count, 0)} matching record(s) are in `
836
+ + `${destinations.map(set => `${set.name || set.sys_id} (${set.sys_id})`).join(', ')}. `
837
+ + 'These may be historical captures and do not prove this save was routed elsewhere. '
838
+ + 'Capture can be asynchronous; re-check the intended set before completing or exporting it.'
839
+ : `Content was saved, but no update XML naming this flow was found in ${updateSet?.name || updateSetId} `
840
+ + `or by nameLIKE${flowId}. Capture may be absent or recorded under a different name; `
841
+ + 'inspect sys_update_xml for the flow sys_id before completing the set.';
842
+ }
843
+ return capture;
844
+ }
845
+
846
+ // The flow's own update XML is named `<table>_<sys_id>`, so the flow sys_id is
847
+ // searchable across every set. This locates candidate captures without moving
848
+ // records; a historical match alone cannot establish where this save landed.
849
+ async function findCaptureElsewhere(sdk, flowId, intendedSetId) {
850
+ const id = idValue(flowId);
851
+ // Only a single opaque token may reach the encoded query; never allow query
852
+ // operators such as ^ or = to be injected through a caller-supplied id.
853
+ if (!/^[0-9a-zA-Z_-]{1,64}$/.test(id)) {
854
+ return { checked: false, reason: 'flow identifier is not a safe exact token', update_sets: [] };
855
+ }
856
+ const params = new URLSearchParams({
857
+ sysparm_query: `nameLIKE${id}`,
858
+ sysparm_limit: '50',
859
+ sysparm_display_value: 'all',
860
+ sysparm_fields: 'sys_id,name,type,action,target_name,update_set,sys_created_on',
861
+ });
862
+ let rows;
863
+ try {
864
+ rows = await sdk.list('sys_update_xml', params);
865
+ } catch (error) {
866
+ return { checked: true, available: false, reason: error.message, update_sets: [] };
867
+ }
868
+ const bySet = new Map();
869
+ for (const row of rows) {
870
+ const raw = row.update_set;
871
+ const setId = idValue(raw);
872
+ if (!setId || setId === intendedSetId) continue;
873
+ const entry = bySet.get(setId) || { sys_id: setId, name: raw?.display_value || '', count: 0, records: [] };
874
+ entry.count += 1;
875
+ entry.records.push({
876
+ sys_id: idValue(row.sys_id),
877
+ name: row.name?.display_value || row.name || '',
878
+ action: row.action?.display_value || row.action || '',
879
+ sys_created_on: row.sys_created_on?.display_value || row.sys_created_on || '',
880
+ });
881
+ bySet.set(setId, entry);
882
+ }
883
+ return { checked: true, available: true, query: `nameLIKE${id}`, update_sets: [...bySet.values()] };
820
884
  }
821
885
 
822
886
  export async function createFlowFromManifest(sdk, instance, inputManifest, options = {}) {
@@ -825,6 +889,12 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
825
889
  const idFactory = options.idFactory || (() => randomUUID());
826
890
  const readUpdateSet = options.readUpdateSet || (async () => null);
827
891
  const snapshots = [];
892
+ let captureContext;
893
+ try {
894
+ captureContext = await resolveCaptureContext(options, readUpdateSet);
895
+ } catch (error) {
896
+ throw new Error(`Flow creation refused before any content write: capture context could not be established. ${error.message}`, { cause: error });
897
+ }
828
898
 
829
899
  let parentResponse;
830
900
  try {
@@ -885,7 +955,7 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
885
955
  instance, flowId, scope, type: 'Autosave', annotation: 'JSN flow create',
886
956
  }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
887
957
  const selectedUpdateSet = await readUpdateSet();
888
- const updateSetCapture = await readUpdateSetCapture(sdk, selectedUpdateSet, flowId);
958
+ const updateSetCapture = await readUpdateSetCapture(sdk, selectedUpdateSet, flowId, { locateElsewhere: true });
889
959
 
890
960
  const triggerReadback = findArray(processflow, 'triggerInstances')[0] || {};
891
961
  return {
@@ -895,6 +965,7 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
895
965
  processflow,
896
966
  definition_readback: { available: true, status: 'read_back', flow_id: flowId },
897
967
  version,
968
+ ...(captureContext ? { capture_context: captureContext } : {}),
898
969
  update_set_capture: updateSetCapture,
899
970
  update_set_mutations: snapshots,
900
971
  lifecycle: { published: false, supported: ['draft', 'autosave'], deferred: ['publish/activation', 'Flow Logic', 'subflows', 'flow variables', 'error handling'] },
@@ -984,6 +1055,12 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
984
1055
  deferred: DEFERRED_LIFECYCLE,
985
1056
  },
986
1057
  };
1058
+ let captureContext;
1059
+ try {
1060
+ captureContext = await resolveCaptureContext(options, readUpdateSet);
1061
+ } catch (error) {
1062
+ throw new Error(`Flow ${flowId} update refused before any content write: capture context could not be established. ${error.message}`, { cause: error });
1063
+ }
987
1064
  // Baseline the published runtime after the definition read (a legacy read can
988
1065
  // materialize a version row) and before the edit session exists.
989
1066
  const runtimeBefore = published ? await readFlowRuntime(sdk, instance, flowId, { scope, snapshotId }) : null;
@@ -1082,7 +1159,7 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1082
1159
  completedStage = 'runtime_verified';
1083
1160
  }
1084
1161
  const selectedUpdateSet = await readUpdateSet();
1085
- const updateSetCapture = await readUpdateSetCapture(sdk, selectedUpdateSet, flowId);
1162
+ const updateSetCapture = await readUpdateSetCapture(sdk, selectedUpdateSet, flowId, { locateElsewhere: true });
1086
1163
  // Report what the record says after the save, not the pre-edit label: a
1087
1164
  // published flow that now has a draft working copy must not look published
1088
1165
  // in the result. `active` and the snapshot pointers are the runtime gates.
@@ -1099,6 +1176,7 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1099
1176
  definition_readback: { available: true, status: 'read_back', flow_id: flowId },
1100
1177
  version,
1101
1178
  ...(runtime ? { runtime_preservation: runtime } : {}),
1179
+ ...(captureContext ? { capture_context: captureContext } : {}),
1102
1180
  update_set_capture: updateSetCapture,
1103
1181
  update_set_mutations: snapshots,
1104
1182
  lifecycle: {