@jacebenson/jsn 5.5.3-dev.177.1 → 5.5.3-dev.179.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.5.3-dev.177.1",
3
+ "version": "5.5.3-dev.179.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": {
@@ -97,6 +97,11 @@ export function dailyCheckSkipCommands(caps = collectCapabilities()) {
97
97
  return out;
98
98
  }
99
99
 
100
+ export function skipsContextHeader(argv, caps = collectCapabilities()) {
101
+ return contextHeaderSkipCommands(caps).has(argv._?.[0])
102
+ || caps.get(argv._?.[0])?.skipContextHeaderSubcommands?.includes(argv._?.[1]) === true;
103
+ }
104
+
100
105
  export function contextHeaderSkipCommands(caps = collectCapabilities()) {
101
106
  const out = dailyCheckSkipCommands(caps);
102
107
  for (const [name, capability] of caps) {
package/src/cli.js CHANGED
@@ -12,7 +12,7 @@ import { renderHelp, renderTips } from './help.js';
12
12
  import { isMutationCommand, refreshMutationCommands } from './mutations.js';
13
13
  import { maybeShowHome } from './welcome.js';
14
14
  import { skippedUpdatesCmd } from './commands/skipped-updates.js';
15
- import { isLocalPreview, noInstanceCommands, dailyCheckSkipCommands, contextHeaderSkipCommands } from './capabilities.js';
15
+ import { isLocalPreview, noInstanceCommands, dailyCheckSkipCommands, skipsContextHeader } from './capabilities.js';
16
16
  import { guardExit, exitWithError, AppError, CodeUsage } from './errors.js';
17
17
  import { formatCommandList } from './helpers.js';
18
18
 
@@ -352,7 +352,7 @@ export function buildCLI() {
352
352
  }
353
353
 
354
354
  // Print context header for interactive terminals
355
- if (!contextHeaderSkipCommands().has(cmd)) {
355
+ if (!skipsContextHeader(argv)) {
356
356
  await argv.app.printContextHeader(argv);
357
357
  }
358
358
  })
@@ -1,4 +1,5 @@
1
1
  import fs from 'node:fs';
2
+ import { diffUpdateSets } from '../update-set-diff.js';
2
3
  import path from 'node:path';
3
4
  import { inspectUpdateSetXML, updateSetFilename, MAX_UPDATE_SET_BYTES } from '../update-set-xml.js';
4
5
  import { editor, confirm } from '../prompts.js';
@@ -15,6 +16,7 @@ import { assertNoUnresolvedProblems, DEFAULT_OPERATION_TIMEOUT_MS } from '../upd
15
16
  declareCapabilities('updatesets', {
16
17
  mutationSubcommands: ['create', 'set', 'complete', 'ignore', 'parent', 'import', 'reopen', 'preview', 'commit'],
17
18
  mutationContextExemptSubcommands: ['create', 'set', 'import', 'reopen', 'preview', 'commit'],
19
+ skipContextHeaderSubcommands: ['diff'],
18
20
  localPreviewSubcommands: ['import'],
19
21
  });
20
22
 
@@ -548,6 +550,15 @@ export function updateSetsCmd(wrap) {
548
550
  describe: 'Manage update sets. Global + Default mutations require approval (--force only after user approval); create/set remain available to select a dedicated capture set. Scope mismatches warn; completed capture sets block writes.',
549
551
  builder: (yargs) => {
550
552
  return yargs
553
+ .command({
554
+ command: 'diff',
555
+ describe: 'Read-only captured-set comparison: jsn updatesets diff --source dev --target test [--from 2w|2026-10-01]. Not deployment readiness; bounded count-verified reads (20 x 200 rows/query).',
556
+ builder: y => y
557
+ .option('source', { type: 'string', demandOption: true, describe: 'Source profile' })
558
+ .option('target', { type: 'string', demandOption: true, describe: 'Target profile (all dates)' })
559
+ .option('from', { type: 'string', default: '2w', describe: 'Source sys_updated_on UTC window: 2w, 14d or YYYY-MM-DD; not completion history' }),
560
+ handler: wrap(diffUpdateSets),
561
+ })
551
562
  .command({
552
563
  command: 'list',
553
564
  aliases: ['ls'],
package/src/output.js CHANGED
@@ -93,6 +93,7 @@ export class OutputWriter {
93
93
  constructor(opts = {}) {
94
94
  this.format = opts.format || FormatAuto;
95
95
  this.writer = opts.writer || process.stdout;
96
+ this.errorWriter = opts.errorWriter || process.stderr;
96
97
  this.jqFilter = opts.jqFilter || '';
97
98
  this.verbose = opts.verbose === true;
98
99
  this.raw = opts.raw === true;
@@ -289,14 +290,27 @@ export class OutputWriter {
289
290
  }
290
291
  }
291
292
 
292
- writeCSV(data, opts) {
293
- if (opts.summary && isTTY(this.writer)) {
294
- this.writer.write(opts.summary + '\n\n');
295
- }
293
+ writeCSV(data, _opts) {
294
+ // CSV stdout contains only the table, even on a terminal. Pagination is
295
+ // diagnostic output, not an extra row that spreadsheet readers must skip.
296
296
  if (Array.isArray(data)) {
297
297
  this.writeCSVTable(data);
298
298
  } else if (data && typeof data === 'object' && Array.isArray(data.records)) {
299
299
  this.writeCSVTable(data.records);
300
+ const page = data.pagination;
301
+ if (page?.hasMore === true) {
302
+ const count = data.records.length;
303
+ const total = Number.isSafeInteger(page.total) && page.total >= 0
304
+ ? ` of ${page.total}` : '';
305
+ const unknown = total ? '' : '; total unknown';
306
+ // List commands advance the requested window, including short pages.
307
+ // Do not guess an offset when the envelope lacks that context.
308
+ const nextOffset = Number.isSafeInteger(page.offset) && page.offset >= 0
309
+ && Number.isSafeInteger(page.limit) && page.limit > 0
310
+ && Number.isSafeInteger(page.offset + page.limit)
311
+ ? `; next offset ${page.offset + page.limit}` : '';
312
+ this.errorWriter.write(`CSV pagination: returned ${count}${total} records${unknown}; more available${nextOffset}.\n`);
313
+ }
300
314
  } else {
301
315
  this.writeCSVTable([data]);
302
316
  }
@@ -0,0 +1,228 @@
1
+ import { resolveSession } from './session.js';
2
+ import { errUsage } from './errors.js';
3
+
4
+ const idPattern = /^[a-f0-9]{32}$/i;
5
+ const raw = value => String(value?.value ?? value ?? '');
6
+ const fields = 'sys_id,name,state,parent,sys_updated_on';
7
+ const caveat = 'Window selects currently complete source sets by sys_updated_on, not completion-transition history. Context members are not readiness claims. Captured updates only: this does not compare current record values or establish deployment readiness. Exact payload comparison is conservative (no XML normalization).';
8
+
9
+ export function parseDiffWindow(value = '2w', now = new Date()) {
10
+ if (/^\d+[dw]$/.test(value)) {
11
+ const amount = Number(value.slice(0, -1));
12
+ if (!amount || amount > 36500) throw errUsage('Invalid --from window');
13
+ return new Date(now.getTime() - amount * (value.endsWith('w') ? 7 : 1) * 86400000).toISOString().slice(0, 19).replace('T', ' ');
14
+ }
15
+ if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
16
+ const date = new Date(`${value}T00:00:00Z`);
17
+ if (Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value) return `${value} 00:00:00`;
18
+ }
19
+ throw errUsage('--from must be a date (YYYY-MM-DD) or relative window (2w, 14d)');
20
+ }
21
+
22
+ // Strict envelopes and counts: SDK.list/aggregateCount intentionally have forgiving
23
+ // defaults unsuitable for proving absence. Use the same authenticated GET transport.
24
+ export async function readDiffTable(sdk, table, query, required, coverage, label) {
25
+ const entry = { source: label, table, query, status: 'error', fetched: 0, total: null };
26
+ coverage.push(entry);
27
+ const rows = [];
28
+ try {
29
+ const countParams = new URLSearchParams({ sysparm_count: 'true', sysparm_query: query });
30
+ const count = await sdk.request(`${sdk.baseURL}/api/now/stats/${table}?${countParams}`, { method: 'GET' });
31
+ const value = count?.result?.stats?.count;
32
+ if (value == null || !/^\d+$/.test(String(value))) throw new Error('Unreadable provider count');
33
+ entry.total = Number(value);
34
+ const seen = new Set();
35
+ for (let page = 0; rows.length < entry.total && page < 20; page++) {
36
+ const params = new URLSearchParams({ sysparm_query: `${query}${query ? '^' : ''}ORDERBYsys_id`, sysparm_fields: required.join(','), sysparm_display_value: 'false', sysparm_limit: '200', sysparm_offset: String(rows.length) });
37
+ const response = await sdk.request(`${sdk.baseURL}/api/now/table/${table}?${params}`, { method: 'GET' });
38
+ if (!Array.isArray(response?.result)) throw new Error('Unreadable record array');
39
+ if (!response.result.length) throw new Error('Pagination ended before provider count');
40
+ for (const row of response.result) {
41
+ if (required.some(key => !Object.hasOwn(row, key))) throw new Error('Required fields omitted (schema or ACL)');
42
+ if (!idPattern.test(raw(row.sys_id)) || seen.has(raw(row.sys_id))) throw new Error('Invalid or repeated record identity');
43
+ seen.add(raw(row.sys_id));
44
+ rows.push(row);
45
+ }
46
+ }
47
+ entry.fetched = rows.length;
48
+ if (rows.length !== entry.total) throw new Error('Page budget/count mismatch');
49
+ const after = await sdk.request(`${sdk.baseURL}/api/now/stats/${table}?${countParams}`, { method: 'GET' });
50
+ if (String(after?.result?.stats?.count) !== String(value)) throw new Error('Provider count changed during pagination');
51
+ entry.status = 'complete';
52
+ } catch (error) {
53
+ entry.fetched = rows.length;
54
+ entry.error = error.message;
55
+ entry.status = rows.length ? 'partial' : 'error';
56
+ }
57
+ return { rows, complete: entry.status === 'complete' };
58
+ }
59
+
60
+ function profileSDK(app, name) {
61
+ const session = resolveSession({ profile: name }, app.config);
62
+ if (session.unknownProfile || !session.profile || !session.instance) throw errUsage(`Unknown or unconfigured profile: ${name}`);
63
+ return app.getSDKForProfile(session.instance, { profileName: name, profile: session.profile, username: session.username, authMethod: session.profile.auth_method, domain: session.domain });
64
+ }
65
+
66
+ async function contents(sdk, field, id, coverage, label) {
67
+ return readDiffTable(sdk, 'sys_update_xml', `${field}=${id}`, ['sys_id', 'name', 'action', 'payload', field], coverage, label);
68
+ }
69
+ function captureMap(rows) {
70
+ const map = new Map();
71
+ for (const row of rows) {
72
+ const key = raw(row.name);
73
+ if (!key || map.has(key) || !raw(row.payload)) return null;
74
+ // name is the stable customer-update artifact identity; sys_id, set refs,
75
+ // capture timestamps and updater belong to this instance's envelope.
76
+ map.set(key, JSON.stringify([raw(row.action), raw(row.payload)]));
77
+ }
78
+ return map;
79
+ }
80
+
81
+ export async function diffUpdateSets(argv, app) {
82
+ const from = parseDiffWindow(argv.from);
83
+ const source = profileSDK(app, argv.source);
84
+ const target = profileSDK(app, argv.target);
85
+ const coverage = [];
86
+ const selected = await readDiffTable(source, 'sys_update_set', `state=complete^sys_updated_on>=${from}`, fields.split(','), coverage, 'source selection');
87
+ const inventory = await readDiffTable(source, 'sys_update_set', '', fields.split(','), coverage, 'source hierarchy');
88
+ const remote = await readDiffTable(target, 'sys_remote_update_set', '', ['sys_id', 'name', 'state', 'remote_sys_id', 'update_set'], coverage, 'target all dates');
89
+ const all = new Map([...inventory.rows, ...selected.rows].map(row => [raw(row.sys_id), row]));
90
+ const selectedIDs = new Set(selected.rows.map(row => raw(row.sys_id)));
91
+ const included = new Set(selectedIDs);
92
+ const cycles = [];
93
+ for (const id of selectedIDs) {
94
+ let current = id;
95
+ const path = new Set();
96
+ while (current && all.has(current)) {
97
+ if (path.has(current)) { cycles.push(current); break; }
98
+ path.add(current); included.add(current);
99
+ current = raw(all.get(current).parent);
100
+ }
101
+ }
102
+ // Include every member sharing an observed ancestor, including older and
103
+ // incomplete members; fixed point handles nested children without recursion.
104
+ for (let pass = 0; pass < all.size; pass++) {
105
+ let changed = false;
106
+ for (const [id, row] of all) if (!included.has(id) && included.has(raw(row.parent))) { included.add(id); changed = true; }
107
+ if (!changed) break;
108
+ }
109
+ const sets = [];
110
+ for (const id of included) {
111
+ const row = all.get(id);
112
+ let base = id;
113
+ const ancestors = new Set();
114
+ while (all.has(base) && raw(all.get(base).parent)) {
115
+ if (ancestors.has(base)) { base = '(cycle)'; break; }
116
+ ancestors.add(base);
117
+ base = raw(all.get(base).parent);
118
+ }
119
+ if (!all.has(base) && base !== '(cycle)') base = `(unreadable ${base})`;
120
+ const result = { sys_id: id, name: raw(row.name), state: raw(row.state), parent: raw(row.parent), base, context: !selectedIDs.has(id), status: 'Unknown', evidence: [] };
121
+ result.base_name = all.has(base) ? raw(all.get(base).name) : null;
122
+ result.parent_name = all.has(result.parent) ? raw(all.get(result.parent).name) : null;
123
+ result.group = !result.parent && ![...all.values()].some(member => raw(member.parent) === id) ? 'standalone' : 'batch';
124
+ result.capture_counts = { source: null, target: null };
125
+ sets.push(result);
126
+ if (result.context) { result.evidence.push('Hierarchy context only; not selected for comparison'); continue; }
127
+ if (!selected.complete || !remote.complete) { result.evidence.push('Incomplete source selection or target inventory'); continue; }
128
+ const a = await contents(source, 'update_set', id, coverage, `source contents ${id}`);
129
+ result.capture_counts.source = a.complete ? a.rows.length : null;
130
+ const left = captureMap(a.rows);
131
+ if (!a.complete || !left) { result.evidence.push('Incomplete or ambiguous source captured contents'); continue; }
132
+ const candidates = remote.rows.filter(candidate => raw(candidate.remote_sys_id) === id);
133
+ result.candidates = candidates.map(candidate => ({ sys_id: raw(candidate.sys_id), state: raw(candidate.state), update_set: raw(candidate.update_set) }));
134
+ if (!candidates.length) { result.status = 'Missing'; result.evidence.push('Complete target inventory: no remote_sys_id matches source sys_id'); continue; }
135
+ if (candidates.length !== 1) { result.evidence.push('Ambiguous origin identity'); continue; }
136
+ const candidate = candidates[0];
137
+ if (raw(candidate.state) !== 'committed') { result.status = 'Retrieved not committed'; result.evidence.push(`Target retrieved state: ${raw(candidate.state) || '(empty)'}`); continue; }
138
+ const b = await contents(target, 'remote_update_set', raw(candidate.sys_id), coverage, `target contents ${raw(candidate.sys_id)}`);
139
+ result.capture_counts.target = b.complete ? b.rows.length : null;
140
+ const right = captureMap(b.rows);
141
+ if (!a.complete || !b.complete || !left || !right) { result.evidence.push('Incomplete or ambiguous captured contents'); continue; }
142
+ result.changes = [...new Set([...left.keys(), ...right.keys()])].filter(key => left.get(key) !== right.get(key)).map(name => ({ name, source: left.has(name), target: right.has(name) }));
143
+ result.status = result.changes.length ? 'Different' : 'Matching';
144
+ result.evidence.push('Origin remote_sys_id equals source sys_id; committed retrieved state; count-verified captured name/action/payload comparison');
145
+ }
146
+ const report = { source: argv.source, target: argv.target, from, date_basis: 'sys_updated_on (UTC)', caveat, coverage, hierarchy_cycles: [...new Set(cycles)], sets };
147
+ const formatted = formatUpdateSetDiff(report, argv);
148
+ Object.defineProperty(report, '_formatted', { value: formatted, enumerable: false });
149
+ app.ok(report, { summary: 'Captured update-set comparison' });
150
+ return report;
151
+ }
152
+
153
+ // Pure production renderer also supports replaying a saved report without instance reads.
154
+ export function formatUpdateSetDiff(report, { verbose = false } = {}) {
155
+ const { sets, coverage } = report;
156
+ if (verbose) {
157
+ const lines = [`Update sets: ${report.source} → ${report.target} (since ${report.from} UTC)`, report.caveat];
158
+ if (!sets.filter(set => !set.context).length) lines.push(report.coverage.find(entry => entry.source === 'source selection')?.status === 'complete' ? 'No selected sets: no currently complete source sets in this window.' : 'Source selection unreadable or incomplete; absence of selected sets is not established.');
159
+ const grouped = [...sets].sort((a, b) => a.group.localeCompare(b.group) || a.base.localeCompare(b.base) || a.parent.localeCompare(b.parent) || a.sys_id.localeCompare(b.sys_id));
160
+ let heading;
161
+ for (const set of grouped) {
162
+ const group = set.group === 'standalone' ? 'Standalone update sets' : `Batch: ${set.base_name || set.base} [${set.base}]`;
163
+ if (heading !== group) { lines.push('', group); heading = group; }
164
+ lines.push(` ${set.name} — ${set.status}${set.context ? ' (context only)' : ''}`, ` Source state: ${set.state}; parent: ${set.parent ? (set.parent_name || `unreadable ${set.parent}`) : '(none)'}`, ` Captures: source ${set.capture_counts.source ?? 'unknown'} / target ${set.capture_counts.target ?? 'unknown'}`, ` ${set.evidence.join('; ')}`);
165
+ lines.push(` Source ID: ${set.sys_id}; parent ID: ${set.parent || '(none)'}`);
166
+ for (const candidate of set.candidates || []) lines.push(` Target candidate: ${candidate.sys_id}; state: ${candidate.state}; update set: ${candidate.update_set || '(none)'}`);
167
+ for (const change of set.changes || []) lines.push(` ${change.name}: ${!change.target ? 'missing-in-target' : !change.source ? 'target-only' : 'content differs'}`);
168
+ }
169
+ for (const entry of coverage) lines.push(`Coverage ${entry.source}: ${entry.status} — ${entry.fetched}/${entry.total ?? '?'}${entry.error ? ` — ${entry.error}` : ''}`);
170
+ if (report.hierarchy_cycles.length) lines.push(`Hierarchy cycles: ${report.hierarchy_cycles.join(', ')}`);
171
+ return lines.join('\n');
172
+ }
173
+ const labels = { Matching: 'Committed, matching', Missing: 'Missing in target', 'Retrieved not committed': 'Loaded, not committed', Different: 'Content differs', Unknown: 'Unable to verify' };
174
+ const lines = [`${report.source} → ${report.target} · since ${report.from} UTC`, 'Complete source sets last updated in this window. Captured updates, not deployment readiness.'];
175
+ const selected = sets.filter(set => !set.context);
176
+ if (!selected.length) lines.push(coverage.find(entry => entry.source === 'source selection')?.status === 'complete'
177
+ ? 'No selected sets: no currently complete source sets in this window.'
178
+ : 'Source selection unreadable or incomplete; retry with --verbose to inspect coverage.');
179
+ const groups = new Map();
180
+ for (const set of sets) {
181
+ const key = set.group === 'standalone' ? 'standalone' : set.base;
182
+ if (!groups.has(key)) groups.set(key, []);
183
+ groups.get(key).push(set);
184
+ }
185
+ for (const members of groups.values()) {
186
+ const first = members[0];
187
+ lines.push('', first.group === 'standalone' ? 'Standalone update sets' : `Batch: ${first.base_name || '(unreadable batch)'}`);
188
+ const ids = new Set(members.map(set => set.sys_id));
189
+ const children = new Map();
190
+ for (const set of members) {
191
+ if (!children.has(set.parent)) children.set(set.parent, []);
192
+ children.get(set.parent).push(set);
193
+ }
194
+ const visited = new Set();
195
+ const render = root => {
196
+ const pending = [{ set: root, depth: 0 }];
197
+ while (pending.length) {
198
+ const { set, depth, last = true } = pending.pop();
199
+ if (visited.has(set.sys_id)) continue;
200
+ visited.add(set.sys_id);
201
+ const indent = ' '.repeat(depth + 1);
202
+ lines.push(`${indent}${depth ? (last ? '└─ ' : '├─ ') : ''}${set.name} — ${set.context ? `Context only (${set.state})` : labels[set.status] || labels.Unknown}`);
203
+ if (!set.context && set.status === 'Different') {
204
+ for (const change of set.changes || []) lines.push(`${indent} ${change.name}: ${!change.target ? 'missing-in-target' : !change.source ? 'target-only' : 'content differs'}`);
205
+ }
206
+ if (!set.context && set.status === 'Unknown') {
207
+ const reason = set.evidence?.[0] || 'Comparison evidence unavailable';
208
+ lines.push(`${indent} ${reason}; inspect --verbose and retry after resolving it.`);
209
+ }
210
+ const descendants = children.get(set.sys_id) || [];
211
+ for (let i = descendants.length - 1; i >= 0; i--) pending.push({ set: descendants[i], depth: depth + 1, last: i === descendants.length - 1 });
212
+ }
213
+ };
214
+ // Root-first traversal preserves provider order among siblings. A second pass
215
+ // covers cycles and missing ancestors once each, without recursion.
216
+ for (const set of members) if (!ids.has(set.parent)) render(set);
217
+ for (const set of members) render(set);
218
+ }
219
+ if (selected.length) {
220
+ const counts = new Map();
221
+ for (const set of selected) {
222
+ const label = labels[set.status] || labels.Unknown;
223
+ counts.set(label, (counts.get(label) || 0) + 1);
224
+ }
225
+ lines.push('', [...counts].map(([label, count]) => `${count} ${label}`).join(' · '));
226
+ }
227
+ return lines.join('\n');
228
+ }