@jacebenson/jsn 5.5.5 → 5.5.6-dev.200.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/README.md CHANGED
@@ -1,329 +1,51 @@
1
1
  # JSN: ServiceNow CLI
2
2
 
3
- A command-line interface for ServiceNow. Read and update records, manage flows, inspect platform data, and automate routine work from your terminal or AI agent.
3
+ Read ServiceNow records, inspect platform metadata, search documentation, and make explicit changes from your terminal or AI agent.
4
4
 
5
- ## Install
5
+ [npm](https://www.npmjs.com/package/@jacebenson/jsn) · [GitHub](https://github.com/jacebenson/jsn) · [JSN docs](https://jsn.jace.pro/docs/install/)
6
6
 
7
- Supports the current Node.js LTS release. Supports macOS, Linux, and Windows.
7
+ ## Install and connect
8
8
 
9
- ```bash
9
+ Use the current [Node.js LTS release](https://nodejs.org/en/about/previous-releases) and npm on macOS, Linux, or Windows. Older Node.js release lines are not supported.
10
+
11
+ ```sh
10
12
  npm install -g @jacebenson/jsn
11
13
  jsn setup
12
14
  ```
13
15
 
14
- See the [setup guide](https://github.com/jacebenson/jsn/blob/main/docs/docs-setup.md) to connect an instance safely.
15
-
16
- ### Dev channel
17
-
18
- For the newest changes from `main`, including changes that may be unstable:
19
-
20
- ```bash
21
- npm install -g @jacebenson/jsn@dev
22
- ```
23
-
24
- Dev builds check the dev channel for updates during normal use, at most once
25
- per day. Run `jsn version --check` to check immediately. To install the newest
26
- dev build, run `jsn upgrade` (alias: `jsn update`). It preserves your installed
27
- channel and skips installation when no newer version is available. Use
28
- `--dry-run` to print the npm command without network access or installation,
29
- `--force` to reinstall, or `--channel dev|latest` to switch channels explicitly.
30
- For example, `jsn upgrade --channel latest` returns to stable. npm installation
31
- permissions still apply; the command does not elevate privileges automatically.
32
-
33
- Pushes to `main` promote the commit to `dev` and publish a tested prerelease
34
- under npm's `dev` tag. Versions include the workflow run number and attempt
35
- (for example, `4.3.9-dev.123.1`); they do not move npm's stable `latest` tag.
36
- The npm trusted publisher for `publish-dev.yml` must authorize the repository's
37
- `dev` GitHub environment, alongside the production publishing configuration.
38
-
39
- ### Knowledge search
16
+ Setup connects a named profile to your instance. Its default preset allows writes, so enable read-only mode before exploring. See [setup and authentication](https://jsn.jace.pro/docs/setup/).
40
17
 
41
- Use `jsn knowledge search "VPN setup" --profile work` (alias `kb`) to search
42
- accessible articles, then `jsn knowledge show KB0000010 --profile work` to read
43
- one. Search supports bounded `--limit`/`--offset`, knowledge-base sys_ids with
44
- `--kb`, and `--language`. JSON preserves native HTML; human output uses Markdown.
45
- Hints preserve an explicitly selected profile/instance. The Knowledge API plugin
46
- (`sn_km_api`) must be available; access is evaluated by that API, with no fallback
47
- to direct table reads. Reads do not request view-count updates. See the
48
- [Knowledge API reference](https://www.servicenow.com/docs/r/yokohama/api-reference/rest-apis/knowledge-api.html).
18
+ For unreleased changes, use `npm install -g @jacebenson/jsn@dev`; see [channels and updates](https://github.com/jacebenson/jsn/blob/main/docs/releases.md).
49
19
 
50
- ### Instance Scan
20
+ ## Read and discover
51
21
 
52
- `jsn scan` manages checks and suites and runs scans against an explicit target.
53
- Use `jsn scan --help` and each subcommand's `--help` to discover the options.
54
-
55
- ```bash
56
- jsn scan checks list --profile dev
57
- jsn scan checks create --type table --data-file check.json --profile dev
58
- jsn scan checks activate <check-id> --profile dev
59
- jsn scan suites add-check <suite-id> --check <check-id> --profile dev
60
- jsn scan run --update-set "My change" --suite "My suite" --wait --profile dev
61
- jsn scan run --table sys_script_include --record <record-id> --profile dev
62
- jsn scan results <execution-id> --profile dev
22
+ ```sh
23
+ jsn records list --table incident --query "active=true" --limit 5 --json
24
+ jsn discover --table incident
25
+ jsn docs "GlideRecord" --limit 5
26
+ jsn --help
63
27
  ```
64
28
 
65
- Check types are `table`, `column`, `linter`, and `script`. Definitions are created
66
- inactive unless the payload explicitly sets `active: true`; activation never
67
- starts a scan. Both checks and suites support list/show/create/update/delete and
68
- activate/deactivate. Suites also support add-check/remove-check.
69
-
70
- Runs require an update set, scope, record plus table, or explicit `--full`.
71
- Instance-wide scans may traverse many tables even when a check's script only
72
- examines a few records. Starting and cancelling a scan require confirmation;
73
- use `--force` only after approving that operation. `--wait --timeout 120` bounds
74
- the wait, not the scan's lifetime. A timed-out wait keeps the execution id and
75
- does not cancel or resubmit the scan. Use `status`, `results`, or `cancel` next.
76
-
77
- Update-set scans examine current instance records, not the historical XML
78
- versions. Inactive records may be skipped. Script-only checks do not participate
79
- in record/update-set scans; use an explicitly instance-wide suite run to execute
80
- them. Execution success does not mean zero findings or complete test coverage:
81
- results report recorded check executions, finding counts, unreadable sources,
82
- and truncated lists separately. A result's rerun hint preserves the previous
83
- target combination and requires `--full` again for instance-wide scans.
84
-
85
- Every command returns next-step breadcrumbs in human and JSON output, retaining
86
- an explicitly selected profile or instance. `updatesets show` also offers a scan
87
- hint. Recommendation/generation of new checks is not part of this command;
88
- JSN contains no AI and does not infer missing business requirements.
89
-
90
- ### CMDB search
91
-
92
- `jsn cmdb search "web" --profile work` searches names, FQDNs, IP addresses and
93
- serial numbers on `cmdb_ci`. Use `--class cmdb_ci_server` for an exact class
94
- match (excluding subclasses), and bounded `--limit`/`--offset` pagination.
95
- Search text is literal; encoded-query operators and query scripts are rejected.
96
- Existing `cmdb list --query` remains available for deliberate encoded queries.
97
- Results include show/relationship hints and preserve the selected connection.
29
+ Instance reads use your selected profile; add `--profile <name>` to choose another. Documentation search needs no ServiceNow connection and uses the hosted service by default. Use `jsn <command> --help` for options or `jsn --all-commands --help` for the full reference.
98
30
 
99
- ### Supported versions
31
+ ## Choose output
100
32
 
101
- Only the current release and the two preceding releases in each channel are
102
- supported (three stable releases and three dev builds). For example, with
103
- stable `4.3.11`, versions `4.3.11`, `4.3.10`, and `4.3.9` are supported.
104
- Update to the newest version in your channel before reporting an issue.
33
+ Use the default terminal view for people, `--csv` or `--tsv` for flat rows, and `--json` when scripts need pagination, context, or errors. CSV/TSV do not fetch more pages or preserve both reference IDs and labels. Pagination notices go to stderr only when more results are explicitly known; silence does not prove completeness. JSON retains reference objects only if the command has not already flattened them. See [output details](https://jsn.jace.pro/docs/output/).
105
34
 
106
- Publishing uses npm trusted publishing (OIDC) and advances the channel's dist-tag.
107
- CI/CD does not deprecate older versions or require an `NPM_TOKEN` secret. Older
108
- versions remain available; their availability does not extend the support window.
35
+ ## Work safely
109
36
 
110
- The optional maintenance script `scripts/deprecate-old-versions.mjs` can preview
111
- older versions with `node scripts/deprecate-old-versions.mjs latest` (or `dev`).
112
- Applying deprecations with `--apply` requires npm authentication and
113
- `NODE_AUTH_TOKEN`; it is separate from publishing. The script requires the
114
- checkout's package version to match the channel's current npm tag.
37
+ Use `jsn auth modify <profile> --read-only` to block instance writes. ServiceNow roles and ACLs still decide what you can access. Help and discovery may show a compact command list for the connected account; this is not an access grant or an exhaustive capability check.
115
38
 
116
- ## Try it
117
-
118
- ```bash
119
- jsn incidents list --query "active=true^priority=1"
120
- jsn records list --table incident --limit 10 --json
121
- jsn flows list
122
- ```
123
-
124
- Run `jsn --help` for a concise command overview, or `jsn --all-commands --help` for the complete command and flag reference. See the [CLI guide](https://github.com/jacebenson/jsn/blob/main/docs/cli-guide.md) for authentication, output formats, development, and examples. The [docs site](https://jacebenson.github.io/jsn/) has feature guides.
39
+ Writes are not universally dry-run operations or confirmation prompts. Inspect each command's help, target profile, scope, and update set before changing anything. Use `--force` only for an approved operation. See [safety guidance](https://jsn.jace.pro/docs/safety/).
125
40
 
126
41
  ## AI agents
127
42
 
128
- JSN includes a skill for Claude Code, OpenCode, Hermes, Cursor, Copilot, and other agents. Use `jsn skill install --target all` to install it or `jsn skill show` to inspect it.
129
-
130
- ## Development
131
-
132
- ```bash
133
- cd cli
134
- npm ci
135
- npm test
136
- ```
137
-
138
- ## License
139
-
140
- MIT
141
-
142
-
143
- ### Commands for the connected account
144
-
145
- Login and OAuth refresh check for the current account's `admin` role. Profiles
146
- without that role show a compact command list focused on tickets, generic
147
- records, people/groups, documentation, and connection management. If the role
148
- check is unavailable, the profile also uses compact help; this does not assert
149
- that the account lacks admin. Existing profiles keep full help until renewed.
150
-
151
- This applies to root help, root JSON, `discover`, and root shell completion.
152
- Use `jsn --all-commands --help` or `jsn discover --all-commands --json` to inspect
153
- every registered command. Explicit command paths remain available and ServiceNow
154
- ACLs decide access. Reauthenticate (or refresh OAuth) after roles change.
155
-
156
- ### Ordering catalog items
157
-
158
- Use `jsn catalogitems search "laptop" --profile work`, then
159
- `jsn catalogitems describe <item-sys-id> --profile work` to inspect pricing and
160
- variable definitions through the native Service Catalog API. Create a JSON file
161
- mapping variable names to values, then preview with
162
- `jsn catalogitems order <item-sys-id> --variables-file variables.json --dry-run --profile work`.
163
- Omit `--dry-run` to submit after confirmation. `--quantity` defaults to one;
164
- `--requested-for` accepts a user sys_id subject to instance delegation rules.
165
-
166
- `show` is the one view of an item — `describe` and `inputs` are aliases for it.
167
- It reads the item twice and answers once: the Table API gives the definition
168
- (`sc_cat_item` plus `item_option_new`), and
169
- `/api/sn_sc/servicecatalog/items/{id}` gives what this account can actually
170
- request. The catalog API wins when it answers; the definition list keeps the
171
- command working when it does not, with `variables_source` naming which one
172
- answered and `variables_api_error` carrying the reason for the fallback.
173
-
174
- Questions come back as `{name, label, type, friendly_type, mandatory,
175
- instance_supplied}` with `required_variables` and `instance_supplied_variables`,
176
- so a script can build the payload without guessing names or types. Layout
177
- entries that draw the form but hold no value — containers, labels, HTML and rich
178
- text blocks, breaks and UI macros — are not reported as questions; only their
179
- container children are walked. `required_variables` excludes the
180
- instance-supplied ones: "Requested for" (type 31) is mandatory in the API
181
- payload, but the instance fills it from the session and `--requested-for`
182
- overrides it. `order` refuses locally when a required question is missing and an
183
- unknown variable name is reported as `unknown_variable_names` without blocking.
184
- The server remains the authority.
185
-
186
- What the API returns is what a caller can send: questions withheld by a catalog UI
187
- policy are absent, and a policy-applied mandatory flag is not visible here, so the
188
- server still decides at submission. Record producers and order guides expose their
189
- variables but are not orderable through `order`.
190
-
191
- Orders use `order_now`, preserving catalog fulfillment rather than inserting an
192
- RITM directly. `order_now` returns the request (REQ); JSN then reads the request's
193
- items and reports `request_id`, `request_number` and `requested_items`
194
- (`sys_id`/`number`). If that follow-up read is denied, the order is still
195
- reported as placed with `requested_items_readable: false` — inspect requests
196
- rather than resubmitting. The command handles standard catalog items; record
197
- producers and order guides require separate workflows. Server rules validate
198
- dynamic variables at submission; a preview does not validate those rules.
199
- Preview output lists variable names and required names, not entered values.
200
- Previews only read, so they work on a read-only profile; submitting requires a
201
- write-enabled profile and no development update set. Confirmation follows the
202
- existing profile policy; automation can supply `--force` only for an approved
203
- order. Timeout or incomplete response is an uncertain outcome: inspect requests
204
- before retrying. JSN does not automatically submit a second order.
205
- `create/list/show` retain their definition-management behavior.
206
-
207
- See the [Service Catalog API reference](https://www.servicenow.com/docs/r/api-reference/rest-apis/c_ServiceCatalogAPI.html).
208
-
209
- ### Viewing service and HR cases
210
-
211
- `jsn cases list`, `jsn cases show <number>` and `jsn cases search "<text>"` read
212
- cases through the normal authenticated Table API. Which case table is meant
213
- depends on the installed application, so JSN probes the known case tables in
214
- order — `sn_customerservice_case` (Customer Service Management), then
215
- `sn_hr_core_case` (HR Service Delivery) — and uses the first one the profile can
216
- read. `jsn cases tables` reports each candidate without claiming access, and
217
- `--table <name>` names any other case table.
218
-
219
- ```bash
220
- jsn cases list --json
221
- jsn cases list --hr --query "active=true"
222
- jsn cases search "printer" --table sn_customerservice_case
223
- jsn cases show CS0001001
224
- ```
225
-
226
- Visibility is not widened by JSN: application roles and ACLs decide which
227
- records are returned, and a denied table reports `forbidden` (HTTP 403) rather
228
- than an empty list. An instance without a case application reports which tables
229
- were unavailable instead of pretending there are no cases, and naming such a
230
- table with `--table` fails the same way (`Reading <table> failed (HTTP 400)`,
231
- exit 2) instead of printing an empty list. To scope a list to the connected
232
- account, add a query term — field names differ per application, for example
233
- `--query "opened_by=javascript:gs.getUserID()"`. These commands only read; case
234
- work that changes state stays in the application UI or `jsn records update`.
235
-
236
- HR cases are a thin addition over this generic path: `--hr` selects
237
- `sn_hr_core_case`. Employee self-service visibility depends on the HR roles and
238
- ACLs of the connected account — an administrator profile does not represent an
239
- employee's view. HR case tasks, relations and the employee portal's widgets are
240
- not exposed yet.
241
-
242
- ## Domain configuration and browser sessions
243
-
244
- `jsn domains current` reports the selected profile's configured `X-Now-Domain`
245
- header. `domains set <name-or-id>` and `domains set clear` configure that header
246
- locally. Header effectiveness depends on the instance; clearing it does not
247
- reset the actual server session domain.
248
-
249
- With saved browser-session (`gck`) credentials, use these explicit commands:
250
-
251
- ```bash
252
- jsn domains session-current --profile example --json
253
- jsn domains session-list --profile example --search '*Internal' --limit 20 --offset 0 --json
254
- jsn domains session-reset --profile example --json
255
- jsn domains session-list --profile example --json
256
- jsn domains session-set <domain-sys-id> --profile example --json
257
- ```
258
-
259
- `session-list` returns one picker-visible page (`items`, `offset`, `limit`,
260
- `next_offset`). Search matches a name prefix, or a substring with a leading `*`.
261
- Visibility depends on the actual session domain. For cross-branch selection,
262
- explicitly reset to global, then list and select a domain from that result.
263
- Neither listing nor selecting silently resets the session. `session-current`
264
- reports both `configured_domain` and `session_domain`.
265
-
266
- **Session reset and selection may affect a browser sharing these credentials.**
267
- Both commands verify the resulting domain with a separate readback. They leave
268
- profile configuration unchanged and omit the configured domain header on picker
269
- requests. Save the original domain ID from `session-current` if you intend to
270
- restore it afterward. A failed readback can leave the session changed; inspect
271
- `session-current` before retrying. These commands do not call `touch-session`.
272
- Other authentication methods retain the existing profile configuration flow.
273
-
274
- ## Documentation search
275
-
276
- ```bash
277
- jsn docs "GlideRecord" --limit 5
278
- jsn docs --path "api-reference/c_GlideRecordClientSideAPI.md"
279
- ```
280
-
281
- No ServiceNow connection is required. Hosted docs at `https://jsn.jace.pro` are
282
- the default and download no database. `jsn setup` asks once for defaults for new
283
- connections and whether to use hosted documentation. Decline hosted docs to let
284
- JSN start a local server, or decline that too and enter your own service base URL.
285
- Later changes live under **Defaults and documentation** in setup. Existing connections
286
- keep their saved settings.
287
-
288
- Local mode downloads the public documentation on first use and checks for updates
289
- daily while running. The server starts again automatically when needed. A first
290
- search can report that the index is still being prepared; later updates preserve
291
- the last working index if offline. Local storage lives under
292
- `~/.jsn/docs/docs.db` for the default family. Other families use
293
- `~/.jsn/docs/releases/NAME/docs.db`. `JSN_DATA_HOME` overrides the parent directory.
294
- Existing default-family installs keep their original index path.
295
-
296
- To host the same service yourself, run `jsn docs --serve --host 0.0.0.0 --port 3000`.
297
- It manages its own index; expose it through your normal HTTPS proxy. The hosted
298
- website and this server share one search engine. `JSN_DOCS_URL` temporarily
299
- overrides the saved choice without starting a local server.
300
-
301
- Choose a family with `jsn docs "GlideRecord" --release brazil`. The same option
302
- applies to `--path`, `docs show <ID>`, `docs status`, `docs sync`, `docs install`
303
- and `--serve`. Resolution is `--release` first, then the optional `docs.release`
304
- preference, then `australia`. Release names contain 1–40 lowercase letters,
305
- digits or dashes. The service decides which families exist.
306
-
307
- Documentation preferences are saved in the global profile config at
308
- `$XDG_CONFIG_HOME/servicenow/config.json`, normally
309
- `~/.config/servicenow/config.json`. Alongside `docs.source` and `docs.url`, set
310
- `docs.release` without changing the service URL:
311
-
312
- ```json
313
- { "docs": { "source": "hosted", "url": "https://jsn.jace.pro", "release": "brazil" } }
314
- ```
43
+ Inspect the bundled skill with `jsn skill show`, then use `jsn skill install` to select your agent or `jsn skill install --target hermes` for Hermes. Reinstall after upgrading JSN; reinstalling replaces recorded copies, including local edits. See [agent installation](https://jsn.jace.pro/docs/agents/).
315
44
 
316
- `jsn docs releases` lists installed families, revisions, document counts, index
317
- paths and the default marker without contacting the network. To install an
318
- optional local index, use `jsn docs install --source snapshot --release brazil`,
319
- or `jsn docs sync --release brazil --no-embed`. Sync downloads the named Git
320
- branch; `--no-ingest` downloads only the source. Snapshot installs use
321
- `/docs-index/releases/NAME/manifest.json` and verify the declared release. Only
322
- the default family can fall back to the old `/docs-index/manifest.json` when
323
- the family manifest returns 404. That legacy manifest may omit `release`.
324
- `jsn docs --serve --release brazil` serves only Brazil and rejects requests
325
- for other families. Search, read and status JSON include the selected `release`.
45
+ ## Go deeper
326
46
 
327
- Exact paths remain stable across revisions. Numeric IDs can be pinned with
328
- `--revision <search-revision>`. Older `docs search`, `docs show` and `docs status`
329
- spellings remain compatible but are omitted from the everyday help menu.
47
+ - [CLI guide and feature workflows](https://jsn.jace.pro/docs/cli-guide/)
48
+ - [Documentation search and local hosting](https://jsn.jace.pro/docs/install/)
49
+ - [Feature library](https://jsn.jace.pro/#features)
50
+ - [Development and contributing](https://github.com/jacebenson/jsn#development-and-contributing)
51
+ - [MIT license](https://github.com/jacebenson/jsn/blob/main/LICENSE)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.5.5",
3
+ "version": "5.5.6-dev.200.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": {
@@ -11,9 +11,7 @@
11
11
  "test": "node scripts/test.mjs",
12
12
  "test:mutation": "stryker run",
13
13
  "lint": "npx eslint src/ bin/ test/",
14
- "start": "node bin/jsn.js",
15
- "docs": "npm --prefix ../docs run build",
16
- "docs:serve": "npm --prefix ../docs run serve"
14
+ "start": "node bin/jsn.js"
17
15
  },
18
16
  "keywords": [
19
17
  "servicenow",
@@ -10,7 +10,7 @@ import { globalConfigDir } from '../config.js';
10
10
  *
11
11
  * Whitelist approach (issue #143 findings #2/#3): first map the `://`
12
12
  * protocol separator to `_` exactly as the Go version's encoding does
13
- * (so existing keyring keys like `https_dev437538.service-now.com` keep
13
+ * (so existing keyring keys like `https_example.service-now.com` keep
14
14
  * matching), then drop everything outside [a-zA-Z0-9._-]. Blacklist
15
15
  * stripping of just `/` and `:` left quotes, `$()`, backticks, `;`,
16
16
  * spaces, and backslashes — which broke out of double-quoted shell args
package/src/auth.js CHANGED
@@ -26,11 +26,11 @@ export { classifyCredentialState } from './auth/credential-state.js';
26
26
 
27
27
  // ─── Basic auth from environment variables ───
28
28
  // SN_USERNAME / SN_PASSWORD — global credentials
29
- // SN_<INSTANCE>_USERNAME / SN_<INSTANCE>_PASSWORD — instance-specific (e.g. SN_DEV328604_USERNAME)
29
+ // SN_<INSTANCE>_USERNAME / SN_<INSTANCE>_PASSWORD — instance-specific (e.g. SN_EXAMPLE_USERNAME)
30
30
 
31
31
  function envVarName(instance) {
32
32
  // Normalize instance URL to an env-var-safe name
33
- // e.g. https://dev328604.service-now.com → DEV328604
33
+ // e.g. https://example.service-now.com → EXAMPLE
34
34
  const host = instance.replace(/https?:\/\//, '').replace(/\/.*$/, '').replace(/\.service-now\.com.*/, '').replace(/[^a-zA-Z0-9]/g, '').toUpperCase();
35
35
  return host;
36
36
  }
@@ -44,7 +44,7 @@ function getBasicAuthFromEnv(instance) {
44
44
  return null;
45
45
  }
46
46
 
47
- // Try instance-specific env vars first (e.g. SN_DEV328604_USERNAME)
47
+ // Try instance-specific env vars first (e.g. SN_EXAMPLE_USERNAME)
48
48
  const host = envVarName(instance);
49
49
  const instanceUser = process.env[`SN_${host}_USERNAME`];
50
50
  const instancePass = process.env[`SN_${host}_PASSWORD`];
@@ -53,7 +53,7 @@ export function declareCapabilities(name, caps) {
53
53
  /**
54
54
  * The collected capability registry: root command name → capabilities.
55
55
  * Includes the implicit declarations for yargs built-ins ('help') and the
56
- * shell plumbing ('completion') which have no factory to declare from.
56
+ * local commands which have no factory to declare from.
57
57
  *
58
58
  * @returns {Map<string, object>}
59
59
  */
@@ -61,14 +61,13 @@ export function collectCapabilities() {
61
61
  const caps = new Map(REGISTRY);
62
62
  if (!caps.has('help')) caps.set('help', { noInstance: true, skipDailyChecks: true });
63
63
  if (!caps.has('version')) caps.set('version', { noInstance: true, skipDailyChecks: true });
64
- if (!caps.has('completion')) caps.set('completion', { noInstance: true, skipDailyChecks: true });
65
64
  return caps;
66
65
  }
67
66
 
68
67
  /**
69
68
  * Derive the set of root command names that run without an instance.
70
69
  * Preserves the legacy skip-list semantics exactly: help, version,
71
- * completion, setup, auth, skill, docs.
70
+ * setup, auth, skill, docs.
72
71
  *
73
72
  * @param {Map<string, object>} [caps] — from collectCapabilities()
74
73
  * @returns {Set<string>}
@@ -84,7 +83,7 @@ export function noInstanceCommands(caps = collectCapabilities()) {
84
83
  /**
85
84
  * Derive the set of root command names that skip the daily npm-version /
86
85
  * skill checks and the interactive context header. Legacy semantics:
87
- * help, version, completion, skill, docs (a subset of noInstanceCommands).
86
+ * help, version, skill, docs (a subset of noInstanceCommands).
88
87
  *
89
88
  * @param {Map<string, object>} [caps] — from collectCapabilities()
90
89
  * @returns {Set<string>}
@@ -49,7 +49,7 @@ class CommandNode {
49
49
  * subcommand to layer a specialized handler over the base one (see
50
50
  * `requests show`). Appending instead of replacing left the base registration
51
51
  * first in the list and reachable by dispatch/help while the duplicate was
52
- * invisible to the registry (child counts, inventory, completion).
52
+ * invisible to the registry (child counts, inventory).
53
53
  *
54
54
  * Registration order is preserved (the slot is replaced in place) and the
55
55
  * replaced node's aliases are carried over so layered commands keep resolving
@@ -116,7 +116,6 @@ export class LocalCLI {
116
116
  this.middlewares = [];
117
117
  this.failHandler = null;
118
118
  this.script = 'jsn';
119
- this.completionCommand = '__completion';
120
119
  }
121
120
 
122
121
  scriptName(value) { this.script = value; return this; }
@@ -137,7 +136,6 @@ export class LocalCLI {
137
136
  */
138
137
  onParentDiscovery(fn) { this.parentDiscovery = fn; return this; }
139
138
  demandCommand(count, message) { this.root.demand = { count, message }; return this; }
140
- completion(name, _description, handler) { this.completionCommand = name; this.completionHandler = handler; return this; }
141
139
  help() { this.helpEnabled = true; return this; }
142
140
  version() { return this; }
143
141
  strictCommands() { this.strictCmd = true; return this; }
@@ -150,10 +148,6 @@ export class LocalCLI {
150
148
  getCommandHandlers: () => Object.fromEntries(all.map((n) => [n.name, n.definition.handler])),
151
149
  }) };
152
150
  }
153
- showCompletionScript() {
154
- process.stdout.write(`###-begin-jsn-completions-###\n_jsn_yargs_completions() {\n local completions=$(jsn --get-yargs-completions "$@")\n COMPREPLY=( $(compgen -W "$completions" -- "\${COMP_WORDS[COMP_CWORD]}") )\n}\ncomplete -F _jsn_yargs_completions jsn\n###-end-jsn-completions-###\n`);
155
- }
156
-
157
151
  _lookup(list, value) { return list.find((n) => n.name === value || n.aliases.includes(value)); }
158
152
  _knownOptions(nodes) {
159
153
  const map = new Map();
@@ -299,7 +293,7 @@ export class LocalCLI {
299
293
  * stay unchanged.
300
294
  */
301
295
  commandRegistry({ summaries = false } = {}) {
302
- const visible = (node) => node.name !== this.completionCommand && !node.definition.hidden;
296
+ const visible = (node) => !node.definition.hidden;
303
297
  const serialize = (node) => {
304
298
  node.build();
305
299
  const entry = {
@@ -334,7 +328,7 @@ export class LocalCLI {
334
328
  /** Structured child signatures for a parent node, built on demand. */
335
329
  subcommandsOf(node) {
336
330
  return node.children
337
- .filter((child) => child.name !== this.completionCommand && !child.definition.hidden)
331
+ .filter((child) => !child.definition.hidden)
338
332
  .map((child) => {
339
333
  child.build();
340
334
  return {
@@ -362,7 +356,7 @@ export class LocalCLI {
362
356
 
363
357
  _commandRows(node) {
364
358
  return node.children
365
- .filter((child) => child.name !== this.completionCommand && !child.definition.hidden)
359
+ .filter((child) => !child.definition.hidden)
366
360
  .map((child) => ({
367
361
  label: child.definition.command || child.name,
368
362
  description: child.definition.describe || '',
@@ -408,28 +402,10 @@ export class LocalCLI {
408
402
  }));
409
403
  }
410
404
  async parse() {
411
- if (this.args.includes('--get-yargs-completions')) {
412
- const prefix = this.args.at(-1) || '';
413
- let completionArgs = this.args.slice(this.args.indexOf('--get-yargs-completions') + 1, -1);
414
- if (completionArgs[0] === this.script) completionArgs = completionArgs.slice(1);
415
- const { path } = this._findPath(completionArgs);
416
- const node = path.at(-1) || this.root;
417
- node.build();
418
- const argv = { _: path.map((n) => n.name) };
419
- const completionFilter = (callback) => {
420
- const values = [...node.children].filter((n) => n.name !== this.completionCommand && !n.definition.hidden)
421
- .flatMap((n) => path.length ? [n.name] : [n.name, ...n.aliases]);
422
- const opts = [...this._optionConfig(path)].map(([name]) => `--${name}`);
423
- callback(null, [...new Set([...values, ...opts])]);
424
- };
425
- const finish = (values) => process.stdout.write([...new Set(values || [])]
426
- .filter((x) => x.startsWith(prefix) || prefix.startsWith('-') && x.startsWith(prefix)).join('\n') + '\n');
427
- if (this.completionHandler) {
428
- this.completionHandler(prefix, argv, completionFilter, finish);
429
- } else {
430
- completionFilter((err, values) => finish(values));
431
- }
432
- return;
405
+ // Reject stale installed shell snippets instead of dispatching their words
406
+ // as ordinary commands (for example the `r` alias).
407
+ if (this.args.some(arg => arg.split('=')[0] === '--get-yargs-completions')) {
408
+ return this._fail('Unknown option: --get-yargs-completions');
433
409
  }
434
410
  if (this.args[0] === 'help') {
435
411
  const target = this._findPath(this.args.slice(1));
package/src/cli.js CHANGED
@@ -143,9 +143,6 @@ function wrap(handler) {
143
143
  export function buildCLI() {
144
144
  const cfg = loadConfig();
145
145
  const app = new App(cfg);
146
- // Root command names for the completion filter — captured from the yargs
147
- // registry after the chain below finishes registering all commands.
148
- let rootCommands = [];
149
146
 
150
147
  const cliInstance = yargs(hideBin(process.argv))
151
148
  .scriptName('jsn')
@@ -465,64 +462,6 @@ export function buildCLI() {
465
462
  .command(upgradeCmd(wrap))
466
463
  .command(discoverCmd(wrap, (argv) => visibleCommandRegistry(cliInstance.commandRegistry(), app.config, argv)))
467
464
  .demandCommand(1, 'You must specify a command')
468
- // Completion plumbing under a hidden command name, so the explicit
469
- // 'completion' command below owns the UX. (#176)
470
- // The custom filter fixes two yargs behaviors:
471
- // 1. Under strictCommands(), yargs' default completion handler aborts
472
- // when the current word isn't an exact command match. Delegating to
473
- // completionFilter (the default generator) sidesteps that.
474
- // 2. When the current word is an exact ALIAS (e.g. "inc" for incidents),
475
- // yargs descends into that command's subcommands, so a still-being-
476
- // typed "jsn inc<TAB>" offers subcommands that can't match the prefix.
477
- // When completing the FIRST word, merge in the root command list — the
478
- // shell's compgen prefix-filters the final list anyway.
479
- .completion('__completion', false, (current, argv, completionFilter, done) => {
480
- completionFilter((err, completions) => {
481
- let out = completions || [];
482
- const depth = (argv._ || []).length;
483
- if (current && !current.startsWith('-') && depth === 0) {
484
- out = [...new Set([...out, ...rootCommands])];
485
- }
486
- const options = cliInstance.parseGlobalOptions(process.argv.slice(2));
487
- const visible = visibleCommandRegistry(cliInstance.commandRegistry(), loadConfig(options), options);
488
- if (!depth) {
489
- const names = new Set(visible.commands.flatMap(command => [command.name, ...command.aliases]));
490
- out = out.filter(value => value.startsWith('-') || names.has(value));
491
- }
492
- done([...new Set(out)]);
493
- });
494
- })
495
- // User-facing completion command with a real help page (install docs).
496
- // yargs' built-in completion command prints the script even for --help,
497
- // which is why the plumbing above uses the hidden '__completion' name.
498
- .command({
499
- command: 'completion',
500
- describe: 'Generate shell completion script',
501
- builder: (y) => y
502
- .usage('Usage: jsn completion > <file for your shell>')
503
- .epilogue([
504
- 'Install for your shell:',
505
- '',
506
- ' # bash (auto-loaded if the bash-completion package is installed)',
507
- ' jsn completion > ~/.local/share/bash-completion/jsn',
508
- '',
509
- ' # bash (simple)',
510
- ' jsn completion >> ~/.bashrc',
511
- '',
512
- ' # fish',
513
- ' jsn completion > ~/.config/fish/completions/jsn.fish',
514
- '',
515
- ' # zsh — the generated script is bash-style, load via bashcompinit.',
516
- ' # Add to ~/.zshrc:',
517
- ' autoload -U +X bashcompinit && bashcompinit',
518
- ' source <(jsn completion)',
519
- '',
520
- 'Restart your shell (or source the file) after installing.',
521
- ].join('\n')),
522
- handler: () => {
523
- cliInstance.showCompletionScript();
524
- },
525
- })
526
465
  .onParentDiscovery((argv, { path, subcommands }) => {
527
466
  // Reached only for a parent command that declares no default handler of
528
467
  // its own (attachments, docs community, and any future parent) —
@@ -642,10 +581,6 @@ export function buildCLI() {
642
581
  return renderHelp(config, registry, { full: options?.allCommands === true });
643
582
  };
644
583
 
645
- // Snapshot the root command names (plus aliases) for the completion
646
- // filter. Done before any parse — command builders mutate the registry.
647
- rootCommands = cliInstance.getInternalMethods().getCommandInstance().getCommands();
648
-
649
584
  // The capability registry is fully populated now that every command
650
585
  // factory has run — generate the mutation guard's path list.
651
586
  refreshMutationCommands();
@@ -5,7 +5,7 @@ const BASIC_COMMANDS = new Set([
5
5
  'knowledge',
6
6
  'groups', 'groupmembers', 'grouproles', 'users', 'setup', 'auth', 'skill',
7
7
  'cmdb',
8
- 'version', 'upgrade', 'docs', 'history', 'discover', 'completion',
8
+ 'version', 'upgrade', 'docs', 'history', 'discover',
9
9
  'catalogitems', 'cases',
10
10
  ]);
11
11
 
@@ -602,7 +602,7 @@ export async function loginProfile(argv, app, { concise = false } = {}) {
602
602
  Examples:
603
603
  jsn auth login https://dev12345.service-now.com
604
604
  jsn auth login dev373698
605
- jsn auth login --basic https://dev328604.service-now.com
605
+ jsn auth login --basic https://example.service-now.com
606
606
 
607
607
  Find your instance URL in your browser's address bar when logged into ServiceNow.`);
608
608
  }
@@ -1,5 +1,7 @@
1
1
  import { searchFlows, formatFlowSearch } from '../flow-search.js';
2
2
  import fs from 'node:fs';
3
+ import { prepareFlowClone, cloneFlow } from '../flow-clone.js';
4
+ import { canUsePicker } from '../helpers.js';
3
5
  import { formatRecordForDisplay, formatCommandList, getStringField, interactiveList } from '../helpers.js';
4
6
  import { discoverFlowContextFields, normalizeFlowContext, summarizeFlowContexts, formatFlowContextSummary, aggregateFlowContextMappings, mergeFlowContextStats, buildFlowContextQuery } from '../flow-context.js';
5
7
  import { declareCapabilities } from '../capabilities.js';
@@ -44,6 +46,7 @@ const FLOW_COMMANDS = [
44
46
  { name: 'status [identifier]', description: 'Check whether a flow is actually able to run' },
45
47
  { name: 'publish [identifier]', description: 'Publish (activate) a flow, or a custom action with --action' },
46
48
  { name: 'test [identifier]', description: 'Execute a record-triggered flow against one record' },
49
+ { name: 'clone [identifier]', description: 'Duplicate an inactive Draft flow using native Designer copy (alias: copy)' },
47
50
  { name: 'create', description: 'Create a draft flow: guided in a terminal, JSON manifest in scripts' },
48
51
  { name: 'update [identifier]', description: 'Update a draft, or a published flow whose definition reports write access (alias: edit)' },
49
52
  { name: 'doctor', description: 'Check whether this instance can publish flows at all' },
@@ -70,7 +73,7 @@ function triggerGuidance(trigger) {
70
73
  };
71
74
  }
72
75
 
73
- declareCapabilities('flows', { mutationSubcommands: ['create', 'update', 'edit', 'delete', 'publish', 'test', 'unlock'] });
76
+ declareCapabilities('flows', { mutationSubcommands: ['clone', 'copy', 'create', 'update', 'edit', 'delete', 'publish', 'test', 'unlock'] });
74
77
 
75
78
  function renderChecks(checks) {
76
79
  return checks.map((c) => {
@@ -386,6 +389,29 @@ export function flowsCmd(wrap) {
386
389
  });
387
390
  }),
388
391
  })
392
+ .command({
393
+ command: 'clone [identifier]',
394
+ aliases: ['copy'],
395
+ describe: 'Duplicate a supported inactive Draft through native Designer copy',
396
+ builder: y => y
397
+ .option('name', { type: 'string', describe: 'New unique name; required in automation, defaults to source name + copy interactively' })
398
+ .option('force', { type: 'boolean', default: false, describe: 'Approve this clone without confirmation' })
399
+ .epilogue('Same source scope and security/domain policy. Never publishes, activates or executes.\n'
400
+ + 'Select an aligned named in-progress update set first. Unsupported graph categories fail before allocation.\n'
401
+ + 'Live acceptance is pending. Partial failures retain the new identity; reconcile before retrying.'),
402
+ handler: wrap(async (argv, app) => {
403
+ app.requireInstance();
404
+ const identifier = await pickFlow(argv, app);
405
+ if (identifier === undefined) return;
406
+ const plan = await prepareFlowClone(app.sdk, app.getEffectiveInstance(), identifier, { ...argv, interactive: canUsePicker(app, argv) });
407
+ await confirmDesignerMutation(argv, app,
408
+ `Clone ${plan.source.name} (${plan.source.id}) as ${JSON.stringify(plan.name)} in ${plan.scope}; inactive Draft, source unchanged`,
409
+ ['flows', 'clone', plan.source.id, '--name', plan.name]);
410
+ const result = await cloneFlow(app.sdk, app.getEffectiveInstance(), plan);
411
+ return app.ok(result, { summary: `Cloned inactive Draft ${result.flow.name} (${result.flow.id}); source unchanged; capture verified`,
412
+ breadcrumbs: [{ action: 'show', cmd: `jsn flows show ${result.flow.id}`, description: 'Inspect the cloned Draft' }] });
413
+ }),
414
+ })
389
415
  .command({
390
416
  command: 'create',
391
417
  describe: 'Create a draft flow from a JSON manifest or guided prompts',
@@ -0,0 +1,36 @@
1
+ import { SaxesParser } from 'saxes';
2
+ import { isSysId } from './resolve-record.js';
3
+
4
+ // Reuse the previously reviewed strict parent/version XML contract.
5
+ export function verifyCopyCapture(payload, flowId, versionId) {
6
+ if (typeof payload !== 'string' || !isSysId(versionId)) return false;
7
+ const parser = new SaxesParser({ xmlns: false });
8
+ const stack = [];
9
+ const parents = [];
10
+ let parent;
11
+ let invalid = false;
12
+ parser.on('doctype', () => { invalid = true; });
13
+ parser.on('error', () => { invalid = true; });
14
+ parser.on('opentag', tag => {
15
+ stack.push(tag.name);
16
+ if (tag.name === 'sys_hub_flow') {
17
+ if (parent) invalid = true;
18
+ parent = { depth: stack.length, fields: {} };
19
+ parents.push(parent);
20
+ } else if (parent && stack.length === parent.depth + 1 && ['sys_id', 'version_record'].includes(tag.name)) {
21
+ if (Object.hasOwn(parent.fields, tag.name)) invalid = true;
22
+ parent.fields[tag.name] = '';
23
+ }
24
+ });
25
+ const text = value => {
26
+ if (parent && stack.length === parent.depth + 1 && Object.hasOwn(parent.fields, stack.at(-1))) parent.fields[stack.at(-1)] += value;
27
+ };
28
+ parser.on('text', text);
29
+ parser.on('cdata', text);
30
+ parser.on('closetag', () => {
31
+ if (parent && stack.length === parent.depth) parent = undefined;
32
+ stack.pop();
33
+ });
34
+ try { parser.write(payload).close(); } catch { return false; }
35
+ return !invalid && parents.length === 1 && parents[0].fields.sys_id?.trim() === flowId && parents[0].fields.version_record?.trim() === versionId;
36
+ }
@@ -0,0 +1,425 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { readFlowSafeEditStatus, flowSafeEditRequest } from './flow-safe-edit.js';
3
+ import { createVerifiedFlowVersion } from './flow-versioning.js';
4
+ import { isDeepStrictEqual } from 'node:util';
5
+ import { AppError, CodeAPI, errUsage } from './errors.js';
6
+ import { assertSafeExactMatch } from './helpers.js';
7
+ import { resolveRecord, unwrapSysId, isSysId } from './resolve-record.js';
8
+ import { readProcessFlow, readCurrentUpdateSet } from './flow-create.js';
9
+ import { readEffectiveUpdateSet } from './context.js';
10
+ import { verifyCopyCapture } from './flow-clone-capture.js';
11
+
12
+ const raw = value => value && typeof value === 'object' && 'value' in value ? value.value : value;
13
+ const collections = ['triggerInstances', 'actionInstances', 'inputs', 'outputs'];
14
+ // Native copy handles allocation. Unknown graph contracts must be rejected BEFORE
15
+ // asking it to allocate, not reconstructed through the create-manifest adapter.
16
+ const unsupported = ['flowLogicInstances', 'subFlowInstances', 'flowVariables', 'flowCatalogVariables', 'stages', 'connection_configurations', 'deletedFlowLogicInstances', 'nonCriticalErrors'];
17
+ const contextual = ['id', 'name', 'copiedFrom', 'internalName', 'flowCatalogVariableModelId', 'versionRecordId', 'version', 'created', 'updated', 'updatedBy', 'security', 'canWriteProtection', 'userCanRead', 'isFlowEntitled', 'userHasRolesAssignedToFlow'];
18
+ const preserved = ['masterSnapshotId', 'deleted', 'description', 'scope', 'scopeDisplayName', 'scopeName', 'scopeLogo', 'scopeProtectionPolicyReadOnly', 'status', 'active', 'protection', 'type', 'annotation', 'natlang', 'category', 'remoteTriggerSysId', 'access', 'serviceCatalogCallable', 'clientCallable', 'runAs', 'domainName', 'domainId', 'compilerBuild', 'runWithRoles', 'allowHighSecurityRoles', 'pharmacy', 'startingIndexOfErrorHandlingInstances', 'flowPriority', 'attributes', 'authoredOnReleaseVersion', 'generationSource', 'displayNameAfterPreview', 'substatus', 'flowEngineVersion', 'masterSnapshot', 'labelCacheAsJsonString', 'latestSnapshot', 'snapshot', 'isPublished', 'savedAsJson', 'jsonSnapshot'];
19
+ const triggerKeys = ['id', 'flowSysId', 'remoteSysId', 'name', 'inputs', 'outputs', 'displayText', 'deleted', 'metadata', 'comment', 'type', 'triggerDefinitionId', 'publishedVersion', 'userCanRead', 'triggerType', 'hasDynamicOutputs'];
20
+ const actionKeys = ['id', 'flowSysId', 'order', 'displayText', 'uiUniqueIdentifier', 'deleted', 'metadata', 'parent', 'comment', 'generationSource', 'uiComponentIndex', 'actionTypeSysId', 'inputs', 'actionType', 'parentActionTypeId', 'compiledSnapshot', 'aliasIds', 'internalName', 'name', 'type', 'snapshot'];
21
+ const pill = /^\{\{([a-f0-9]{32}|[a-f0-9-]{36})(\.[A-Za-z0-9_.]+)\}\}$/;
22
+ export const flowCloneDigest = value => {
23
+ const canonical = item => Array.isArray(item) ? item.map(canonical) : item && typeof item === 'object'
24
+ ? Object.fromEntries(Object.keys(item).sort().map(key => [key, canonical(item[key])])) : item;
25
+ return createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
26
+ };
27
+ function refuse(message) { throw errUsage(`${message}. No clone allocated.`); }
28
+ function empty(value) { return Array.isArray(value) ? value.length === 0 : value && typeof value === 'object' && Object.keys(value).length === 0; }
29
+ function knownKeys(value, allowed, path) {
30
+ const unknown = Object.keys(value).filter(key => !allowed.includes(key));
31
+ if (unknown.length) refuse(`Unverified provider fields at ${path}: ${unknown.join(', ')}`);
32
+ }
33
+ function variableEntries(items) { return items.flatMap(item => [item, ...variableEntries(item.children || [])]); }
34
+ function owned(source) {
35
+ return [...source.triggerInstances, ...source.actionInstances, ...variableEntries(source.inputs), ...variableEntries(source.outputs)];
36
+ }
37
+ function validateValues(value, path = 'definition') {
38
+ if (!value || typeof value !== 'object') return;
39
+ if (Array.isArray(value)) return value.forEach((item, index) => validateValues(item, `${path}[${index}]`));
40
+ // A complete typed value pill is a known reference. Embedded pills, scripts
41
+ // containing pills and opaque binding encodings are not safe to certify.
42
+ if (typeof value.value === 'string' && value.value.includes('{{')) {
43
+ if (value.scriptActive || !pill.test(value.value)) refuse(`Unsupported embedded/script binding at ${path}`);
44
+ }
45
+ for (const [key, child] of Object.entries(value)) validateValues(child, `${path}.${key}`);
46
+ }
47
+ export function validateCloneSource(source) { return validateCloneDefinition(source, true); }
48
+
49
+ function validateCloneDefinition(source, requireSavedVersion) {
50
+ if (!source || source.type !== 'flow' || !isSysId(source.id)) refuse('A readable Flow definition is required');
51
+ if (source.active !== false || source.status !== 'draft' || source.deleted !== false) refuse('Only inactive, nondeleted Draft sources are supported');
52
+ if (source.security?.can_read !== true || source.security?.can_write !== true) refuse('Source must explicitly permit read and write');
53
+ for (const field of ['scope', 'domainId', 'domainName', 'access', 'protection', 'runAs', 'runWithRoles', 'description']) {
54
+ if (!Object.hasOwn(source, field)) refuse(`Source security/property inventory is missing ${field}`);
55
+ }
56
+ knownKeys(source, [...collections, ...unsupported, ...contextual, ...preserved], 'flow');
57
+ for (const key of unsupported) if (source[key] !== undefined && !empty(source[key])) refuse(`Clone verification does not yet support nonempty ${key}`);
58
+ if (source.startingIndexOfErrorHandlingInstances !== -1) refuse('Error-handler graph cloning is not yet verified');
59
+ for (const key of collections) if (!Array.isArray(source[key])) refuse(`Unreadable ${key}`);
60
+ if (source.triggerInstances.length !== 1) refuse('Exactly one record trigger is required');
61
+ for (const trigger of source.triggerInstances) {
62
+ knownKeys(trigger, triggerKeys, 'trigger');
63
+ if (!['record_create', 'record_update', 'record_create_or_update'].includes(trigger.type) || trigger.deleted !== false) refuse('Unsupported trigger lifecycle/family');
64
+ if (trigger.remoteSysId) refuse('Remote trigger cloning is not verified');
65
+ }
66
+ for (const action of source.actionInstances) {
67
+ knownKeys(action, actionKeys, 'action');
68
+ if (action.parent || action.compiledSnapshot || action.snapshot || action.aliasIds?.length || action.deleted !== false) refuse('Nested/runtime/aliased action cloning is not verified');
69
+ if (!isSysId(action.actionTypeSysId) || action.actionType?.state !== 'published') refuse('Action must reference a published reusable definition');
70
+ }
71
+ if (source.masterSnapshotId || source.latestSnapshot || source.masterSnapshot || source.snapshot || source.isPublished || source.jsonSnapshot) refuse('Source has runtime snapshot state');
72
+ for (const item of [...source.triggerInstances, ...source.actionInstances]) {
73
+ if (!isSysId(item.id) || item.flowSysId !== source.id) refuse('Component identity/ownership is incomplete');
74
+ }
75
+ if (!isSysId(source.versionRecordId) && (requireSavedVersion || ![undefined, null, ''].includes(source.versionRecordId))) refuse('Source has no readable saved version pointer');
76
+ const identities = new Set([source.id]);
77
+ for (const item of owned(source)) {
78
+ if (!item.id) continue; // nested anonymous schema children have no identity
79
+ if (!isSysId(item.id) || identities.has(item.id)) refuse('Ambiguous owned component identity');
80
+ identities.add(item.id);
81
+ if (item.flowSysId !== undefined && item.flowSysId !== source.id) refuse('Invalid component ownership');
82
+ if (item.uiUniqueIdentifier) {
83
+ if (identities.has(item.uiUniqueIdentifier)) refuse('Duplicate UI identity');
84
+ identities.add(item.uiUniqueIdentifier);
85
+ }
86
+ }
87
+ if (!isSysId(source.flowCatalogVariableModelId) || identities.has(source.flowCatalogVariableModelId)) refuse('Missing or reused catalog model identity');
88
+ validateValues(source);
89
+ return { collections, unsupported, preserved, contextual };
90
+ }
91
+
92
+ // The editor save re-materializes a provider label on mapping-provider variables
93
+ // that lacked one. Accept only the exact type label the provider would derive;
94
+ // a different, missing or foreign value still fails structural comparison.
95
+ function normalizeProviderLabels(source, destination) {
96
+ const pairs = (a = [], b = [], visit) => a.forEach((item, index) => b[index] && visit(item, b[index]));
97
+ const variables = (a, b) => pairs(a, b, (from, to) => {
98
+ // Definition GETs use type_label; the save serializer uses typeLabel.
99
+ if (from.attributes && !Object.hasOwn(from.attributes, 'uiTypeLabel') && to.attributes &&
100
+ Object.hasOwn(to.attributes, 'uiTypeLabel') && to.attributes.uiTypeLabel === (to.type_label ?? to.typeLabel)) {
101
+ delete to.attributes.uiTypeLabel;
102
+ }
103
+ variables(from.children, to.children);
104
+ });
105
+ variables(source.inputs, destination.inputs);
106
+ variables(source.outputs, destination.outputs);
107
+ pairs(source.triggerInstances, destination.triggerInstances, (from, to) => { variables(from.inputs, to.inputs); variables(from.outputs, to.outputs); });
108
+ pairs(source.actionInstances, destination.actionInstances, (from, to) => { variables(from.inputs, to.inputs); variables(from.outputs, to.outputs); });
109
+ return destination;
110
+ }
111
+
112
+ function nativeCloneComparable(source, destination) {
113
+ const result = normalizeProviderLabels(source, structuredClone(destination));
114
+ for (const [index, action] of result.actionInstances.entries()) {
115
+ const original = source.actionInstances[index];
116
+ const definitionId = a => a.actionType?.id ?? a.actionType?.fId;
117
+ const definitionState = a => a.actionType?.state ?? a.actionType?.fState;
118
+ if (action.compiledSnapshot && action.compiledSnapshot !== original?.compiledSnapshot) {
119
+ if (!original || original.compiledSnapshot !== '' || action.snapshot || action.parent || action.aliasIds?.length ||
120
+ definitionId(original) !== original.actionTypeSysId || definitionState(original) !== 'published' ||
121
+ definitionState(action) !== 'published' || !isSysId(action.actionTypeSysId) ||
122
+ action.actionTypeSysId !== original.actionTypeSysId || definitionId(action) !== action.actionTypeSysId ||
123
+ action.compiledSnapshot !== action.actionTypeSysId) throw new Error('Unverified native action snapshot derivation');
124
+ action.compiledSnapshot = original.compiledSnapshot;
125
+ }
126
+ }
127
+ return result;
128
+ }
129
+
130
+ // Identity maps apply only to owned identity/ownership paths and complete typed
131
+ // input pills. User scripts, conditions, arbitrary keys and literal IDs stay exact.
132
+ export function verifyClonedFlow(source, destination, name) {
133
+ return verifyCloneGraph(source, destination, name, true);
134
+ }
135
+
136
+ // Private provisional contract: only the destination pointer may be absent, and
137
+ // only while native save/version creation is still pending. Source stays strict.
138
+ function verifyCloneGraph(source, destination, name, requireSavedVersion) {
139
+ validateCloneSource(source);
140
+ // The native editor preserves flow-local UI identifiers and, for a flat
141
+ // published reusable action, materializes compiledSnapshot as that definition
142
+ // identity. This is destination-only: runtime-bearing sources still refuse.
143
+ const comparable = nativeCloneComparable(source, destination);
144
+ try { validateCloneDefinition(comparable, requireSavedVersion); }
145
+ catch (cause) { throw new Error(`Destination definition invalid: ${cause.message.replace(/\. No clone allocated\.$/, '')}`, { cause }); }
146
+ if (destination.name !== name || destination.scope !== source.scope || destination.copiedFrom !== source.id) throw new Error('Clone identity/name/scope/provenance mismatch');
147
+ const before = owned(source), after = owned(destination);
148
+ if (before.length !== after.length) throw new Error('Clone owned component count changed');
149
+ const old = new Set([source.id, source.flowCatalogVariableModelId, ...before.flatMap(item => [item.id, item.uiUniqueIdentifier]).filter(Boolean)]);
150
+ const fresh = new Set();
151
+ const mapping = new Map();
152
+ function allocate(a, b) {
153
+ if (!a) { if (b) throw new Error('Unexpected owned identity'); return; }
154
+ if (!b || old.has(b) || fresh.has(b)) throw new Error('Clone reused or omitted an owned identity');
155
+ fresh.add(b); mapping.set(a, b);
156
+ }
157
+ allocate(source.id, destination.id);
158
+ allocate(source.flowCatalogVariableModelId, destination.flowCatalogVariableModelId);
159
+ before.forEach((item, index) => {
160
+ allocate(item.id, after[index].id);
161
+ if (item.uiUniqueIdentifier && item.uiUniqueIdentifier === after[index].uiUniqueIdentifier) mapping.set(item.uiUniqueIdentifier, item.uiUniqueIdentifier);
162
+ else allocate(item.uiUniqueIdentifier, after[index].uiUniqueIdentifier);
163
+ });
164
+ const ref = value => mapping.get(value) || value;
165
+ function values(value) {
166
+ if (Array.isArray(value)) return value.map(values);
167
+ if (!value || typeof value !== 'object') return value;
168
+ const result = Object.fromEntries(Object.entries(value).map(([key, child]) => [key, values(child)]));
169
+ if (!value.scriptActive && typeof value.value === 'string' && pill.test(value.value)) {
170
+ result.value = value.value.replace(pill, (_all, id, path) => `{{${ref(id)}${path}}}`);
171
+ if (value.displayValue === value.value) result.displayValue = result.value;
172
+ }
173
+ return result;
174
+ }
175
+ function component(item) {
176
+ const result = values(item);
177
+ for (const key of ['id', 'uiUniqueIdentifier', 'flowSysId']) if (Object.hasOwn(item, key)) result[key] = ref(item[key]);
178
+ if (item.children) result.children = item.children.map(component);
179
+ return result;
180
+ }
181
+ for (const key of collections) {
182
+ if (!isDeepStrictEqual(source[key].map(component), comparable[key])) throw new Error(`Clone changed or miswired ${key}`);
183
+ }
184
+ for (const key of [...preserved, ...unsupported]) if (!isDeepStrictEqual(source[key], destination[key])) throw new Error(`Clone did not preserve ${key}`);
185
+ return { verified: true, identity_count: mapping.size, inventory: { preserved, regenerated: ['id', 'flowCatalogVariableModelId', 'component.id'], flow_local_ui_identity: 'preserved or remapped with typed references', derived: ['flat published action compiledSnapshot linked to unchanged reusable definition'], contextual, unsupported_nonempty: unsupported } };
186
+ }
187
+
188
+ async function readSavedCloneVersion(sdk, flow) {
189
+ const rows = await sdk.list('sys_hub_flow_version', new URLSearchParams({ sysparm_query: `sys_id=${flow.versionRecordId}^flow=${flow.id}`, sysparm_limit: '2', sysparm_fields: 'sys_id,flow,payload' }));
190
+ if (!Array.isArray(rows) || rows.length !== 1 || raw(rows[0].flow) !== flow.id || raw(rows[0].sys_id) !== flow.versionRecordId) throw new Error('Exact saved version is not readable');
191
+ const payload = JSON.parse(raw(rows[0].payload));
192
+ if (payload?.id !== flow.id || payload.name !== flow.name || payload.scope !== flow.scope) throw new Error('Saved version identity/name/scope mismatch');
193
+ // Independently link each saved component/value to the current definition.
194
+ // Parameter schemas differ between native serialized and GET forms; the full
195
+ // serialized schemas are compared source-to-destination below, not flattened.
196
+ const valueTree = values => (values || []).map(value => ({ name: value.name, value: value.value, scriptActive: value.scriptActive, children: valueTree(value.children) }));
197
+ for (const key of collections) {
198
+ if (!Array.isArray(payload[key]) || payload[key].length !== flow[key].length) throw new Error(`Saved version has incomplete ${key}`);
199
+ payload[key].forEach((item, index) => {
200
+ const current = flow[key][index];
201
+ if (item.id !== current.id || item.flowSysId !== current.flowSysId || !isDeepStrictEqual(valueTree(item.inputs), valueTree(current.inputs))) throw new Error(`Saved version has stale identity/input values in ${key}`);
202
+ });
203
+ }
204
+ return payload;
205
+ }
206
+
207
+ export function verifyClonedVersions(source, destination) {
208
+ destination = nativeCloneComparable(source, destination);
209
+ // Version serialization records the compiler engine version. A freshly saved
210
+ // draft is uncompiled (0); requiring the source's compiled value would demand
211
+ // a compilation this workflow never performs. Only that exact draft state is
212
+ // accepted - any other engine version still fails the structural comparison.
213
+ if (destination.engineVersion === 0 && Number.isInteger(source.engineVersion) && source.engineVersion > 0) {
214
+ destination.engineVersion = source.engineVersion;
215
+ }
216
+ const ownedIds = new Set([source.id, source.flowCatalogVariableModelId, ...collections.flatMap(key => source[key].map(item => item.id)).filter(Boolean)]);
217
+ for (const key of collections) for (const item of destination[key]) {
218
+ if (item.id && ownedIds.has(item.id)) throw new Error('Saved version reused an owned database identity');
219
+ }
220
+ const mapping = new Map([[source.id, destination.id], [source.flowCatalogVariableModelId, destination.flowCatalogVariableModelId]]);
221
+ for (const key of collections) {
222
+ const before = key === 'inputs' || key === 'outputs' ? variableEntries(source[key]) : source[key];
223
+ const after = key === 'inputs' || key === 'outputs' ? variableEntries(destination[key]) : destination[key];
224
+ if (before.length !== after.length) throw new Error(`Saved version changed ${key}`);
225
+ before.forEach((item, index) => { for (const field of ['id', 'uiUniqueIdentifier']) if (item[field]) mapping.set(item[field], after[index][field]); });
226
+ }
227
+ function translate(value) {
228
+ if (Array.isArray(value)) return value.map(translate);
229
+ if (!value || typeof value !== 'object') return value;
230
+ const result = Object.fromEntries(Object.entries(value).map(([key, child]) => [key, translate(child)]));
231
+ if (!value.scriptActive && typeof value.value === 'string' && pill.test(value.value)) {
232
+ result.value = value.value.replace(pill, (_all, id, path) => `{{${mapping.get(id) || id}${path}}}`);
233
+ if (value.displayValue === value.value) result.displayValue = result.value;
234
+ }
235
+ return result;
236
+ }
237
+ function component(item) {
238
+ const result = translate(item);
239
+ for (const field of ['id', 'uiUniqueIdentifier', 'flowSysId']) if (item[field]) result[field] = mapping.get(item[field]) || item[field];
240
+ if (item.children) result.children = item.children.map(component);
241
+ return result;
242
+ }
243
+ const expected = translate(source);
244
+ for (const key of collections) expected[key] = source[key].map(component);
245
+ // These are version-level provenance/permission fields, never graph content.
246
+ const omitted = new Set(contextual);
247
+ const stable = value => {
248
+ const result = structuredClone(Object.fromEntries(Object.entries(value).filter(([key]) => !omitted.has(key))));
249
+ // Native version serialization omits this mapper on these two fixed record
250
+ // trigger outputs; current ProcessFlow schemas agree. Never strip mapper
251
+ // metadata from action inputs, authored schemas, or arbitrary outputs.
252
+ for (const trigger of result.triggerInstances || []) for (const output of trigger.outputs || []) {
253
+ if (((output.name === 'current' && output.type === 'document_id') || (output.name === 'table_name' && output.type === 'table_name')) &&
254
+ output.parameter?.name === output.name && output.parameter?.type === output.type &&
255
+ output.parameter?.attributes?.element_mapping_provider === 'com.glide.flow_design.action.data.FlowDesignVariableMapper') {
256
+ delete output.parameter.attributes.element_mapping_provider;
257
+ }
258
+ }
259
+ return result;
260
+ };
261
+ const before = stable(expected), after = stable(destination);
262
+ // Measured native save omission: triggerInstances[].inputs[].parameter's
263
+ // own empty choice lists only. Validate both parameter shapes and their input
264
+ // names; never walk defaults, values, children, or unknown provider payloads.
265
+ for (const [index, trigger] of before.triggerInstances.entries()) {
266
+ for (const [inputIndex, input] of trigger.inputs.entries()) {
267
+ const saved = after.triggerInstances?.[index]?.inputs?.[inputIndex];
268
+ const parameter = input.parameter, savedParameter = saved?.parameter;
269
+ if (!parameter || !savedParameter || typeof input.name !== 'string' ||
270
+ input.name !== saved.name || parameter.name !== input.name || savedParameter.name !== input.name ||
271
+ typeof parameter.type !== 'string' || parameter.type !== savedParameter.type ||
272
+ !Array.isArray(parameter.children) || !Array.isArray(savedParameter.children)) continue;
273
+ for (const field of ['choices', 'defaultChoices']) {
274
+ if (Array.isArray(parameter[field]) && parameter[field].length === 0 && !Object.hasOwn(savedParameter, field)) delete parameter[field];
275
+ }
276
+ }
277
+ }
278
+ if (!isDeepStrictEqual(before, after)) throw new Error('Saved version content/schema was not preserved under the explicit identity map');
279
+ return true;
280
+ }
281
+
282
+ // Full native save: preserve every readable field, including typed schemas and
283
+ // unknown nested provider metadata. The shipped editor removes only reusable
284
+ // action inputs/steps (not instance inputs), and emits label_cache separately.
285
+ export function serializeNativeClone(flow) {
286
+ const body = structuredClone(flow);
287
+ body.deletedActions = [];
288
+ body.deletedTriggers = [];
289
+ body.label_cache = JSON.parse(body.labelCacheAsJsonString || '[]');
290
+ body.aliasOverride = { aliasOverrideMappings: [] };
291
+ body.clientSessionId = randomUUID();
292
+ for (const action of body.actionInstances) {
293
+ delete action.actionType.inputs;
294
+ delete action.actionType.steps;
295
+ }
296
+ return body;
297
+ }
298
+
299
+ async function ownedCloneLease(sdk, instance, id) {
300
+ const user = await sdk.getCurrentUser({ touchLastSeen: false });
301
+ const rows = await sdk.list('sys_hub_flow_safe_edit', new URLSearchParams({ sysparm_query: `flow=${id}`, sysparm_limit: '2', sysparm_fields: 'sys_id,flow,user' }));
302
+ const status = await readFlowSafeEditStatus(sdk, instance, id);
303
+ if (!isSysId(user?.sys_id) || !Array.isArray(rows) || rows.length !== 1 ||
304
+ !isSysId(raw(rows[0].sys_id)) || raw(rows[0].flow) !== id || raw(rows[0].user) !== user.sys_id ||
305
+ status.canUserEdit !== true || status.currentEditor) throw new Error('Native clone lease ownership is unconfirmed; no save or release attempted');
306
+ return raw(rows[0].sys_id);
307
+ }
308
+
309
+ // Call only for a positively acknowledged allocation owned by this invocation,
310
+ // or an explicitly approved recovery of that exact retained allocation.
311
+ export async function completeNativeClone(sdk, instance, source, flow, name) {
312
+ verifyCloneGraph(source, flow, name, false);
313
+ const leaseId = await ownedCloneLease(sdk, instance, flow.id);
314
+ let failure, completed;
315
+ try {
316
+ const response = await sdk.request(`${instance}/api/now/processflow/flow?sysparm_transaction_scope=${encodeURIComponent(flow.scope)}`, {
317
+ method: 'PUT', body: JSON.stringify(serializeNativeClone(flow)),
318
+ });
319
+ if (response?.error || response?.result?.error || response?.result?.errors?.length) throw new Error('Native save returned flow errors');
320
+ completed = await readProcessFlow(sdk, instance, flow.id, flow.scope);
321
+ verifyCloneGraph(source, completed, name, false);
322
+ await createVerifiedFlowVersion(sdk, { instance, flowId: flow.id, scope: flow.scope, type: 'Save', annotation: '' });
323
+ completed = await readProcessFlow(sdk, instance, flow.id, flow.scope);
324
+ verifyClonedFlow(source, completed, name);
325
+ // The update-set XML for this record is generated from the parent write, so it
326
+ // still carries the pre-version record pointer. Re-saving the identical owned
327
+ // graph once after version creation makes the exact parent capture reference
328
+ // the current saved version; it creates no new version and changes no content.
329
+ const refresh = await sdk.request(`${instance}/api/now/processflow/flow?sysparm_transaction_scope=${encodeURIComponent(flow.scope)}`, {
330
+ method: 'PUT', body: JSON.stringify(serializeNativeClone(completed)),
331
+ });
332
+ if (refresh?.error || refresh?.result?.error || refresh?.result?.errors?.length) throw new Error('Native capture-refresh save returned flow errors');
333
+ completed = await readProcessFlow(sdk, instance, flow.id, flow.scope);
334
+ verifyClonedFlow(source, completed, name);
335
+ } catch (error) { failure = error; }
336
+ // Recheck exact lease identity/user before release, including failure paths.
337
+ // Never acquire/take over another session and never delete the flow itself.
338
+ try {
339
+ if (await ownedCloneLease(sdk, instance, flow.id) !== leaseId) throw new Error('Native clone lease changed; release refused');
340
+ const { deleteResult } = await flowSafeEditRequest(sdk, instance, flow.id, 'delete');
341
+ if (deleteResult?.deleteSuccess !== true || deleteResult.id !== flow.id) throw new Error('Native clone release was not acknowledged');
342
+ const status = await readFlowSafeEditStatus(sdk, instance, flow.id);
343
+ const leases = await sdk.list('sys_hub_flow_safe_edit', new URLSearchParams({ sysparm_query: `flow=${flow.id}`, sysparm_limit: '2', sysparm_fields: 'sys_id' }));
344
+ if (status.canUserEdit || status.currentEditor || !Array.isArray(leases) || leases.length) throw new Error('Native clone release readback failed');
345
+ } catch (error) { throw new Error(`${failure ? `${failure.message}; ` : ''}Clone ${flow.id} lease release failed: ${error.message}`, { cause: error }); }
346
+ if (failure) throw failure;
347
+ return completed;
348
+ }
349
+
350
+ async function assertUnusedName(sdk, scope, name) {
351
+ const rows = await sdk.list('sys_hub_flow', new URLSearchParams({ sysparm_query: `name=${name}^sys_scope=${scope}`, sysparm_limit: '1', sysparm_fields: 'sys_id,name,sys_scope' }));
352
+ if (!Array.isArray(rows)) refuse('Collision lookup was unreadable');
353
+ if (rows.length) refuse(`A flow named ${JSON.stringify(name)} already exists in the source scope; no overwrite`);
354
+ }
355
+ export async function prepareFlowClone(sdk, instance, identifier, options = {}) {
356
+ try {
357
+ assertSafeExactMatch(identifier);
358
+ const record = await resolveRecord(sdk, { table: 'sys_hub_flow', identifier, matchField: 'name', resource: 'Flow', fields: ['sys_scope', 'name', 'active', 'status'] });
359
+ const id = unwrapSysId(record), scope = raw(record.sys_scope);
360
+ if (!isSysId(id) || !(scope === 'global' || isSysId(scope))) refuse('Unreadable native source scope or identity');
361
+ const source = await readProcessFlow(sdk, instance, id, scope);
362
+ if (source.id !== id || source.scope !== scope) refuse('Source definition identity/scope mismatch');
363
+ validateCloneSource(source);
364
+ if (!options.name && !options.interactive) refuse('--name is required for automation');
365
+ const name = options.name ?? `${source.name} copy`;
366
+ if (typeof name !== 'string' || !name.trim()) refuse('--name must be nonempty');
367
+ assertSafeExactMatch(name);
368
+ await assertUnusedName(sdk, scope, name);
369
+ const saved_version = await readSavedCloneVersion(sdk, source);
370
+ return { source, scope, name, source_digest: flowCloneDigest(source), saved_version, version_digest: flowCloneDigest(saved_version) };
371
+ } catch (cause) {
372
+ if (cause instanceof AppError) throw cause;
373
+ throw new AppError(CodeAPI, `Clone preflight failed: ${cause.message}`, 'No clone allocated.', 0, cause);
374
+ }
375
+ }
376
+
377
+ export async function cloneFlow(sdk, instance, plan, { capturePolls = 21, pollDelay = 250 } = {}) {
378
+ let id, stage = 'preflight';
379
+ let allocationAttempted = false;
380
+ try {
381
+ validateCloneSource(plan.source);
382
+ if (flowCloneDigest(plan.source) !== plan.source_digest) refuse('Clone plan changed');
383
+ await assertUnusedName(sdk, plan.scope, plan.name);
384
+ const current = await readCurrentUpdateSet(sdk), effective = await readEffectiveUpdateSet(sdk);
385
+ const setId = raw(current?.sys_id || current?.sysId);
386
+ if (!isSysId(setId) || raw(current?.state) !== 'in progress' || raw(current?.name) === 'Default' || effective.sys_id !== setId) refuse('Select a named in-progress update set and align the effective session before cloning');
387
+ // No session context writes. Caller selection must already be aligned.
388
+ const sourceBefore = await readProcessFlow(sdk, instance, plan.source.id, plan.scope);
389
+ if (flowCloneDigest(sourceBefore) !== plan.source_digest) refuse('Source changed after confirmation');
390
+ if (flowCloneDigest(plan.saved_version) !== plan.version_digest || flowCloneDigest(await readSavedCloneVersion(sdk, sourceBefore)) !== plan.version_digest) refuse('Source saved version changed after confirmation');
391
+ stage = 'native_copy'; allocationAttempted = true;
392
+ // Source-confirmed Designer contract. Exactly one allocation, no fallbacks.
393
+ const response = await sdk.request(`${instance}/api/now/processflow/flow/${plan.source.id}/copy?sysparm_transaction_scope=${encodeURIComponent(plan.scope)}`, { method: 'POST', body: JSON.stringify({ name: plan.name, scope: plan.scope }) });
394
+ const allocated = response?.result?.data;
395
+ if (!isSysId(allocated) || allocated === plan.source.id) throw new Error('Provider returned no fresh clone identity');
396
+ id = allocated;
397
+ stage = 'definition_readback';
398
+ let flow = await readProcessFlow(sdk, instance, id, plan.scope);
399
+ const graph = verifyCloneGraph(plan.source, flow, plan.name, false);
400
+ stage = 'native_save_version_release';
401
+ flow = await completeNativeClone(sdk, instance, plan.source, flow, plan.name);
402
+ stage = 'saved_version';
403
+ if (!isSysId(flow.versionRecordId) || flow.versionRecordId === plan.source.versionRecordId) throw new Error('No fresh saved version pointer');
404
+ const savedVersion = await readSavedCloneVersion(sdk, flow);
405
+ verifyClonedVersions(plan.saved_version, savedVersion);
406
+ stage = 'update_set_capture';
407
+ let captures;
408
+ for (let attempt = 0; attempt < capturePolls; attempt++) {
409
+ const rows = await sdk.list('sys_update_xml', new URLSearchParams({ sysparm_query: `update_set=${setId}^name=sys_hub_flow_${id}`, sysparm_limit: '2', sysparm_fields: 'sys_id,name,update_set,action,payload' }));
410
+ if (!Array.isArray(rows)) throw new Error('Unreadable update-set capture');
411
+ if (rows.length === 1 && raw(rows[0].name) === `sys_hub_flow_${id}` && raw(rows[0].update_set) === setId && raw(rows[0].action) === 'INSERT_OR_UPDATE' && verifyCopyCapture(raw(rows[0].payload), id, flow.versionRecordId)) { captures = rows; break; }
412
+ if (attempt + 1 < capturePolls) await new Promise(resolve => setTimeout(resolve, pollDelay));
413
+ }
414
+ if (!captures) throw new Error('Exact new parent/version XML capture not verified within bounded read polling');
415
+ stage = 'source_and_context_preservation';
416
+ const sourceAfter = await readProcessFlow(sdk, instance, plan.source.id, plan.scope);
417
+ if (flowCloneDigest(sourceAfter) !== plan.source_digest) throw new Error('Source digest changed during clone');
418
+ const finalSet = await readCurrentUpdateSet(sdk), finalEffective = await readEffectiveUpdateSet(sdk);
419
+ if (!isDeepStrictEqual(current, finalSet) || !isDeepStrictEqual(effective, finalEffective)) throw new Error('Capture context changed during clone');
420
+ return { flow, source: { id: plan.source.id, unchanged: true, before_digest: plan.source_digest, after_digest: flowCloneDigest(sourceAfter) }, graph, version: { id: flow.versionRecordId, flow: id }, capture: { update_set: setId, parent: id, version: flow.versionRecordId, records: captures.map(row => raw(row.sys_id)) }, context_unchanged: true, published: false, activated: false, executed: false };
421
+ } catch (cause) {
422
+ if (!allocationAttempted && cause instanceof AppError) throw cause;
423
+ throw new AppError(CodeAPI, `Flow clone ${id ? `allocated ${id}, verification failed` : allocationAttempted ? 'allocation outcome uncertain' : 'failed before allocation'} at ${stage}: ${cause.message}`, `${id ? `Inspect flows show ${id}.` : allocationAttempted ? `Reconcile source ${plan.source.id} and name ${JSON.stringify(plan.name)} before retrying.` : 'No clone allocated.'} No automatic retry, cleanup, publish or execution.`, 0, cause);
424
+ }
425
+ }
@@ -1404,7 +1404,21 @@ function assertStepReadback(definition, expectedSteps, kind, flowId) {
1404
1404
  if (expected.inputs) {
1405
1405
  for (const input of expected.inputs) {
1406
1406
  const found = inputList(actual).filter(i => i.name === input.name);
1407
- if (found.length !== 1 || !requestedContentMatches(found[0], input)) throw new Error(`Flow ${flowId} ${kind} ${expected.uiUniqueIdentifier} input ${input.name} did not match the requested value; preservation failed`);
1407
+ // ProcessFlow reads unwrap GraphQL value envelopes and derive choice
1408
+ // display labels (e.g. info -> Info). Compare the semantic value and
1409
+ // requested metadata, not the transport envelope or rendered label.
1410
+ const { value, displayValue: _displayValue, ...metadata } = input;
1411
+ const savedInput = { ...found[0] };
1412
+ if (metadata.parameter) {
1413
+ // Read-side attributes are a map; GraphQL accepts their string form.
1414
+ metadata.parameter = Object.fromEntries(Object.entries(flowDesignParameter(metadata.parameter)).filter(([, v]) => v !== null));
1415
+ savedInput.parameter = flowDesignParameter(savedInput.parameter);
1416
+ }
1417
+ if (found.length !== 1
1418
+ || !isDeepStrictEqual(inputRawValue(found[0]), inputRawValue(input))
1419
+ || (found[0].value && typeof found[0].value === 'object' && Object.hasOwn(found[0].value, 'schemaless')
1420
+ && !requestedContentMatches(found[0].value, value))
1421
+ || !requestedContentMatches(savedInput, metadata)) throw new Error(`Flow ${flowId} ${kind} ${expected.uiUniqueIdentifier} input ${input.name} did not match the requested value; preservation failed`);
1408
1422
  }
1409
1423
  }
1410
1424
  }
package/src/help.js CHANGED
@@ -158,7 +158,6 @@ const CONFIG_COMMANDS = [
158
158
  { name: 'domains', desc: 'Domains (domain separation)' },
159
159
  { name: 'midservers', desc: 'MID Servers and MID-run commands' },
160
160
  { name: 'platform', desc: 'Platform health and node statistics (read-only)' },
161
- { name: 'completion', desc: 'Shell completion script' },
162
161
  ];
163
162
 
164
163
  const DEVELOPER_COMMANDS = [