@jacebenson/jsn 5.5.10-dev.235.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.
@@ -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
@@ -638,6 +655,10 @@ export function recordsCmd(wrap) {
638
655
  command: 'inspect <table> <identifier>',
639
656
  aliases: ['debug', 'diag'],
640
657
  describe: 'Inspect a record: show audit history, business rules, and running flows',
658
+ discoveryTasks: [{
659
+ phrases: ['record history', 'audit history', 'record changes', 'show record history', 'who changed a record'],
660
+ args: ['--json'], description: 'Inspect audit history for the specified table and record',
661
+ }],
641
662
  builder: (y) => y
642
663
  .positional('table', { describe: 'Table name (e.g. incident)', type: 'string' })
643
664
  .positional('identifier', { describe: 'Record sys_id or number', type: 'string' }),
@@ -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:
@@ -26,6 +26,11 @@ export function withTableBehavior(command, wrap) {
26
26
  command: 'behavior <table>',
27
27
  aliases: ['behaviour'],
28
28
  describe: 'Read-only inventory of tables behavior: rules, scripts, actions, policies, dictionary, notifications, ACLs, styles, views and flow triggers (inherited included)',
29
+ discoveryTasks: [{
30
+ phrases: ['inherited business rules', 'inherited rules', 'parent table business rules', 'business rules from ancestors'],
31
+ args: ['--category', 'business_rules', '--json'],
32
+ description: 'List business rules for the specified table, including inherited rules by default',
33
+ }],
29
34
  builder: (y) => y
30
35
  .positional('table', { type: 'string', describe: 'Table name (e.g. incident)' })
31
36
  .option('category', {
@@ -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: [
@@ -92,6 +95,11 @@ export function ticketsCmd(wrap) {
92
95
  .command({
93
96
  command: 'update <number>',
94
97
  describe: 'Update a ticket',
98
+ discoveryTasks: [{
99
+ phrases: ['write work note', 'write work notes', 'add work note', 'add work notes', 'append work notes', 'write a work note', 'add internal note'],
100
+ args: ['--field', 'work_notes=<text>', '--json'],
101
+ description: 'Write a work note to the specified ticket; replace the required number and text placeholders',
102
+ }],
95
103
  builder: (y) => recordOptions(y, false)
96
104
  .option('data', { type: 'string', describe: 'JSON fields' })
97
105
  .option('data-file', { type: 'string', describe: 'Read JSON payload from file' })
@@ -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;
@@ -0,0 +1,187 @@
1
+ // Five-minute metadata cache, isolated by instance + profile + authenticated
2
+ // principal + table. Only fully observed metadata is persisted; denied,
3
+ // unavailable and incomplete reads are never cached as fact.
4
+ //
5
+ // The cache is a latency tradeoff, not authorization: an ACL or schema change
6
+ // inside the TTL is not reflected, so every diagnostic says so.
7
+
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import crypto from 'node:crypto';
11
+ import { cacheDir } from './config.js';
12
+
13
+ export const DEFAULT_TTL_MS = 300_000;
14
+ const VERSION = 3;
15
+ export const QUERY_CACHE_LIMITS = Object.freeze({ entries: 64, entryBytes: 262144, bytes: 8388608 });
16
+ const TABLE = /^[a-zA-Z0-9_]+$/;
17
+
18
+ const digest = value => crypto.createHash('sha256').update(value).digest('hex');
19
+
20
+ export function identityKey(identity = {}, table = '') {
21
+ return digest([identity.instance || '', identity.profile || '', identity.principal || '', table].join('\n'));
22
+ }
23
+
24
+ function validIdentity(identity) {
25
+ return Boolean(identity && identity.instance && identity.principal && identity.principal !== 'guest');
26
+ }
27
+
28
+ function validPayload(payload) {
29
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)
30
+ || payload.complete !== true || payload.source !== 'table-api'
31
+ || !Number.isSafeInteger(payload.total) || payload.total <= 0 || payload.total >= 1000) return false;
32
+ if (payload.state !== 'observed') return false;
33
+ if (!Array.isArray(payload.hierarchy) || !payload.hierarchy.length || !payload.hierarchy.every(name => TABLE.test(name))) return false;
34
+ if (!payload.fields || typeof payload.fields !== 'object' || Array.isArray(payload.fields)) return false;
35
+ let count = 0;
36
+ for (const [owner, fields] of Object.entries(payload.fields)) {
37
+ if (!payload.hierarchy.includes(owner) || !fields || typeof fields !== 'object' || Array.isArray(fields)) return false;
38
+ for (const [element, definition] of Object.entries(fields)) {
39
+ if (!TABLE.test(element) || !definition || typeof definition !== 'object') return false;
40
+ if (typeof definition.type !== 'string' || !definition.type || definition.type === 'unknown'
41
+ || (definition.type === 'reference' && !definition.reference)) return false;
42
+ if (typeof definition.reference !== 'string' || (definition.reference && !TABLE.test(definition.reference))) return false;
43
+ count++;
44
+ }
45
+ }
46
+ return count === payload.total;
47
+ }
48
+
49
+ /**
50
+ * @param {{identity:{instance:string,profile:string,principal:string},
51
+ * ttlMs?:number, dir?:string}} options
52
+ */
53
+ export function createQueryMetadataCache({ identity = {}, ttlMs = DEFAULT_TTL_MS, dir = '', platform = process.platform } = {}) {
54
+ identity = { ...identity };
55
+ ttlMs = Math.min(DEFAULT_TTL_MS, Math.max(0, ttlMs));
56
+ const memory = new Map();
57
+ // Match flow-search policy: Node mode bits cannot prove Windows private DACLs.
58
+ const persist = platform !== 'win32' && validIdentity(identity);
59
+ const root = dir || path.join(cacheDir(), 'query-metadata');
60
+ const keyFor = table => identityKey(identity, table);
61
+ const fileFor = key => path.join(root, `${key}.json`);
62
+ function boundMemory() {
63
+ let bytes = 0;
64
+ for (const [table, entry] of [...memory].reverse()) {
65
+ bytes += Buffer.byteLength(JSON.stringify(entry.payload));
66
+ if (bytes > QUERY_CACHE_LIMITS.bytes) memory.delete(table);
67
+ }
68
+ while (memory.size > QUERY_CACHE_LIMITS.entries) memory.delete(memory.keys().next().value);
69
+ }
70
+
71
+
72
+ function readFile(table) {
73
+ if (!persist) return null;
74
+ const key = keyFor(table);
75
+ const file = fileFor(key);
76
+ try {
77
+ const parent = fs.lstatSync(root);
78
+ if (!parent.isDirectory() || (parent.mode & 0o077) || (process.getuid && parent.uid !== process.getuid())) return null;
79
+ const stat = fs.lstatSync(file);
80
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size > QUERY_CACHE_LIMITS.entryBytes
81
+ || (process.getuid && stat.uid !== process.getuid()) || (stat.mode & 0o077) !== 0) return null; // foreign permissions: refuse
82
+ const entry = JSON.parse(fs.readFileSync(file, 'utf-8'));
83
+ if (!entry || entry.version !== VERSION || entry.key !== key) return null;
84
+ if (entry.instance !== identity.instance || entry.profile !== (identity.profile || '')
85
+ || entry.principal !== identity.principal || entry.table !== table) return null;
86
+ if (!Number.isSafeInteger(entry.fetched_at) || entry.fetched_at > Date.now() || Date.now() - entry.fetched_at >= ttlMs) return null;
87
+ if (!validPayload(entry.payload) || entry.payload.hierarchy[0] !== table) return null;
88
+ return { payload: entry.payload, fetched_at: entry.fetched_at };
89
+ } catch {
90
+ return null;
91
+ }
92
+ }
93
+
94
+ function writeFile(table, payload) {
95
+ if (!persist || !validPayload(payload)) return;
96
+ const key = keyFor(table);
97
+ const file = fileFor(key);
98
+ const temp = path.join(root, `.${key}.${process.pid}.${crypto.randomBytes(6).toString('hex')}.tmp`);
99
+ try {
100
+ fs.mkdirSync(root, { recursive: true, mode: 0o700 });
101
+ const parent = fs.lstatSync(root);
102
+ if (!parent.isDirectory() || (parent.mode & 0o077) || (process.getuid && parent.uid !== process.getuid())) return;
103
+ const body = JSON.stringify({
104
+ version: VERSION, key,
105
+ instance: identity.instance, profile: identity.profile || '',
106
+ principal: identity.principal, table, fetched_at: Date.now(), payload,
107
+ });
108
+ if (Buffer.byteLength(body) > QUERY_CACHE_LIMITS.entryBytes) return;
109
+ fs.writeFileSync(temp, body, { mode: 0o600, flag: 'wx' });
110
+ fs.renameSync(temp, file);
111
+ const files = fs.readdirSync(root).filter(name => /^[a-f0-9]{64}\.json$/.test(name))
112
+ .map(name => ({ name, stat: fs.lstatSync(path.join(root, name)) }))
113
+ .filter(item => item.stat.isFile()).sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs);
114
+ let bytes = 0;
115
+ for (const [index, item] of files.entries()) {
116
+ bytes += item.stat.size;
117
+ if (index >= QUERY_CACHE_LIMITS.entries || bytes > QUERY_CACHE_LIMITS.bytes) fs.unlinkSync(path.join(root, item.name));
118
+ }
119
+ } catch {
120
+ try { fs.unlinkSync(temp); } catch { /* best effort */ }
121
+ }
122
+ }
123
+
124
+ return {
125
+ identity,
126
+ persistent: persist,
127
+ get(table) {
128
+ const hit = memory.get(table);
129
+ if (hit && hit.fetched_at <= Date.now() && Date.now() - hit.fetched_at < ttlMs) return hit;
130
+ if (hit) memory.delete(table);
131
+ const disk = readFile(table);
132
+ if (disk) { memory.set(table, disk); boundMemory(); }
133
+ return disk;
134
+ },
135
+ set(table, payload) {
136
+ if (!validPayload(payload) || payload.hierarchy[0] !== table
137
+ || Buffer.byteLength(JSON.stringify(payload)) > QUERY_CACHE_LIMITS.entryBytes - 2048) return null;
138
+ const entry = { payload, fetched_at: Date.now() };
139
+ memory.set(table, entry);
140
+ boundMemory();
141
+ writeFile(table, payload);
142
+ return entry;
143
+ },
144
+ /** Explicit refresh: forget this table before the next read. */
145
+ refresh(table) { memory.delete(table); if (persist) { try { fs.unlinkSync(fileFor(keyFor(table))); } catch { /* absent */ } } },
146
+ /**
147
+ * Invalidate entries affected by a table/field mutation. When the affected
148
+ * scope is uncertain, clearing this identity's cache is the safe choice.
149
+ */
150
+ invalidate({ tables = [], all = false } = {}) {
151
+ const affected = new Set(tables.filter(Boolean));
152
+ memory.clear();
153
+ if (platform === 'win32') return { removed: 0 };
154
+ // With unknown principal, clear this instance/profile to avoid stale privileged reuse.
155
+ let removed = 0;
156
+ let entries;
157
+ try {
158
+ const parent = fs.lstatSync(root);
159
+ if (!parent.isDirectory() || (parent.mode & 0o077) || (process.getuid && parent.uid !== process.getuid())) return { removed: 0 };
160
+ entries = fs.readdirSync(root);
161
+ } catch { return { removed: 0 }; }
162
+ for (const name of entries) {
163
+ if (!/^[a-f0-9]{64}\.json$/.test(name)) continue;
164
+ const file = path.join(root, name);
165
+ let entry;
166
+ try {
167
+ const stat = fs.lstatSync(file);
168
+ if (!stat.isFile() || stat.size > QUERY_CACHE_LIMITS.entryBytes || (stat.mode & 0o077)) continue;
169
+ entry = JSON.parse(fs.readFileSync(file, 'utf-8'));
170
+ } catch { continue; }
171
+ if (entry?.instance !== identity.instance || entry?.profile !== (identity.profile || '')
172
+ || (persist && entry?.principal !== identity.principal)) continue;
173
+ const related = entry?.payload?.hierarchy || [];
174
+ const references = Object.values(entry?.payload?.fields || {}).flatMap(fields =>
175
+ Object.values(fields || {}).map(definition => definition?.reference).filter(Boolean));
176
+ const touch = all || !affected.size
177
+ || affected.has(entry.table) || related.some(name => affected.has(name))
178
+ || references.some(name => affected.has(name));
179
+ if (!touch) continue;
180
+ try { fs.unlinkSync(file); removed++; } catch { /* best effort */ }
181
+ }
182
+ return { removed };
183
+ },
184
+ };
185
+ }
186
+
187
+ export { digest as queryCacheDigest };
@@ -0,0 +1,189 @@
1
+ // On-demand, table-scoped metadata for encoded-query validation.
2
+ //
3
+ // A bounded sys_db_object ancestry walk and one sys_dictionary request cover
4
+ // visible ancestors. Unresolved tables allow one bounded name-candidate lookup. Nothing here dumps a
5
+ // whole instance schema, and nothing here treats a hidden row as absence.
6
+
7
+ const FIELD_LIMIT = 1000;
8
+ const MAX_DEPTH = 8;
9
+
10
+ const raw = value => String(value && typeof value === 'object' ? value.value ?? '' : value ?? '');
11
+ const isName = value => typeof value === 'string' && /^[a-zA-Z0-9_]+$/.test(value);
12
+
13
+ function params(query, fields, limit) {
14
+ return new URLSearchParams({
15
+ sysparm_query: query,
16
+ sysparm_fields: fields,
17
+ sysparm_limit: String(limit),
18
+ sysparm_display_value: 'false',
19
+ });
20
+ }
21
+
22
+ function classifyFailure(error) {
23
+ const status = Number(error?.status);
24
+ if (status === 401 || status === 403 || error?.code === 'auth_error') return 'denied';
25
+ return 'unavailable';
26
+ }
27
+
28
+ async function readList(sdk, table, searchParams) {
29
+ try {
30
+ const responseMetadata = {};
31
+ const read = sdk.listStrict || sdk.list;
32
+ const rows = await read.call(sdk, table, searchParams, { responseMetadata });
33
+ if (!Array.isArray(rows)) return { state: 'unavailable', reason: 'Metadata response was not an array' };
34
+ return { rows, total: responseMetadata.total };
35
+ } catch (error) {
36
+ return { state: classifyFailure(error), reason: 'Metadata read failed or returned an invalid envelope' };
37
+ }
38
+ }
39
+
40
+ // One prefix-bounded, ACL-scoped candidate read, never a schema inventory.
41
+ // Suggestions are labels only and are never cached or substituted into queries.
42
+ async function tableSuggestions(sdk, table, requests) {
43
+ if (!isName(table) || table.length < 3) return [];
44
+ const prefix = table.slice(0, 3);
45
+ const query = `nameSTARTSWITH${prefix}^ORDERBYname`;
46
+ requests.push({ table: 'sys_db_object', query, fields: 'name', limit: 20 });
47
+ const result = await readList(sdk, 'sys_db_object', params(query, 'name', 20));
48
+ if (!result.rows || result.rows.length > 20) return [];
49
+ const distance = (a, b) => {
50
+ let previous = Array.from({ length: b.length + 1 }, (_, i) => i);
51
+ for (let i = 1; i <= a.length; i++) {
52
+ const next = [i];
53
+ for (let j = 1; j <= b.length; j++) next[j] = Math.min(next[j - 1] + 1, previous[j] + 1, previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
54
+ previous = next;
55
+ }
56
+ return previous[b.length];
57
+ };
58
+ return [...new Set(result.rows.map(row => raw(row?.name)))]
59
+ .filter(name => isName(name) && name.length <= 160 && name !== table && name.startsWith(prefix))
60
+ .map(name => ({ name, distance: distance(table.slice(0, 160), name) }))
61
+ .filter(candidate => candidate.distance <= Math.max(2, Math.floor(table.length / 4)))
62
+ .sort((a, b) => a.distance - b.distance || a.name.localeCompare(b.name))
63
+ .slice(0, 3).map(candidate => candidate.name);
64
+ }
65
+
66
+ /**
67
+ * Read table + ancestor field metadata as visible to the caller's own ACLs.
68
+ * States: observed | denied | unavailable | incomplete.
69
+ * `incomplete` is never absence: callers must not treat missing fields as
70
+ * definitively unknown-to-the-platform.
71
+ */
72
+ export async function readTableMetadata(sdk, table, { maxDepth = MAX_DEPTH, limit = FIELD_LIMIT } = {}) {
73
+ if (!isName(table)) {
74
+ return { state: 'unavailable', table, hierarchy: [], fields: {}, reason: 'Invalid table name', requests: [] };
75
+ }
76
+ const requests = [];
77
+ const hierarchy = [];
78
+ const visited = new Set();
79
+ let next = { query: `name=${table}`, fields: 'sys_id,name,super_class', limit: 2 };
80
+ let state = 'observed';
81
+ let reason = '';
82
+
83
+ for (let depth = 0; next && depth < maxDepth; depth++) {
84
+ const search = params(next.query, next.fields, next.limit);
85
+ requests.push({ table: 'sys_db_object', query: next.query, fields: next.fields, limit: next.limit });
86
+ const result = await readList(sdk, 'sys_db_object', search);
87
+ if (!result.rows) {
88
+ return { state: result.state, table, hierarchy: hierarchy.map(item => item.name), fields: {}, reason: result.reason, requests,
89
+ suggestions: depth === 0 ? await tableSuggestions(sdk, table, requests) : [] };
90
+ }
91
+ if (result.rows.length !== 1) {
92
+ // First hop: the table is not visible (may not exist, may be ACL-hidden).
93
+ // Deeper hop: an ancestor is hidden or the chain is malformed.
94
+ state = depth === 0 ? 'denied' : 'incomplete';
95
+ reason = depth === 0
96
+ ? `Table ${table} is not visible to this identity; it may not exist or may be ACL-hidden`
97
+ : `Ancestor metadata above ${hierarchy.at(-1)?.name || table} is not visible`;
98
+ break;
99
+ }
100
+ const row = result.rows[0];
101
+ const name = raw(row?.name);
102
+ const id = raw(row?.sys_id);
103
+ if (!row || typeof row !== 'object' || !isName(name) || visited.has(name)
104
+ || (depth === 0 ? name !== table : id !== next.query.slice(7))) {
105
+ state = 'incomplete';
106
+ reason = 'Malformed or cyclic sys_db_object ancestry';
107
+ break;
108
+ }
109
+ visited.add(name);
110
+ hierarchy.push({ name, sys_id: id });
111
+ if (!Object.hasOwn(row, 'super_class')) {
112
+ state = 'incomplete';
113
+ reason = 'Parent metadata is not visible; inheritance coverage is incomplete';
114
+ break;
115
+ }
116
+ const parentValue = row.super_class;
117
+ const readableParent = typeof parentValue === 'string'
118
+ || (parentValue && typeof parentValue === 'object' && !Array.isArray(parentValue)
119
+ && Object.hasOwn(parentValue, 'value') && typeof parentValue.value === 'string');
120
+ if (!readableParent) {
121
+ state = 'incomplete';
122
+ reason = 'Parent reference has no readable raw value; inheritance coverage is incomplete';
123
+ break;
124
+ }
125
+ const parent = raw(row.super_class);
126
+ if (!parent) { next = null; break; }
127
+ if (!/^[a-f0-9]{32}$/i.test(parent)) {
128
+ state = 'incomplete';
129
+ reason = 'Malformed parent reference in sys_db_object';
130
+ break;
131
+ }
132
+ next = { query: `sys_id=${parent}`, fields: 'sys_id,name,super_class', limit: 2 };
133
+ }
134
+ if (next && hierarchy.length >= maxDepth) {
135
+ state = state === 'observed' ? 'incomplete' : state;
136
+ reason ||= `Table inheritance depth limit ${maxDepth} reached`;
137
+ }
138
+ if (!hierarchy.length) {
139
+ return { state, table, hierarchy: [], fields: {}, reason, requests, suggestions: await tableSuggestions(sdk, table, requests) };
140
+ }
141
+
142
+ const names = hierarchy.map(item => item.name);
143
+ const query = `nameIN${names.join(',')}^elementISNOTEMPTY`;
144
+ requests.push({ table: 'sys_dictionary', query, fields: 'sys_id,name,element,internal_type,reference', limit });
145
+ const dictionary = await readList(sdk, 'sys_dictionary', params(query, 'sys_id,name,element,internal_type,reference', limit));
146
+ if (!dictionary.rows) {
147
+ return { state: dictionary.state, table, hierarchy: names, fields: {}, reason: dictionary.reason, requests };
148
+ }
149
+ const fields = {};
150
+ for (const row of dictionary.rows) {
151
+ const owner = raw(row?.name);
152
+ const element = raw(row?.element);
153
+ if (!isName(owner) || !isName(element) || !names.includes(owner)) {
154
+ state = state === 'observed' ? 'incomplete' : state;
155
+ reason ||= 'Ignored a malformed or out-of-scope sys_dictionary row';
156
+ continue;
157
+ }
158
+ if (!Object.hasOwn(row, 'internal_type') || !raw(row.internal_type)
159
+ || !Object.hasOwn(row, 'reference')
160
+ || (raw(row.internal_type) === 'reference' && !isName(raw(row.reference)))) {
161
+ state = state === 'observed' ? 'incomplete' : state;
162
+ reason ||= 'Field type or reference metadata is not visible';
163
+ }
164
+ fields[owner] ||= {};
165
+ fields[owner][element] = {
166
+ type: raw(row.internal_type) || 'unknown',
167
+ reference: isName(raw(row.reference)) ? raw(row.reference) : '',
168
+ };
169
+ }
170
+ if (!dictionary.rows.length || !Number.isSafeInteger(dictionary.total)
171
+ || dictionary.total !== dictionary.rows.length || dictionary.rows.length >= limit) {
172
+ state = state === 'observed' ? 'incomplete' : state;
173
+ reason ||= `sys_dictionary limit ${limit} reached; field coverage is incomplete`;
174
+ }
175
+ return { state, table, hierarchy: names, fields, reason, requests,
176
+ complete: state === 'observed', source: 'table-api', total: dictionary.total };
177
+ }
178
+
179
+ /** Resolve one field through the dictionary, marking where it was inherited. */
180
+ export function resolveField(metadata, table, element) {
181
+ const owners = metadata.hierarchy?.length ? metadata.hierarchy : [table];
182
+ for (const owner of owners) {
183
+ const definition = metadata.fields?.[owner]?.[element];
184
+ if (definition) return { ...definition, owner, inherited: owner !== table };
185
+ }
186
+ return null;
187
+ }
188
+
189
+ export const QUERY_METADATA_LIMITS = Object.freeze({ maxDepth: MAX_DEPTH, fields: FIELD_LIMIT });