@jacebenson/jsn 5.5.10-dev.236.1 → 5.5.10-dev.237.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.10-dev.236.1",
3
+ "version": "5.5.10-dev.237.1",
4
4
  "description": "A command-line interface for ServiceNow that follows the Unix philosophy: simple, composable, and scriptable.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/app.js CHANGED
@@ -15,6 +15,7 @@ import { saveConfig, isTrustedCredentialDestination } from './config.js';
15
15
  import { resolveSession, applySession, contextFromSession, requireSessionInstance } from './session.js';
16
16
  import { errUsage, errAuth } from './errors.js';
17
17
  import { canPrompt, canUsePicker } from './helpers.js';
18
+ import { queryDiagnostics, invalidateAfterMutation } from './query-validate.js';
18
19
  import { guardMutationContext } from './mutation-context.js';
19
20
 
20
21
 
@@ -64,6 +65,7 @@ export class App {
64
65
  recovery: createAuthRecovery({ app: this, session }),
65
66
  canInteract: () => canUsePicker(this, this._authArgv || {}),
66
67
  });
68
+ this.sdk.afterMetadataMutation = table => invalidateAfterMutation(this, table);
67
69
  }
68
70
 
69
71
  /** Build a profile-scoped SDK without leaking auth construction to commands. */
@@ -93,6 +95,9 @@ export class App {
93
95
  }
94
96
 
95
97
  ok(data, opts = {}) {
98
+ const diagnostics = queryDiagnostics(this.queryValidation);
99
+ if (diagnostics.query_validation && data && typeof data === 'object' && !Array.isArray(data)) data = Object.assign(data, diagnostics);
100
+ else if (diagnostics.query_validation) opts = { ...opts, meta: { ...opts.meta, ...diagnostics } };
96
101
  this.output.ok(data, this.mutationContext ? { ...opts, context: { ...opts.context, mutation: this.mutationContext } } : opts);
97
102
  }
98
103
 
package/src/cli.js CHANGED
@@ -12,7 +12,7 @@ import { resolveSession, applySession } from './session.js';
12
12
  import { renderHelp, renderTips } from './help.js';
13
13
  import { isMutationCommand, refreshMutationCommands } from './mutations.js';
14
14
  import { maybeShowHome } from './welcome.js';
15
- import { isLocalPreview, noInstanceCommands, dailyCheckSkipCommands } from './capabilities.js';
15
+ import { isLocalPreview, noInstanceCommands, dailyCheckSkipCommands, collectCapabilities } from './capabilities.js';
16
16
  import { guardExit, exitWithError, AppError, CodeUsage } from './errors.js';
17
17
  import { formatCommandList } from './helpers.js';
18
18
 
@@ -116,6 +116,8 @@ export function resolveRequestedFormat(argv) {
116
116
  */
117
117
  const DISCOVERY_OWNED_ELSEWHERE = new Set(['auth', 'perf', 'skill', 'groupmembers', 'grouproles']);
118
118
 
119
+ import { validateReadQuery, assertWriteQuery } from './query-validate.js';
120
+
119
121
  function wrap(handler) {
120
122
  return async (argv) => {
121
123
  try {
@@ -124,6 +126,14 @@ function wrap(handler) {
124
126
  process.stderr.write('Error: App context not initialized.\n');
125
127
  process.exit(1);
126
128
  }
129
+ const caps = collectCapabilities().get(argv._?.[0]) || {};
130
+ app.queryValidation = null;
131
+ if (((typeof argv.query === 'string' && argv.query.trim()) || caps.filteredMutationSubcommands?.includes(argv._?.[1]))
132
+ && !caps.noInstance && caps.encodedQuery !== false) {
133
+ const target = typeof caps.queryTable === 'function' ? caps.queryTable(argv) : caps.queryTable || caps.table || argv.table;
134
+ const options = { table: target, query: argv.query, refresh: argv['refresh-metadata'] };
135
+ app.queryValidation = await (isMutationCommand(argv) ? assertWriteQuery : validateReadQuery)(app, options);
136
+ }
127
137
  await app.guardMutationContext(argv);
128
138
  await handler(argv, app);
129
139
  } catch (err) {
@@ -150,6 +160,7 @@ export function buildCLI() {
150
160
  },
151
161
  ])
152
162
  .options({
163
+ 'refresh-metadata': { type: 'boolean', describe: 'Refresh query metadata instead of reusing the five-minute cache' },
153
164
  'all-commands': { type: 'boolean', describe: 'Show the full command list, including admin and developer tools' },
154
165
 
155
166
  'expect-scope': { type: 'string', description: 'Intended customization scope, exact scope/name or sys_id' },
@@ -13,7 +13,7 @@ export const flowsCmdDefinition = {
13
13
  aliases: ['flow'],
14
14
  describe: 'Manage Flow Designer flows',
15
15
  };
16
- declareCapabilities('flows', { transactionScopeOption: 'scope', mutationContextExemptSubcommands: ['test', 'unlock'], mutationSubcommands: ['clone', 'copy', 'create', 'update', 'edit', 'delete', 'publish', 'test', 'unlock'] });
16
+ declareCapabilities('flows', { queryTable: argv => argv._?.[1] === 'executions' ? 'sys_flow_context' : 'sys_hub_flow', transactionScopeOption: 'scope', mutationContextExemptSubcommands: ['test', 'unlock'], mutationSubcommands: ['clone', 'copy', 'create', 'update', 'edit', 'delete', 'publish', 'test', 'unlock'] });
17
17
  export const flowsCmd = wrap => ({ ...flowsCmdDefinition, load: () => require('./commands/flows.js').flowsCmd(wrap) });
18
18
 
19
19
  export const workflowsCmdDefinition = {
@@ -21,7 +21,7 @@ export const workflowsCmdDefinition = {
21
21
  aliases: ['workflow'],
22
22
  describe: 'Inspect legacy Workflow Editor workflows (read-only)',
23
23
  };
24
- declareCapabilities('workflows', { mutationSubcommands: [] });
24
+ declareCapabilities('workflows', { queryTable: 'wf_workflow', mutationSubcommands: [] });
25
25
  export const workflowsCmd = wrap => ({ ...workflowsCmdDefinition, load: () => require('./commands/workflows.js').workflowsCmd(wrap) });
26
26
 
27
27
  export const midserversCmdDefinition = {
@@ -29,7 +29,7 @@ export const midserversCmdDefinition = {
29
29
  aliases: ['midserver', 'mid'],
30
30
  describe: 'Manage ServiceNow MID Servers and run commands through them',
31
31
  };
32
- declareCapabilities('midservers', { mutationContext: 'operational', mutationSubcommands: ['add', 'remove', 'execute', 'start', 'stop', 'validate'] });
32
+ declareCapabilities('midservers', { queryTable: 'ecc_agent', mutationContext: 'operational', mutationSubcommands: ['add', 'remove', 'execute', 'start', 'stop', 'validate'] });
33
33
  export const midserversCmd = wrap => ({ ...midserversCmdDefinition, load: () => require('./commands/midservers.js').midserversCmd(wrap) });
34
34
 
35
35
  export const subscriptionsCmdDefinition = {
@@ -4,6 +4,7 @@ import { enrichRelatedLists, relatedListOptions } from '../related-lists.js';
4
4
 
5
5
  import { formatRecordForDisplay, findOmittedColumns, getStringField, buildRecordPayload, confirmDelete, interactiveList, canPrompt } from '../helpers.js';
6
6
  import { getRecord, listRecords, recordListParams, createRecord, updateRecord, deleteRecord, recordOptions } from '../records-engine.js';
7
+ import { validateReadQuery, queryDiagnostics, invalidateAfterMutation } from '../query-validate.js';
7
8
  import { unwrapSysId } from '../resolve-record.js';
8
9
  import { getCurrentUser, getCurrentApplication } from '../context.js';
9
10
  import { FormatAuto } from '../output.js';
@@ -135,6 +136,7 @@ export function buildDevCmd(name, table, aliases, defaultColumns, wrap, opts = {
135
136
  handler: wrap(async (argv, app) => {
136
137
  const query = argv.query || '';
137
138
  const constrainedQuery = constrainQuery(query, extraQuery);
139
+ const verdict = await validateReadQuery(app, { table, query, refresh: argv['refresh-metadata'] });
138
140
  const columns = argv.columns ? argv.columns.split(',') : defaultColumns;
139
141
  const limit = argv.limit;
140
142
 
@@ -186,6 +188,7 @@ export function buildDevCmd(name, table, aliases, defaultColumns, wrap, opts = {
186
188
  } : {}),
187
189
  records: argv.displayValues || opts.listProjection === 'full' ? records : records.map(r => formatRecordForDisplay(r, presentColumns)),
188
190
  context: { instance_url: app.getEffectiveInstance() },
191
+ ...queryDiagnostics(verdict),
189
192
  }, {
190
193
  summary: `${records.length} ${name}(s)`,
191
194
  breadcrumbs: buildHints(name, singular, readOnly),
@@ -243,6 +246,7 @@ export function buildDevCmd(name, table, aliases, defaultColumns, wrap, opts = {
243
246
  handler: wrap(async (argv, app) => {
244
247
  const recordData = buildRecordPayload(argv);
245
248
  const record = await createRecord(app.sdk, { table, data: recordData });
249
+ invalidateAfterMutation(app, table);
246
250
  app.ok(record, {
247
251
  summary: `Created ${singular}`,
248
252
  breadcrumbs: [
@@ -270,6 +274,7 @@ export function buildDevCmd(name, table, aliases, defaultColumns, wrap, opts = {
270
274
  const sysID = unwrapSysId(record);
271
275
  const recordData = buildRecordPayload(argv);
272
276
  const updated = await updateRecord(app.sdk, { table, record: { sys_id: sysID }, data: recordData });
277
+ invalidateAfterMutation(app, table);
273
278
  app.ok(updated, { summary: `Updated ${singular} ${id}` });
274
279
  }),
275
280
  })
@@ -290,6 +295,7 @@ export function buildDevCmd(name, table, aliases, defaultColumns, wrap, opts = {
290
295
  await confirmDelete(app, argv, `Delete ${singular} '${recordName}'`);
291
296
 
292
297
  await deleteRecord(app.sdk, { table, record: { sys_id: sysID } });
298
+ invalidateAfterMutation(app, table);
293
299
  app.ok({ name: recordName, sys_id: sysID, deleted: true }, { summary: `Deleted ${singular} '${recordName}'` });
294
300
  }),
295
301
  });
@@ -4,6 +4,7 @@ import { enrichRelatedLists, relatedListOptions } from '../related-lists.js';
4
4
 
5
5
  import { getStringField, formatRecordForDisplay, findOmittedColumns, buildQuerySuffix, resolveFieldsParam, confirmDelete, interactiveList, canPrompt, buildRecordPayload } from '../helpers.js';
6
6
  import { getRecord, listRecords, recordListParams, createRecord, updateRecord, deleteRecord, recordOptions } from '../records-engine.js';
7
+ import { validateReadQuery, queryDiagnostics, invalidateAfterMutation } from '../query-validate.js';
7
8
  import { resolveSysId } from '../resolve-record.js';
8
9
  import { FormatAuto } from '../output.js';
9
10
  import { declareCapabilities } from '../capabilities.js';
@@ -11,7 +12,7 @@ import { declareCapabilities } from '../capabilities.js';
11
12
  export function buildTicketCommands(table, displayName, alias, defaultColumns, stateMap, iconFn, wrap, opts = {}) {
12
13
  // Ticket-style CRUD: list/show are reads; create/update/delete mutate.
13
14
  // Root-level command only.
14
- declareCapabilities(displayName, { mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
15
+ declareCapabilities(displayName, { queryTable: table, mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
15
16
  return {
16
17
  command: `${displayName} [subcommand]`,
17
18
  aliases: [table, alias],
@@ -30,6 +31,7 @@ export function buildTicketCommands(table, displayName, alias, defaultColumns, s
30
31
  .option('offset', { alias: 'o', type: 'number', default: 0, describe: 'Offset for pagination' }),
31
32
  handler: wrap(async (argv, app) => {
32
33
  const query = argv.query || '';
34
+ const verdict = await validateReadQuery(app, { table, query, refresh: argv['refresh-metadata'] });
33
35
  const columns = argv.columns ? argv.columns.split(',') : defaultColumns;
34
36
  const limit = argv.limit;
35
37
  const offset = argv.offset;
@@ -125,6 +127,7 @@ export function buildTicketCommands(table, displayName, alias, defaultColumns, s
125
127
  records: displayRecords,
126
128
  pagination: { limit, offset, hasMore: records.length === limit },
127
129
  context: { instance_url: app.getEffectiveInstance() },
130
+ ...queryDiagnostics(verdict),
128
131
  }, {
129
132
  summary: `${records.length} ${table}(s)`,
130
133
  breadcrumbs,
@@ -175,6 +178,7 @@ export function buildTicketCommands(table, displayName, alias, defaultColumns, s
175
178
  throw new Error('short_description is required (use --description, -f short_description=..., or --data)');
176
179
  }
177
180
  const record = await createRecord(app.sdk, { table, data: recordData });
181
+ invalidateAfterMutation(app, table);
178
182
  app.ok(record, {
179
183
  summary: `Created ${displayName} ${getStringField(record, 'number')}`,
180
184
  breadcrumbs: [
@@ -196,6 +200,7 @@ export function buildTicketCommands(table, displayName, alias, defaultColumns, s
196
200
  const recordData = buildRecordPayload(argv);
197
201
  const sysID = await resolveSysId(app.sdk, { table, identifier: number, identifierField: argv.identifierField, displayValues: argv.displayValues ?? opts.referenceMode, matchField: opts.identifierField || 'number', resource: displayName });
198
202
  const updated = await updateRecord(app.sdk, { table, record: { sys_id: sysID }, data: recordData });
203
+ invalidateAfterMutation(app, table);
199
204
  app.ok(updated, {
200
205
  summary: `Updated ${displayName} ${number}`,
201
206
  breadcrumbs: [
@@ -213,6 +218,7 @@ export function buildTicketCommands(table, displayName, alias, defaultColumns, s
213
218
  await confirmDelete(app, argv, `Delete ${displayName} ${number}`);
214
219
  const sysID = await resolveSysId(app.sdk, { table, identifier: number, identifierField: argv.identifierField, displayValues: argv.displayValues ?? opts.referenceMode, matchField: opts.identifierField || 'number', resource: displayName });
215
220
  await deleteRecord(app.sdk, { table, record: { sys_id: sysID } });
221
+ invalidateAfterMutation(app, table);
216
222
  app.ok({ number, message: `${displayName.charAt(0).toUpperCase() + displayName.slice(1)} deleted` }, {
217
223
  summary: `Deleted ${displayName} ${number}`,
218
224
  });
@@ -25,7 +25,7 @@ import { errUsage, errNotFound } from '../errors.js';
25
25
  import { declareCapabilities } from '../capabilities.js';
26
26
 
27
27
  // approve/reject/submit change approval state on records.
28
- declareCapabilities('approvals', { mutationContext: 'operational', mutationSubcommands: ['approve', 'reject', 'submit'] });
28
+ declareCapabilities('approvals', { queryTable: 'sysapproval_approver', mutationContext: 'operational', mutationSubcommands: ['approve', 'reject', 'submit'] });
29
29
 
30
30
  // Raw sysapproval_approver.state values (verified live).
31
31
  const APPROVAL_STATES = [
@@ -27,7 +27,7 @@ import { errUsage, errNotFound } from '../errors.js';
27
27
  import { declareCapabilities } from '../capabilities.js';
28
28
 
29
29
  // run/run-suite schedule tests that act on records (top-level only).
30
- declareCapabilities('atf', { mutationContext: 'operational', mutationSubcommands: ['run', 'run-suite'] });
30
+ declareCapabilities('atf', { queryTable: argv => argv._?.[1] === 'suites' ? 'sys_atf_test_suite' : 'sys_atf_test', mutationContext: 'operational', mutationSubcommands: ['run', 'run-suite'] });
31
31
 
32
32
  // sn_cicd progress statuses (now-sdk poller.ts)
33
33
  const PROGRESS_PENDING = '0';
@@ -7,6 +7,7 @@
7
7
  import { AppError, CodeForbidden, errUsage, errUsageHint } from '../errors.js';
8
8
  import { buildQuerySuffix, formatCommandList, formatRecordForDisplay, getStringField, quoteShellArg, resolveFieldsParam } from '../helpers.js';
9
9
  import { getRecord, listRecords, recordListParams } from '../records-engine.js';
10
+ import { validateReadQuery, queryDiagnostics } from '../query-validate.js';
10
11
  import { declareCapabilities } from '../capabilities.js';
11
12
 
12
13
  declareCapabilities('cases', {}); // read-only: no mutating subcommands
@@ -87,6 +88,7 @@ async function resolveTable(app, argv) {
87
88
  async function listCases(app, argv, resolved, query) {
88
89
  const columns = argv.columns ? argv.columns.split(',') : DEFAULT_COLUMNS;
89
90
  const fields = resolveFieldsParam(columns);
91
+ const verdict = await validateReadQuery(app, { table: resolved.table, query });
90
92
  const ordered = query ? `${query}^ORDERBYDESCsys_updated_on` : 'ORDERBYDESCsys_updated_on';
91
93
  const params = recordListParams({ limit: argv.limit, offset: argv.offset, fields, query: ordered });
92
94
  let records;
@@ -114,6 +116,7 @@ async function listCases(app, argv, resolved, query) {
114
116
  records: displayRecords,
115
117
  pagination: { limit: argv.limit, offset: argv.offset, hasMore: records.length === argv.limit },
116
118
  context: { instance_url: app.getEffectiveInstance() },
119
+ ...queryDiagnostics(verdict),
117
120
  }, { summary: `${records.length} ${resolved.table}(s)`, breadcrumbs });
118
121
  }
119
122
 
@@ -4,7 +4,7 @@ import { resolveSysId } from '../resolve-record.js';
4
4
  import { declareCapabilities } from '../capabilities.js';
5
5
  import { enrichCatalogItem, buildCatalogFormatted } from './catalog/enrich.js';
6
6
 
7
- declareCapabilities('catalogitems', { mutationSubcommands: ['create', 'order'], mutationContextExemptSubcommands: ['order'], localPreviewSubcommands: ['order'] });
7
+ declareCapabilities('catalogitems', { queryTable: 'sc_cat_item', mutationSubcommands: ['create', 'order'], mutationContextExemptSubcommands: ['order'], localPreviewSubcommands: ['order'] });
8
8
 
9
9
  export function catalogCmd(wrap) {
10
10
  return {
@@ -15,6 +15,9 @@ import {
15
15
  resolveFieldsParam,
16
16
  } from '../helpers.js';
17
17
  import { errNotFound, errUsage } from '../errors.js';
18
+ import { declareCapabilities } from '../capabilities.js';
19
+ declareCapabilities('cmdb', { queryTable: 'cmdb_ci' });
20
+
18
21
  import { cmdbSearchCmd } from './cmdb-search.js';
19
22
 
20
23
  const SYS_ID_RE = /^[0-9a-f]{32}$/i;
@@ -9,7 +9,7 @@ import { declareCapabilities } from '../capabilities.js';
9
9
  export const decisiontablesCmd = (wrap) => {
10
10
  const name = 'decisiontables';
11
11
  const singular = 'decision table';
12
- declareCapabilities(name, { mutationSubcommands: ['create', 'update', 'delete'] });
12
+ declareCapabilities(name, { queryTable: 'sys_decision', mutationSubcommands: ['create', 'update', 'delete'] });
13
13
 
14
14
  const readData = (argv) => {
15
15
  if (argv.dataFile) return fs.readFileSync(argv.dataFile, 'utf8');
@@ -6,7 +6,7 @@ import { getStringField, interactiveList, assertSafeExactMatch } from '../helper
6
6
  import { declareCapabilities } from '../capabilities.js';
7
7
 
8
8
  // `domains set` writes the chosen domain into the profile config.
9
- declareCapabilities('domains', { mutationContext: 'operational', mutationSubcommands: ['set', 'session-set', 'session-reset'] });
9
+ declareCapabilities('domains', { queryTable: 'domain', mutationContext: 'operational', mutationSubcommands: ['set', 'session-set', 'session-reset'] });
10
10
 
11
11
  const DETAIL_FIELDS = 'sys_id,name,parent,sys_domain_path,description,active,sys_created_on,sys_updated_on';
12
12
 
@@ -3,7 +3,7 @@ import { declareCapabilities } from '../capabilities.js';
3
3
 
4
4
  // GraphQL documents may contain mutations. Gate the whole command so normal
5
5
  // instance/auth and read-only protections apply without attempting AST parsing.
6
- declareCapabilities('graphql', { mutationSubcommands: [''] });
6
+ declareCapabilities('graphql', { encodedQuery: false, mutationSubcommands: [''] });
7
7
 
8
8
  function readStdin() {
9
9
  return new Promise((resolve, reject) => {
@@ -3,7 +3,7 @@ import { declareCapabilities } from '../capabilities.js';
3
3
 
4
4
  // add/remove write sys_user_grmember; the mutation guard (instance +
5
5
  // read-only profile) and the delete confirmation both key off this.
6
- declareCapabilities('groupmembers', { mutationContext: 'operational', mutationSubcommands: ['add', 'remove'] });
6
+ declareCapabilities('groupmembers', { queryTable: 'sys_user_grmember', mutationContext: 'operational', mutationSubcommands: ['add', 'remove'] });
7
7
 
8
8
  export function groupMembersCmd(wrap) {
9
9
  return {
@@ -3,7 +3,7 @@ import { declareCapabilities } from '../capabilities.js';
3
3
 
4
4
  // add/remove write sys_group_has_role; the mutation guard (instance +
5
5
  // read-only profile) and the delete confirmation both key off this.
6
- declareCapabilities('grouproles', { mutationContext: 'operational', mutationSubcommands: ['add', 'remove'] });
6
+ declareCapabilities('grouproles', { queryTable: 'sys_group_has_role', mutationContext: 'operational', mutationSubcommands: ['add', 'remove'] });
7
7
 
8
8
  export function groupRolesCmd(wrap) {
9
9
  return {
@@ -1,7 +1,7 @@
1
1
  import { formatRecordForDisplay, getStringField, interactiveList, resolveFieldsParam, assertSafeExactMatch, buildRecordPayload } from '../helpers.js';
2
2
  import { declareCapabilities } from '../capabilities.js';
3
3
 
4
- declareCapabilities('groups', { mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
4
+ declareCapabilities('groups', { queryTable: 'sys_user_group', mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
5
5
 
6
6
  export function groupsCmd(wrap) {
7
7
  return {
@@ -1,3 +1,6 @@
1
+ import { declareCapabilities } from '../capabilities.js';
2
+ declareCapabilities('logs', { queryTable: 'syslog' });
3
+
1
4
  import { formatRecordForDisplay, interactiveList, getStringField } from '../helpers.js';
2
5
 
3
6
  function logIcon(level) {
@@ -6,9 +6,11 @@ import { AmbClient } from '../amb.js';
6
6
  import { watchRecord } from '../record-watch.js';
7
7
  import { declareCapabilities } from '../capabilities.js';
8
8
  import { assertMutationRecordScope, assertMutationScope } from '../intended-context.js';
9
+ import { validateReadQuery, assertWriteQuery, queryDiagnostics, invalidateAfterMutation } from '../query-validate.js';
9
10
 
10
11
  declareCapabilities('records', {
11
12
  mutationContext: 'table',
13
+ filteredMutationSubcommands: ['delete-many', 'bulk'],
12
14
  mutationSubcommands: ['create', 'update', 'delete', 'delete-many', 'bulk'],
13
15
  });
14
16
 
@@ -95,6 +97,7 @@ export function recordsCmd(wrap) {
95
97
  .option('table', { type: 'string', demandOption: true, describe: 'Table name' })
96
98
  .option('sys-id', { type: 'string', describe: 'Record sys_id (filters to a single record)' })
97
99
  .option('query', { type: 'string', describe: 'Encoded query (e.g. "nameLIKEincident" or "active=true")' })
100
+ .option('refresh-metadata', { type: 'boolean', default: false, describe: 'Refresh table metadata used to validate --query (five-minute cache)' })
98
101
  .option('columns', { alias: ['c', 'fields'], type: 'string', describe: 'Comma-separated columns (e.g. "number,short_description")' })
99
102
  .option('limit', { type: 'number', default: 20, describe: 'Max records' })
100
103
  .option('offset', { type: 'number', default: 0, describe: 'Offset' })
@@ -115,6 +118,7 @@ export function recordsCmd(wrap) {
115
118
  const table = argv.table;
116
119
  const columns = argv.columns ? argv.columns.split(',') : getDefaultColumns(table);
117
120
  let query = argv.query || '';
121
+ const verdict = await validateReadQuery(app, { table, query: argv.query || '', refresh: argv['refresh-metadata'] });
118
122
 
119
123
  // If --sys-id is provided, append it to the query
120
124
  if (argv['sys-id']) {
@@ -208,6 +212,7 @@ export function recordsCmd(wrap) {
208
212
  records: displayRecords,
209
213
  pagination: { limit: argv.limit, offset: argv.offset, ...(total != null ? { total, hasMore: argv.offset + argv.limit < total } : {}) },
210
214
  context: { instance_url: app.getEffectiveInstance() },
215
+ ...queryDiagnostics(verdict),
211
216
  }, {
212
217
  summary: `${records.length} record(s) from ${table}${total != null ? ` of ${total}` : ''}`,
213
218
  breadcrumbs,
@@ -370,6 +375,7 @@ export function recordsCmd(wrap) {
370
375
  process.stderr.write(`⚠ ${w.hint}\n`);
371
376
  }
372
377
  const record = await createRecord(app.sdk, { table: argv.table, data: recordData });
378
+ invalidateAfterMutation(app, argv.table);
373
379
  const sysID = getStringField(record, 'sys_id');
374
380
  const mismatches = await verifyWriteBack(app, argv.table, sysID, recordData);
375
381
  for (const m of mismatches) {
@@ -403,6 +409,7 @@ export function recordsCmd(wrap) {
403
409
  const lookup = recordLookup(argv);
404
410
  const resolved = await getRecord(app.sdk, lookup);
405
411
  const record = await updateRecord(app.sdk, { table: argv.table, record: resolved, data: recordData });
412
+ invalidateAfterMutation(app, argv.table);
406
413
  const mismatches = await verifyWriteBack(app, argv.table, unwrapSysId(resolved), recordData);
407
414
  for (const m of mismatches) {
408
415
  process.stderr.write(`⚠ field "${m.field}" was not persisted (sent: "${m.sent}", got: "${m.got}")\n`);
@@ -426,6 +433,7 @@ export function recordsCmd(wrap) {
426
433
  const lookup = recordLookup(argv);
427
434
  await confirmDelete(app, argv, `Delete record from ${argv.table} (${lookup.identifier})`);
428
435
  const sysID = await deleteRecord(app.sdk, lookup);
436
+ invalidateAfterMutation(app, argv.table);
429
437
  app.ok({ message: 'Record deleted', table: argv.table, sys_id: sysID }, { summary: `Deleted record from ${argv.table}` });
430
438
  }),
431
439
  })
@@ -435,6 +443,7 @@ export function recordsCmd(wrap) {
435
443
  builder: (y) => y
436
444
  .option('table', { type: 'string', demandOption: true, describe: 'Table name' })
437
445
  .option('query', { type: 'string', describe: 'Required nonempty encoded query; use records delete for a single record' })
446
+ .option('refresh-metadata', { type: 'boolean', default: false, describe: 'Refresh table metadata before validating the filter (five-minute cache)' })
438
447
  .option('expect-count', { type: 'number', describe: 'Required for deletion: exact expected matching count' })
439
448
  .option('yes', { type: 'boolean', default: false, describe: 'Confirm deletion (requires --expect-count)' })
440
449
  .option('dry-run', { type: 'boolean', default: false, describe: 'Preview only, even with --yes' })
@@ -442,6 +451,8 @@ export function recordsCmd(wrap) {
442
451
  .epilogue('Without --yes, reports count and up to 10 sample records without writes.\nDeletion uses per-record Table API DELETE, then re-counts the query. Concurrent changes cannot be made atomic.'),
443
452
  handler: wrap(async (argv, app) => {
444
453
  if (!argv.query?.trim()) throw errUsage('--query must be nonempty. Use records delete for a single record.');
454
+ // Complete original filter validated before count/enumeration/scope reads or any write.
455
+ await assertWriteQuery(app, { table: argv.table, query: argv.query, refresh: argv['refresh-metadata'] });
445
456
  if (!Number.isSafeInteger(argv.limit) || argv.limit < 1) throw errUsage('--limit must be a positive safe integer.');
446
457
  const dryRun = !argv.yes || argv['dry-run'];
447
458
  const expected = argv['expect-count'];
@@ -509,6 +520,7 @@ export function recordsCmd(wrap) {
509
520
  builder: (y) => y
510
521
  .option('table', { type: 'string', demandOption: true, describe: 'Table name' })
511
522
  .option('query', { type: 'string', describe: 'Encoded query to constrain the aggregation' })
523
+ .option('refresh-metadata', { type: 'boolean', default: false, describe: 'Refresh table metadata used to validate --query (five-minute cache)' })
512
524
  .option('group-by', { type: 'string', describe: 'Comma-separated fields to group by' })
513
525
  .option('display-values', { type: 'string', choices: ['raw', 'display', 'both'], describe: 'Reference values: raw, display or both' })
514
526
  .option('count', { type: 'boolean', default: true, describe: 'Include record counts' })
@@ -519,6 +531,7 @@ export function recordsCmd(wrap) {
519
531
  .option('order-by', { type: 'string', describe: 'Comma-separated fields to order by' }),
520
532
  handler: wrap(async (argv, app) => {
521
533
  app.requireInstance();
534
+ const verdict = await validateReadQuery(app, { table: argv.table, query: argv.query || '', refresh: argv['refresh-metadata'] });
522
535
  const split = (value) => value ? value.split(',').map(v => v.trim()).filter(Boolean) : [];
523
536
  const options = {
524
537
  query: argv.query || '',
@@ -545,6 +558,7 @@ export function recordsCmd(wrap) {
545
558
  },
546
559
  ...result,
547
560
  context: { instance_url: app.getEffectiveInstance() },
561
+ ...queryDiagnostics(verdict),
548
562
  }, { summary: `Aggregated ${argv.table}${options.groupBy.length ? ` by ${options.groupBy.join(', ')}` : ''}` });
549
563
  }),
550
564
  })
@@ -554,6 +568,7 @@ export function recordsCmd(wrap) {
554
568
  builder: (y) => y
555
569
  .option('table', { type: 'string', demandOption: true, describe: 'Table name' })
556
570
  .option('query', { type: 'string', demandOption: true, describe: 'Encoded query selecting the records to update (e.g. "priority=1^state=1")' })
571
+ .option('refresh-metadata', { type: 'boolean', default: false, describe: 'Refresh table metadata before validating the filter (five-minute cache)' })
557
572
  .option('set', { type: 'string', describe: 'JSON object of fields to set' })
558
573
  .option('field', { alias: 'f', type: 'string', array: true, describe: 'Set a field as name=value; repeatable' })
559
574
  .option('dry-run', { type: 'boolean', default: true, describe: 'Preview the count + a sample without mutating (default)' })
@@ -562,6 +577,8 @@ export function recordsCmd(wrap) {
562
577
  .option('force', { type: 'boolean', default: false, describe: 'Skip confirmation (with --execute)' }),
563
578
  handler: wrap(async (argv, app) => {
564
579
  app.requireInstance();
580
+ // Validate the complete original filter before confirmation, count or any write.
581
+ await assertWriteQuery(app, { table: argv.table, query: argv.query, refresh: argv['refresh-metadata'] });
565
582
  const set = buildRecordPayload({ ...argv, data: argv.set }, { required: true });
566
583
  if (!argv['dry-run'] && !argv.execute) {
567
584
  argv.execute = true; // explicit --no-dry-run implies execute intent
@@ -2,7 +2,7 @@ import { declareCapabilities } from '../capabilities.js';
2
2
 
3
3
  // Raw REST passthrough — can hit any endpoint with any method, so the whole
4
4
  // command is a mutation surface on read-only profiles.
5
- declareCapabilities('rest', { mutationSubcommands: [''], mutationContextReadMethods: ['GET', 'HEAD', 'OPTIONS'] });
5
+ declareCapabilities('rest', { encodedQuery: false, mutationSubcommands: [''], mutationContextReadMethods: ['GET', 'HEAD', 'OPTIONS'] });
6
6
 
7
7
  export function restCmd(wrap) {
8
8
  return {
@@ -3,7 +3,7 @@ import { requireCurrentUserSysId, setCurrentApplication } from '../context.js';
3
3
  import { declareCapabilities } from '../capabilities.js';
4
4
  import { unwrapSysId } from '../resolve-record.js';
5
5
 
6
- declareCapabilities('scopes', { mutationSubcommands: ['create', 'set'], mutationContextExemptSubcommands: ['set'] });
6
+ declareCapabilities('scopes', { queryTable: 'sys_scope', mutationSubcommands: ['create', 'set'], mutationContextExemptSubcommands: ['set'] });
7
7
 
8
8
  /**
9
9
  * Resolve a scope identifier to a single sys_scope record.
@@ -14,7 +14,7 @@ import { declareCapabilities } from '../capabilities.js';
14
14
 
15
15
  // `scrapi create` builds a full Scripted REST API in one call (list/show are
16
16
  // reads). Registered at the root.
17
- declareCapabilities('scrapi', { transactionScopeOption: 'scope', mutationSubcommands: ['create'] });
17
+ declareCapabilities('scrapi', { queryTable: 'sys_ws_operation', transactionScopeOption: 'scope', mutationSubcommands: ['create'] });
18
18
 
19
19
  /**
20
20
  * Parse a --resource flag value of the form:
@@ -1,10 +1,11 @@
1
1
  import { enrichRelatedLists, relatedListOptions } from '../related-lists.js';
2
2
  import { formatRecordForDisplay, findOmittedColumns, getStringField, buildQuerySuffix, resolveFieldsParam, buildRecordPayload, confirmDelete } from '../helpers.js';
3
3
  import { getRecord, listRecords, recordListParams, createRecord, updateRecord, deleteRecord, recordOptions } from '../records-engine.js';
4
+ import { validateReadQuery, queryDiagnostics } from '../query-validate.js';
4
5
  import { resolveSysId } from '../resolve-record.js';
5
6
  import { declareCapabilities } from '../capabilities.js';
6
7
 
7
- declareCapabilities('tickets', { mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
8
+ declareCapabilities('tickets', { queryTable: 'task', mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
8
9
 
9
10
  export function ticketsCmd(wrap) {
10
11
  return {
@@ -25,6 +26,7 @@ export function ticketsCmd(wrap) {
25
26
  handler: wrap(async (argv, app) => {
26
27
  const columns = argv.columns ? argv.columns.split(',') : ['number', 'short_description', 'state', 'assigned_to'];
27
28
  const fields = resolveFieldsParam(columns);
29
+ const verdict = await validateReadQuery(app, { table: 'task', query: argv.query || '' });
28
30
  const q = argv.query ? argv.query + '^ORDERBYDESCsys_updated_on' : 'ORDERBYDESCsys_updated_on';
29
31
  const params = recordListParams({ limit: argv.limit, offset: argv.offset, fields, query: q });
30
32
  const records = await listRecords(app.sdk, { table: 'task', params, displayValues: argv.displayValues });
@@ -52,6 +54,7 @@ export function ticketsCmd(wrap) {
52
54
  table: 'task',
53
55
  count: records.length,
54
56
  columns,
57
+ ...queryDiagnostics(verdict),
55
58
  ...(missingColumns.length ? {
56
59
  missing_columns: missingColumns,
57
60
  warnings: [
@@ -103,6 +103,9 @@ function formatTopTransactions(groups) {
103
103
  return `${lines.join('\\n')}\\n`;
104
104
  }
105
105
 
106
+ import { declareCapabilities } from '../capabilities.js';
107
+ declareCapabilities('transactions', { queryTable: 'syslog_transaction' });
108
+
106
109
  export function topTransactionsCmd(wrap) {
107
110
  return {
108
111
  command: 'top',
@@ -13,7 +13,7 @@ import { resolveScope } from './scopes.js';
13
13
  import { unwrapSysId } from '../resolve-record.js';
14
14
  import { assertNoUnresolvedProblems, DEFAULT_OPERATION_TIMEOUT_MS } from '../update-set-apply.js';
15
15
 
16
- declareCapabilities('updatesets', {
16
+ declareCapabilities('updatesets', { queryTable: 'sys_update_set',
17
17
  mutationSubcommands: ['create', 'set', 'complete', 'ignore', 'parent', 'import', 'reopen', 'preview', 'commit'],
18
18
  mutationContextExemptSubcommands: ['create', 'set', 'import', 'reopen', 'preview', 'commit'],
19
19
  skipContextHeaderSubcommands: ['diff'],
@@ -2,7 +2,7 @@ import { formatRecordForDisplay, getStringField, interactiveList, resolveFieldsP
2
2
  import { resolveRecord, resolveSysId } from '../resolve-record.js';
3
3
  import { declareCapabilities } from '../capabilities.js';
4
4
 
5
- declareCapabilities('users', { mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
5
+ declareCapabilities('users', { queryTable: 'sys_user', mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
6
6
 
7
7
  export function usersCmd(wrap) {
8
8
  return {
package/src/output.js CHANGED
@@ -137,6 +137,9 @@ export class OutputWriter {
137
137
  }
138
138
 
139
139
  ok(data, opts = {}) {
140
+ if (!['json', 'quiet'].includes(this.effectiveFormat()) && !this.jqFilter) {
141
+ for (const warning of (data?.query_validation ? data.warnings : opts.meta?.warnings) || [] ) this.errorWriter.write(`Warning: ${warning}\n`);
142
+ }
140
143
  // --get extractor: resolve against the JSON envelope and print just that
141
144
  // value as JSON. Takes precedence over styling/table formats — a path
142
145
  // extract is inherently scriptable, not presentational.
@@ -176,6 +179,7 @@ export class OutputWriter {
176
179
  const format = this.effectiveFormat();
177
180
  const e = error.code ? error : { code: 'unknown', message: String(error), hint: '' };
178
181
  const resp = { ok: false, error: e.message, code: e.code, hint: e.hint || '' };
182
+ if (e.query_validation) resp.query_validation = e.query_validation;
179
183
  if (e.resolution) resp.resolution = e.resolution;
180
184
  if (e.context) resp.context = e.context;
181
185
  if (e.status === 401 || e.status === 403) resp.status = e.status;