@jacebenson/jsn 5.3.0 → 5.4.0-dev.141.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",
3
+ "version": "5.4.0-dev.141.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": {
package/src/app.js CHANGED
@@ -59,6 +59,7 @@ export class App {
59
59
  username: session?.username, authMethod: session?.profile?.auth_method,
60
60
  }), {
61
61
  domain: session?.domain || '',
62
+ username: session?.username || '',
62
63
  recovery: createAuthRecovery({ app: this, session }),
63
64
  onMutation: event => this.recordMutation(instance, session?.profileName, event),
64
65
  });
@@ -69,6 +70,7 @@ export class App {
69
70
  const profile = options.profile || {};
70
71
  return new SDKClient(instance, this.auth.createProfileProvider(instance, options), {
71
72
  domain: options.domain ?? profile.domain ?? '',
73
+ username: options.username || '',
72
74
  onMutation: event => this.recordMutation(instance, options.profileName || null, event),
73
75
  });
74
76
  }
@@ -14,20 +14,34 @@ export function createAuthRecovery({ app, session, argv = () => app._authArgv ||
14
14
  const { instance, profileName, username, profile } = session;
15
15
  const target = profileName ? `--profile ${quoteShellArg(profileName)}` : quoteShellArg(instance);
16
16
  const label = profileName ? `profile ${quoteShellArg(profileName)}` : 'the active profile';
17
- function failure(method = profile?.auth_method) {
17
+ // A 401 is definitive. A login page/redirect is a session rejection too, but
18
+ // only the SDK may decide whether the rejected operation is safe to replay.
19
+ const rejectedKinds = new Set(['http_401', 'login_redirect', 'login_page']);
20
+ function failure(method = profile?.auth_method, kind = 'http_401') {
18
21
  const error = errAPI(401, '');
19
22
  const login = `jsn auth login ${target}`;
20
- error.message = `Authentication rejected for ${label} (HTTP 401).`;
23
+ const expired = kind !== 'http_401';
24
+ error.message = method === 'gck'
25
+ ? `The saved browser session for ${label} was rejected${expired ? ' (a login page was returned)' : ' (HTTP 401)'} and cannot be renewed by JSN. Recapture it to continue.`
26
+ : expired
27
+ ? `The saved session for ${label} expired (a login page was returned instead of the response).`
28
+ : `Authentication rejected for ${label} (HTTP 401).`;
21
29
  error.profile = profileName || null;
22
30
  error.recovery = method === 'basic'
23
31
  ? `jsn auth login --basic ${quoteShellArg(instance)}${profileName ? ` --profile ${quoteShellArg(profileName)}` : ''}`
24
32
  : method === 'gck' ? `jsn auth refresh ${target} --browser`
25
33
  : method === 'oauth' ? `jsn auth refresh ${target}` : login;
26
- error.hint = method === 'basic'
27
- ? `Set SN_USERNAME/SN_PASSWORD to the correct credentials, then run: ${error.recovery}`
28
- : method === 'oauth'
29
- ? `Run interactively: ${error.recovery}. If refresh fails, run: ${login}`
30
- : `Run: ${error.recovery}`;
34
+ if (method === 'gck') {
35
+ // Captured browser cookies are not renewable; only a new capture helps.
36
+ error.recapture_required = true;
37
+ error.hint = `Recapture the browser session, then re-run: ${error.recovery}`;
38
+ } else if (method === 'basic') {
39
+ error.hint = `Set SN_USERNAME/SN_PASSWORD to the correct credentials, then run: ${error.recovery}`;
40
+ } else if (method === 'oauth') {
41
+ error.hint = `Run interactively: ${error.recovery}. If refresh fails, run: ${login}`;
42
+ } else {
43
+ error.hint = `Run: ${error.recovery}`;
44
+ }
31
45
  return error;
32
46
  }
33
47
  // Keep the settled promise too: this provider gets only one recovery attempt.
@@ -43,12 +57,13 @@ export function createAuthRecovery({ app, session, argv = () => app._authArgv ||
43
57
  error.hint = `Run: ${error.recovery}`;
44
58
  return error;
45
59
  },
46
- async recover({ status }) {
47
- if (status !== 401) return false;
48
- return recoveryAttempt ??= recoverOnce();
60
+ async recover({ status, kind } = {}) {
61
+ const reason = kind ?? (status === 401 ? 'http_401' : null);
62
+ if (!rejectedKinds.has(reason)) return false;
63
+ return recoveryAttempt ??= recoverOnce(reason);
49
64
  },
50
65
  };
51
- async function recoverOnce() {
66
+ async function recoverOnce(kind) {
52
67
  let creds;
53
68
  try {
54
69
  creds = await app.auth.getCredentialsFor(instance, username, {
@@ -56,7 +71,7 @@ export function createAuthRecovery({ app, session, argv = () => app._authArgv ||
56
71
  });
57
72
  } catch { throw provider.error; }
58
73
  const method = profile?.auth_method || creds.auth_method;
59
- provider.error = failure(method);
74
+ provider.error = failure(method, kind);
60
75
  if (method === 'oauth' && creds.refresh_token) {
61
76
  try {
62
77
  await app.auth.refreshToken(instance, creds, username ?? null);
package/src/cli.js CHANGED
@@ -65,6 +65,7 @@ import {
65
65
  } from './commands/_simple.js';
66
66
  import { decisiontablesCmd } from './commands/decisiontables.js';
67
67
  import { flowsCmd } from './commands/flows.js';
68
+ import { workflowsCmd } from './commands/workflows.js';
68
69
  import { formsCmd } from './commands/forms.js';
69
70
  import { listsCmd } from './commands/lists.js';
70
71
  import { updateSetsCmd } from './commands/updatesets.js';
@@ -359,6 +360,7 @@ export function buildCLI() {
359
360
  .command(casesCmd(wrap))
360
361
  // AUTOMATION — Async
361
362
  .command(flowsCmd(wrap))
363
+ .command(workflowsCmd(wrap))
362
364
  .command(actionsCmd(wrap))
363
365
  .command(scriptactionsCmd(wrap))
364
366
  .command(scheduledjobsCmd(wrap))
@@ -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' : ''}`;
@@ -0,0 +1,123 @@
1
+ import { declareCapabilities } from '../capabilities.js';
2
+ import { errUsage } from '../errors.js';
3
+ import {
4
+ inspectWorkflow,
5
+ listWorkflows,
6
+ formatWorkflowList,
7
+ formatWorkflowOutline,
8
+ } from '../workflow-inspection.js';
9
+
10
+ // Legacy Workflow Editor inspection is read-only by construction: every
11
+ // request in workflow-inspection.js is a Table API GET. Declaring no mutation
12
+ // subcommands keeps the mutation guard and read-only profiles aligned with
13
+ // what the command can actually do.
14
+ declareCapabilities('workflows', { mutationSubcommands: [] });
15
+
16
+ // A curated human view belongs to the command; keeping it non-enumerable
17
+ // leaves the JSON envelope free of presentation text.
18
+ function defineFormatted(data, formatted) {
19
+ Object.defineProperty(data, '_formatted', { value: formatted, enumerable: false, configurable: true });
20
+ }
21
+
22
+ export function parseWorkflowStep(value) {
23
+ if (value === undefined) return undefined;
24
+ if (!/^[1-9]\d*$/.test(String(value)) || !Number.isSafeInteger(Number(value))) {
25
+ throw errUsage('--step must be a positive integer.');
26
+ }
27
+ return Number(value);
28
+ }
29
+
30
+ export function selectWorkflowStep(data, number) {
31
+ if (number === undefined) return data;
32
+ const step = data.steps.find(step => step.number === number);
33
+ if (!step) throw errUsage(`Step ${number} is out of range: ${data.steps.length} steps; valid range ${data.steps.length ? `1–${data.steps.length}` : 'none (0 steps)'}.`);
34
+ return {
35
+ ...data,
36
+ activities: data.activities.filter(activity => activity.sys_id === step.sys_id),
37
+ steps: [step],
38
+ transitions: data.transitions.filter(edge => edge.from_id === step.sys_id),
39
+ transitions_by_activity: data.transitions_by_activity.filter(group => group.sys_id === step.sys_id),
40
+ };
41
+ }
42
+
43
+ export function workflowsCmd(wrap) {
44
+ return {
45
+ command: 'workflows [subcommand]',
46
+ aliases: ['workflow'],
47
+ describe: 'Inspect legacy Workflow Editor workflows (read-only)',
48
+ builder: (yargs) => yargs
49
+ .command({
50
+ command: 'list',
51
+ aliases: ['ls'],
52
+ describe: 'List legacy workflows with published and checked-out versions',
53
+ builder: (y) => y
54
+ .option('name', { type: 'string', describe: 'Workflow name contains this text' })
55
+ .option('table', { type: 'string', describe: 'Exact target table name (e.g. incident)' })
56
+ .option('query', { type: 'string', describe: 'Additional encoded query (e.g. "nameLIKEapproval")' })
57
+ .option('limit', { alias: 'l', type: 'number', default: 20, describe: 'Page size (1–100)' })
58
+ .option('offset', { type: 'number', default: 0, describe: 'Starting result offset' }),
59
+ handler: wrap(async (argv, app) => {
60
+ app.requireInstance();
61
+ const data = await listWorkflows(app.sdk, {
62
+ name: argv.name || '',
63
+ table: argv.table || '',
64
+ query: argv.query || '',
65
+ limit: argv.limit,
66
+ offset: argv.offset,
67
+ });
68
+ const next = data.pagination.has_more
69
+ ? `jsn workflows list --limit ${data.pagination.limit} --offset ${data.pagination.offset + data.pagination.limit}`
70
+ : '';
71
+ const breadcrumbs = data.records.slice(0, 5).map(record => ({
72
+ action: 'show',
73
+ cmd: `jsn workflows show ${record.sys_id}`,
74
+ description: `Inspect ${record.name}`,
75
+ }));
76
+ if (next) breadcrumbs.push({ action: 'next', cmd: next, description: 'Next page of legacy workflows' });
77
+ defineFormatted(data, formatWorkflowList(data));
78
+ app.ok(data, {
79
+ summary: `${data.count} legacy workflow(s)${data.pagination.has_more ? ', more available' : ''}`,
80
+ breadcrumbs,
81
+ });
82
+ }),
83
+ })
84
+ .command({
85
+ command: 'show <identifier>',
86
+ aliases: ['get'],
87
+ describe: 'Inspect one legacy workflow: versions, activities, transitions, conditions and configuration',
88
+ builder: (y) => y
89
+ .positional('identifier', { type: 'string', describe: 'Workflow name, workflow sys_id, or version sys_id' })
90
+ .option('version', { type: 'string', describe: 'Specific wf_workflow_version sys_id (default: published, else newest)' })
91
+ .option('config', { type: 'boolean', describe: 'Show activity configuration and scripts under each step' })
92
+ .option('step', { type: 'string', describe: 'Inspect one positive step number with full configuration' })
93
+ .option('limit', { alias: 'l', type: 'number', default: 200, describe: 'Maximum activities to read (1–1000)' }),
94
+ handler: wrap(async (argv, app) => {
95
+ app.requireInstance();
96
+ if (typeof argv.identifier !== 'string' || !argv.identifier.trim()) {
97
+ throw errUsage('Provide a legacy workflow name or sys_id.');
98
+ }
99
+ const step = parseWorkflowStep(argv.step);
100
+ const data = await inspectWorkflow(app.sdk, {
101
+ identifier: argv.identifier,
102
+ versionId: argv.version || '',
103
+ // Keep the existing JSON/read contract; --config controls presentation.
104
+ includeConfiguration: step !== undefined || argv.config !== false,
105
+ limit: argv.limit,
106
+ });
107
+ const selected = selectWorkflowStep(data, step);
108
+ const formatted = formatWorkflowOutline(data, { includeConfiguration: argv.config === true, step });
109
+ defineFormatted(selected, formatted);
110
+ const versionLabel = data.version
111
+ ? `${data.version.name} (${data.selection.reason})`
112
+ : 'no readable version';
113
+ app.ok(selected, {
114
+ summary: `Legacy workflow: ${data.workflow.name} — ${versionLabel}, ${selected.activities.length} activity(ies)${data.coverage.complete ? '' : ', partial coverage'}`,
115
+ breadcrumbs: [
116
+ { action: 'list', cmd: 'jsn workflows list', description: 'Back to legacy workflows' },
117
+ ...(data.version ? [{ action: 'json', cmd: `jsn workflows show ${JSON.stringify(data.workflow.name)} --json`, description: 'Structured definition with IDs' }] : []),
118
+ ],
119
+ });
120
+ }),
121
+ }),
122
+ };
123
+ }
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: {
package/src/output.js CHANGED
@@ -167,6 +167,9 @@ export class OutputWriter {
167
167
  resp.recovery = e.recovery;
168
168
  if (Object.hasOwn(e, 'profile')) resp.profile = e.profile;
169
169
  }
170
+ // Captured browser sessions cannot be renewed, so the machine envelope
171
+ // must carry the same recapture marker the in-process error exposes.
172
+ if (e.recapture_required) resp.recapture_required = true;
170
173
  switch (format) {
171
174
  case FormatJSON:
172
175
  case FormatQuiet: