@altopelago/sansa 0.9.0 → 0.10.0

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.
@@ -0,0 +1,423 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from 'node:fs';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { lowerInstruction, parseInstruction, planInstruction, validateMutationPlanTarget } from '../src/index.js';
6
+ import { namespaceFromAeonSource, namespaceFromJsonSource } from '../tools/query-web/runtime.mjs';
7
+
8
+ const here = dirname(fileURLToPath(import.meta.url));
9
+ const root = resolve(here, '..');
10
+ const defaultFixturePath = resolve(root, 'fixtures', 'query-inventory.json');
11
+
12
+ const args = parseArgs(process.argv.slice(2));
13
+
14
+ if (args.help) {
15
+ printHelp();
16
+ process.exit(0);
17
+ }
18
+
19
+ const source = readInstructionSource(args);
20
+ if (!source.trim()) {
21
+ console.error('SANSA Instruction tool error: expected instruction source via --instruction, --instruction-file, or stdin.');
22
+ process.exit(2);
23
+ }
24
+
25
+ const mode = args.mode ?? 'lower';
26
+ const format = args.format ?? 'text';
27
+ if (!['parse', 'lower', 'plan'].includes(mode)) {
28
+ console.error(`SANSA Instruction tool error: unsupported --mode '${mode}'. Expected 'parse', 'lower', or 'plan'.`);
29
+ process.exit(2);
30
+ }
31
+ if (!['text', 'json'].includes(format)) {
32
+ console.error(`SANSA Instruction tool error: unsupported --format '${format}'. Expected 'text' or 'json'.`);
33
+ process.exit(2);
34
+ }
35
+ if (args.target !== undefined && !['aeon', 'json', 'json-compatible'].includes(args.target)) {
36
+ console.error(`SANSA Instruction tool error: unsupported --target '${args.target}'. Expected 'aeon', 'json', or 'json-compatible'.`);
37
+ process.exit(2);
38
+ }
39
+ if (args.target !== undefined && mode !== 'plan') {
40
+ console.error('SANSA Instruction tool error: --target is only available with --mode plan.');
41
+ process.exit(2);
42
+ }
43
+
44
+ let result;
45
+ let fixturePath;
46
+ let targetResult;
47
+ if (mode === 'parse') {
48
+ result = parseInstruction(source);
49
+ } else {
50
+ fixturePath = resolve(args.fixture ?? defaultFixturePath);
51
+ const loaded = await readNamespaceFixture(fixturePath, args.fixtureKind);
52
+ if (!loaded.ok) process.exit(2);
53
+ result = mode === 'plan'
54
+ ? planInstruction(source, loaded.namespace)
55
+ : lowerInstruction(source, loaded.namespace);
56
+ if (mode === 'plan' && result.ok && args.target !== undefined) {
57
+ targetResult = validateMutationPlanTarget(result.plan, args.target);
58
+ if (!targetResult.ok) {
59
+ result = {
60
+ ok: false,
61
+ phase: 'target',
62
+ loweredRequest: result.loweredRequest,
63
+ errors: targetResult.errors,
64
+ };
65
+ }
66
+ }
67
+ }
68
+
69
+ if (format === 'json') {
70
+ console.log(JSON.stringify(formatJsonResult(result, mode, fixturePath, args.target, targetResult), null, 2));
71
+ } else {
72
+ printTextResult(result, mode, fixturePath, args.target, targetResult);
73
+ }
74
+
75
+ process.exit(result.ok ? 0 : 1);
76
+
77
+ function parseArgs(raw) {
78
+ const output = {};
79
+ for (let index = 0; index < raw.length; index += 1) {
80
+ const arg = raw[index];
81
+ if (arg === '--help' || arg === '-h') {
82
+ output.help = true;
83
+ } else if (arg === '--instruction' || arg === '-i') {
84
+ output.instruction = requireValue(raw, ++index, arg);
85
+ } else if (arg === '--instruction-file') {
86
+ output.instructionFile = requireValue(raw, ++index, arg);
87
+ } else if (arg === '--fixture' || arg === '-f') {
88
+ output.fixture = requireValue(raw, ++index, arg);
89
+ } else if (arg === '--fixture-kind') {
90
+ output.fixtureKind = requireValue(raw, ++index, arg);
91
+ } else if (arg === '--format') {
92
+ output.format = requireValue(raw, ++index, arg);
93
+ } else if (arg === '--mode') {
94
+ output.mode = requireValue(raw, ++index, arg);
95
+ } else if (arg === '--target') {
96
+ output.target = requireValue(raw, ++index, arg);
97
+ } else {
98
+ console.error(`SANSA Instruction tool error: unknown argument '${arg}'.`);
99
+ process.exit(2);
100
+ }
101
+ }
102
+ return output;
103
+ }
104
+
105
+ function requireValue(raw, index, flag) {
106
+ const value = raw[index];
107
+ if (!value || value.startsWith('--')) {
108
+ console.error(`SANSA Instruction tool error: ${flag} expects a value.`);
109
+ process.exit(2);
110
+ }
111
+ return value;
112
+ }
113
+
114
+ function readInstructionSource(options) {
115
+ if (typeof options.instruction === 'string') return options.instruction;
116
+ if (typeof options.instructionFile === 'string') return readFileSync(resolve(options.instructionFile), 'utf8');
117
+ if (!process.stdin.isTTY) return readFileSync(0, 'utf8');
118
+ return '';
119
+ }
120
+
121
+ async function readNamespaceFixture(path, explicitKind) {
122
+ const kind = inferFixtureKind(path, explicitKind);
123
+ let source;
124
+ try {
125
+ source = readFileSync(path, 'utf8');
126
+ } catch (error) {
127
+ console.error(`SANSA Instruction tool error: could not read fixture '${path}': ${error.message}`);
128
+ return { ok: false };
129
+ }
130
+
131
+ if (kind === 'json') {
132
+ const result = namespaceFromJsonSource(source);
133
+ if (result.ok) return { ok: true, namespace: namespaceWithParents(result.namespace) };
134
+ console.error(`SANSA Instruction tool error: could not parse JSON fixture '${path}':`);
135
+ console.error(result.text ?? renderDiagnostics(result.errors ?? []));
136
+ return { ok: false };
137
+ }
138
+
139
+ const result = await namespaceFromAeonSource(source);
140
+ if (!result.ok) {
141
+ console.error(`SANSA Instruction tool error: could not compile AEON fixture '${path}':`);
142
+ console.error(result.text ?? renderDiagnostics(result.errors ?? []));
143
+ return { ok: false };
144
+ }
145
+ return { ok: true, namespace: namespaceWithParents(result.namespace) };
146
+ }
147
+
148
+ function namespaceWithParents(namespace) {
149
+ const rootBinding = typeof namespace.root === 'function' ? namespace.root() : namespace.root;
150
+ attachParents(rootBinding);
151
+ return {
152
+ ...namespace,
153
+ parent: namespace.parent ?? ((binding) => binding.parent),
154
+ };
155
+ }
156
+
157
+ function attachParents(binding) {
158
+ if (!binding || typeof binding !== 'object') return;
159
+ for (const child of binding.children ?? []) {
160
+ child.parent = binding;
161
+ attachParents(child);
162
+ }
163
+ const attributeSpace = binding.attributeSpace ?? binding.attributes;
164
+ if (attributeSpace && typeof attributeSpace === 'object') {
165
+ attributeSpace.parent = binding;
166
+ attachParents(attributeSpace);
167
+ }
168
+ for (const localSpace of Object.values(binding.localSpaces ?? {})) {
169
+ if (localSpace && typeof localSpace === 'object') {
170
+ localSpace.parent = binding;
171
+ attachParents(localSpace);
172
+ }
173
+ }
174
+ }
175
+
176
+ function inferFixtureKind(path, explicitKind) {
177
+ if (explicitKind !== undefined) {
178
+ if (explicitKind === 'json' || explicitKind === 'aeon') return explicitKind;
179
+ console.error(`SANSA Instruction tool error: unsupported --fixture-kind '${explicitKind}'. Expected 'json' or 'aeon'.`);
180
+ process.exit(2);
181
+ }
182
+ if (path.endsWith('.json')) return 'json';
183
+ if (path.endsWith('.aeon')) return 'aeon';
184
+ console.error(`SANSA Instruction tool error: could not infer fixture kind from '${path}'. Use --fixture-kind json or --fixture-kind aeon.`);
185
+ process.exit(2);
186
+ }
187
+
188
+ function printTextResult(result, mode, fixturePath, target, targetResult) {
189
+ if (!result.ok) {
190
+ console.error(renderDiagnostics(result.errors));
191
+ return;
192
+ }
193
+ if (mode === 'parse') {
194
+ console.log(result.instruction.canonical);
195
+ return;
196
+ }
197
+ if (mode === 'lower') {
198
+ console.log(renderLoweredRequest(result.request));
199
+ return;
200
+ }
201
+ console.log(`fixture: ${fixturePath}`);
202
+ console.log(renderLoweredRequest(result.loweredRequest));
203
+ console.log(renderPlanSummary(result.plan));
204
+ if (target !== undefined) {
205
+ console.log(`target: ${targetResult?.ok ? `${target} ok` : `${target} failed`}`);
206
+ }
207
+ }
208
+
209
+ function formatJsonResult(result, mode, fixturePath, target, targetResult) {
210
+ if (!result.ok) {
211
+ return {
212
+ ok: false,
213
+ mode,
214
+ ...(target === undefined ? {} : { target }),
215
+ ...(result.phase === undefined ? {} : { phase: result.phase }),
216
+ errors: result.errors,
217
+ ...(result.loweredRequest === undefined ? {} : { loweredRequest: result.loweredRequest }),
218
+ };
219
+ }
220
+ if (mode === 'parse') return result;
221
+ if (mode === 'lower') return result;
222
+ return {
223
+ ok: true,
224
+ mode,
225
+ fixture: fixturePath,
226
+ loweredRequest: result.loweredRequest,
227
+ plan: summarizePlan(result.plan),
228
+ ...(target === undefined ? {} : { target, targetResult }),
229
+ diagnostics: result.diagnostics,
230
+ warnings: result.warnings,
231
+ };
232
+ }
233
+
234
+ function renderLoweredRequest(request) {
235
+ const operations = Array.isArray(request)
236
+ ? request
237
+ : Array.isArray(request?.operations)
238
+ ? request.operations
239
+ : [request];
240
+ const lines = operations.map((operation, index) => {
241
+ const prefix = operations.length > 1 ? `${index + 1}. ` : '';
242
+ return `${prefix}${renderRequestedOperation(operation)}`;
243
+ });
244
+ if (Array.isArray(request?.preconditions) && request.preconditions.length > 0) {
245
+ lines.push(...request.preconditions.map((precondition, index) => {
246
+ const prefix = request.preconditions.length > 1 ? `${index + 1}. ` : '';
247
+ return `${prefix}require ${precondition.expression}${precondition.target === undefined ? '' : ` at ${precondition.target}`}`;
248
+ }));
249
+ }
250
+ return lines.join('\n');
251
+ }
252
+
253
+ function renderRequestedOperation(operation) {
254
+ switch (operation.op) {
255
+ case 'create':
256
+ return `create ${appendMember(operation.parent, operation.name)} = ${renderValue(operation.value)}${renderHints(operation)}`;
257
+ case 'replace':
258
+ return `replace ${operation.target} = ${renderValue(operation.value)}${renderHints(operation)}`;
259
+ case 'remove':
260
+ return `remove ${operation.target}`;
261
+ case 'insert':
262
+ return `insert ${operation.placement.kind ?? operation.placement} in ${operation.container} = ${renderValue(operation.value)}${renderHints(operation)}`;
263
+ case 'move':
264
+ return `move ${operation.source} ${operation.placement.kind ?? operation.placement} in ${operation.container}`;
265
+ default:
266
+ return JSON.stringify(operation);
267
+ }
268
+ }
269
+
270
+ function renderPlanSummary(plan) {
271
+ const lines = [
272
+ `plan: ${plan.operations.length} operation${plan.operations.length === 1 ? '' : 's'}`,
273
+ ...plan.operations.map((operation, index) => `${index + 1}. ${renderPlannedOperation(operation)}`),
274
+ ];
275
+ if (plan.sourceProvenance?.reason !== undefined || plan.sourceProvenance?.claimedAuthor !== undefined) {
276
+ lines.push('provenance:');
277
+ if (plan.sourceProvenance.reason !== undefined) lines.push(`because ${JSON.stringify(plan.sourceProvenance.reason)}`);
278
+ if (plan.sourceProvenance.claimedAuthor !== undefined) lines.push(`by ${JSON.stringify(plan.sourceProvenance.claimedAuthor)}`);
279
+ }
280
+ return lines.join('\n');
281
+ }
282
+
283
+ function renderPlannedOperation(operation) {
284
+ switch (operation.op) {
285
+ case 'create':
286
+ return `create ${appendMember(operation.parent.canonicalAddress, operation.name)} = ${renderValue(operation.value)}${renderHints(operation)}`;
287
+ case 'replace':
288
+ return `replace ${operation.target.canonicalAddress} = ${renderValue(operation.value)}${renderHints(operation)}`;
289
+ case 'remove':
290
+ return `remove ${operation.target.canonicalAddress}`;
291
+ case 'insert':
292
+ return `insert ${operation.placement.kind} in ${operation.container.canonicalAddress} = ${renderValue(operation.value)}${renderHints(operation)}`;
293
+ case 'move':
294
+ return `move ${operation.source.canonicalAddress} ${operation.placement.kind} in ${operation.container.canonicalAddress}`;
295
+ default:
296
+ return JSON.stringify(summarizeOperation(operation));
297
+ }
298
+ }
299
+
300
+ function summarizePlan(plan) {
301
+ return {
302
+ type: plan.type,
303
+ planVersion: plan.planVersion,
304
+ planId: plan.planId,
305
+ operations: plan.operations.map(summarizeOperation),
306
+ preconditions: plan.preconditions.map((precondition) => ({
307
+ expression: precondition.expression,
308
+ canonical: precondition.canonical,
309
+ target: precondition.target?.canonicalAddress,
310
+ })),
311
+ diagnostics: plan.diagnostics,
312
+ portabilityWarnings: plan.portabilityWarnings,
313
+ sourceProvenance: plan.sourceProvenance,
314
+ };
315
+ }
316
+
317
+ function summarizeOperation(operation) {
318
+ switch (operation.op) {
319
+ case 'create':
320
+ return {
321
+ op: 'create',
322
+ parent: operation.parent.canonicalAddress,
323
+ name: operation.name,
324
+ value: operation.value,
325
+ ...hintFields(operation),
326
+ };
327
+ case 'replace':
328
+ return {
329
+ op: 'replace',
330
+ target: operation.target.canonicalAddress,
331
+ value: operation.value,
332
+ ...hintFields(operation),
333
+ };
334
+ case 'remove':
335
+ return { op: 'remove', target: operation.target.canonicalAddress };
336
+ case 'insert':
337
+ return {
338
+ op: 'insert',
339
+ container: operation.container.canonicalAddress,
340
+ placement: summarizePlacement(operation.placement),
341
+ value: operation.value,
342
+ ...hintFields(operation),
343
+ };
344
+ case 'move':
345
+ return {
346
+ op: 'move',
347
+ source: operation.source.canonicalAddress,
348
+ container: operation.container.canonicalAddress,
349
+ placement: summarizePlacement(operation.placement),
350
+ };
351
+ default:
352
+ return { op: operation.op };
353
+ }
354
+ }
355
+
356
+ function summarizePlacement(placement) {
357
+ if (placement.kind === 'first' || placement.kind === 'last') return placement.kind;
358
+ return { kind: placement.kind, anchor: placement.anchor.canonicalAddress };
359
+ }
360
+
361
+ function renderHints(operation) {
362
+ const hints = [];
363
+ if (operation.datatype) hints.push(`datatype:${operation.datatype}`);
364
+ if (operation.kind) hints.push(`kind:${operation.kind}`);
365
+ return hints.length === 0 ? '' : ` (${hints.join(', ')})`;
366
+ }
367
+
368
+ function hintFields(operation) {
369
+ return {
370
+ ...(operation.datatype === undefined ? {} : { datatype: operation.datatype }),
371
+ ...(operation.kind === undefined ? {} : { kind: operation.kind }),
372
+ };
373
+ }
374
+
375
+ function renderValue(value) {
376
+ return typeof value === 'string' ? JSON.stringify(value) : JSON.stringify(value);
377
+ }
378
+
379
+ function appendMember(parent, name) {
380
+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(name)
381
+ ? `${parent}.${name}`
382
+ : `${parent}.[${JSON.stringify(name)}]`;
383
+ }
384
+
385
+ function renderDiagnostics(errors) {
386
+ return (errors ?? []).map((error) => {
387
+ const phase = error.phase ? ` [${error.phase}]` : '';
388
+ const details = diagnosticDetails(error);
389
+ return `${error.code}${phase}${details}: ${error.message}`;
390
+ }).join('\n');
391
+ }
392
+
393
+ function diagnosticDetails(error) {
394
+ const parts = [];
395
+ if (error.candidateAddress) parts.push(`at ${error.candidateAddress}`);
396
+ if (Number.isInteger(error.operationIndex)) parts.push(`operation ${error.operationIndex}`);
397
+ if (typeof error.targetFormat === 'string') parts.push(`target ${error.targetFormat}`);
398
+ if (typeof error.datatype === 'string') parts.push(`datatype ${error.datatype}`);
399
+ if (typeof error.valuePath === 'string') parts.push(`value ${error.valuePath}`);
400
+ return parts.length === 0 ? '' : ` (${parts.join(', ')})`;
401
+ }
402
+
403
+ function printHelp() {
404
+ console.log(`SANSA Instruction tool
405
+
406
+ Usage:
407
+ sansa-instruction --instruction <source> [--mode parse|lower|plan]
408
+ sansa-instruction --instruction-file <path> [--fixture <path>]
409
+ cat instruction.sansa | sansa-instruction --mode plan
410
+
411
+ Options:
412
+ -i, --instruction <source> Instruction source string.
413
+ --instruction-file <path> Read instruction source from a file.
414
+ -f, --fixture <path> JSON or AEON fixture for lower/plan modes.
415
+ Defaults to fixtures/query-inventory.json.
416
+ --fixture-kind <kind> Force fixture kind: json or aeon.
417
+ --mode <mode> parse, lower, or plan. Defaults to lower.
418
+ --target <target> Validate plan target surface: aeon, json, or json-compatible.
419
+ Only available with --mode plan.
420
+ --format <format> text or json. Defaults to text.
421
+ -h, --help Show this help.
422
+ `);
423
+ }
@@ -4,6 +4,7 @@ import { createServer } from 'node:http';
4
4
  import { extname, join, normalize, resolve, sep } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { evaluateQueryForWorkbench, parseQueryForWorkbench } from '../tools/query-web/runtime.mjs';
7
+ import { runMutationForWorkbench } from '../tools/mutate-web/runtime.mjs';
7
8
 
8
9
  const root = resolve(fileURLToPath(new URL('..', import.meta.url)));
9
10
  const port = Number(readArg('--port') ?? process.env.PORT ?? 4173);
@@ -15,6 +16,10 @@ const server = createServer((request, response) => {
15
16
  handleQueryApi(request, response);
16
17
  return;
17
18
  }
19
+ if (url.pathname === '/api/mutate') {
20
+ handleMutateApi(request, response);
21
+ return;
22
+ }
18
23
 
19
24
  const requestedPath = url.pathname === '/' ? '/tools/query-web/index.html' : url.pathname;
20
25
  let filePath = resolve(root, `.${normalize(requestedPath)}`);
@@ -51,6 +56,7 @@ const server = createServer((request, response) => {
51
56
 
52
57
  server.listen(port, host, () => {
53
58
  console.log(`SANSA Query Workbench: http://${host}:${port}/tools/query-web/`);
59
+ console.log(`SANSA Mutate Workbench: http://${host}:${port}/tools/mutate-web/`);
54
60
  });
55
61
 
56
62
  server.on('error', (error) => {
@@ -63,6 +69,45 @@ function readArg(name) {
63
69
  return index === -1 ? undefined : process.argv[index + 1];
64
70
  }
65
71
 
72
+ function handleMutateApi(request, response) {
73
+ if (request.method !== 'POST') {
74
+ writeJson(response, 405, {
75
+ ok: false,
76
+ errors: [{ code: 'SANSA_MUTATE_WORKBENCH_METHOD_NOT_ALLOWED', message: 'Expected POST.' }],
77
+ });
78
+ return;
79
+ }
80
+
81
+ readRequestBody(request, 1_000_000)
82
+ .then(async (body) => {
83
+ let payload;
84
+ try {
85
+ payload = JSON.parse(body);
86
+ } catch (error) {
87
+ writeJson(response, 400, {
88
+ ok: false,
89
+ errors: [{ code: 'SANSA_MUTATE_WORKBENCH_INVALID_REQUEST_JSON', message: error.message }],
90
+ });
91
+ return;
92
+ }
93
+
94
+ const result = await runMutationForWorkbench({
95
+ source: String(payload.source ?? ''),
96
+ requestSource: String(payload.requestSource ?? ''),
97
+ requestKind: payload.requestKind === 'instruction' ? 'instruction' : 'structured',
98
+ mode: payload.mode === 'apply' ? 'apply' : 'plan',
99
+ options: payload.options,
100
+ });
101
+ writeJson(response, result.ok ? 200 : 400, result);
102
+ })
103
+ .catch((error) => {
104
+ writeJson(response, 400, {
105
+ ok: false,
106
+ errors: [{ code: 'SANSA_MUTATE_WORKBENCH_REQUEST_ERROR', message: error.message }],
107
+ });
108
+ });
109
+ }
110
+
66
111
  function handleQueryApi(request, response) {
67
112
  if (request.method !== 'POST') {
68
113
  writeJson(response, 405, {
@@ -95,6 +140,7 @@ function handleQueryApi(request, response) {
95
140
  paramsSource: String(payload.paramsSource ?? ''),
96
141
  policy: payload.policy === 'validation' ? 'validation' : '',
97
142
  transformExtensions: payload.transformExtensions !== false,
143
+ valueSemantics: parseValueSemantics(payload.valueSemantics),
98
144
  budget: payload.budget,
99
145
  });
100
146
  writeJson(response, result.ok ? 200 : 400, result);
@@ -107,6 +153,16 @@ function handleQueryApi(request, response) {
107
153
  });
108
154
  }
109
155
 
156
+ function parseValueSemantics(value) {
157
+ if (value === undefined || value === null || value === '') return '';
158
+ const text = String(value).trim();
159
+ if (text.length === 0) return '';
160
+ if (text.length > 100 || /\s/.test(text)) {
161
+ throw new Error('valueSemantics expects a compact profile id or locale tag.');
162
+ }
163
+ return text;
164
+ }
165
+
110
166
  function readRequestBody(request, maxBytes) {
111
167
  return new Promise((resolveBody, rejectBody) => {
112
168
  let body = '';
package/scripts/query.mjs CHANGED
@@ -28,8 +28,14 @@ const mode = args.mode ?? 'evaluate';
28
28
  const format = args.format ?? 'text';
29
29
  const fixturePath = resolve(args.fixture ?? defaultFixturePath);
30
30
  const policy = parsePolicy(args.policy);
31
+ const valueSemantics = parseValueSemantics(args.valueSemantics);
31
32
  const budget = parseBudgetArgs(args);
32
- const evaluateOptions = buildEvaluateOptions({ policy, transformEnabled: args.disableTransform !== true, budget });
33
+ const evaluateOptions = buildEvaluateOptions({
34
+ policy,
35
+ transformEnabled: args.disableTransform !== true,
36
+ valueSemantics,
37
+ budget,
38
+ });
33
39
 
34
40
  if (!['evaluate', 'parse'].includes(mode)) {
35
41
  console.error(`SANSA Query tool error: unsupported --mode '${mode}'. Expected 'evaluate' or 'parse'.`);
@@ -87,6 +93,8 @@ function parseArgs(raw) {
87
93
  output.mode = requireValue(raw, ++index, arg);
88
94
  } else if (arg === '--policy') {
89
95
  output.policy = requireValue(raw, ++index, arg);
96
+ } else if (arg === '--value-semantics') {
97
+ output.valueSemantics = requireValue(raw, ++index, arg);
90
98
  } else if (arg === '--disable-transform') {
91
99
  output.disableTransform = true;
92
100
  } else if (arg === '--max-from-bindings') {
@@ -112,6 +120,16 @@ function parsePolicy(value) {
112
120
  process.exit(2);
113
121
  }
114
122
 
123
+ function parseValueSemantics(value) {
124
+ if (value === undefined) return undefined;
125
+ const trimmed = value.trim();
126
+ if (!trimmed || trimmed.length > 100 || /\s/.test(trimmed)) {
127
+ console.error('SANSA Query tool error: --value-semantics expects a compact profile id or locale tag.');
128
+ process.exit(2);
129
+ }
130
+ return trimmed;
131
+ }
132
+
115
133
  function parseBudgetArgs(options) {
116
134
  const budget = {};
117
135
  for (const [flag, key] of [
@@ -139,10 +157,12 @@ function parseBudgetLimit(value, flag) {
139
157
  return parsed;
140
158
  }
141
159
 
142
- function buildEvaluateOptions({ policy, transformEnabled, budget }) {
160
+ function buildEvaluateOptions({ policy, transformEnabled, valueSemantics, budget }) {
143
161
  return {
162
+ addressActivation: 'trusted',
144
163
  ...(policy ? { policy } : {}),
145
164
  ...(transformEnabled ? {} : { extensions: { transform: false } }),
165
+ ...(valueSemantics ? { valueSemantics } : {}),
146
166
  ...(budget ? { budget } : {}),
147
167
  };
148
168
  }
@@ -439,8 +459,18 @@ function renderAeonValue(value, metadata, fieldMetadata) {
439
459
  }
440
460
  if (metadata?.kind === 'nan' || (typeof value === 'number' && Number.isNaN(value))) return 'NaN';
441
461
  if (metadata?.kind === 'infinity' || value === Infinity) return 'Infinity';
462
+ if (metadata?.kind === 'toggle' || metadata?.category === 'toggle') return String(value);
442
463
  if (value === -Infinity) return '-Infinity';
443
464
  if (value === null) return 'null';
465
+ if (metadata?.kind === 'hex') return `#${value}`;
466
+ if (metadata?.kind === 'radix') return `%${value}`;
467
+ if (metadata?.kind === 'encoding') return `&${value}`;
468
+ if (metadata?.kind === 'separator') return `^${value}`;
469
+ if (['date', 'time', 'datetime', 'wtc'].includes(metadata?.kind)) return String(value);
470
+ if (metadata?.kind === 'sansaAddress' || metadata?.kind === 'sansa') {
471
+ return value?.canonical ?? value?.address?.canonical ?? value?.address ?? String(value);
472
+ }
473
+ if (metadata?.kind === 'referenceForm') return value?.canonical ?? JSON.stringify(value);
444
474
  if (typeof value === 'string') return JSON.stringify(value);
445
475
  if (typeof value === 'number' || typeof value === 'boolean') return String(value);
446
476
  if (Array.isArray(value)) {
@@ -565,6 +595,8 @@ Options:
565
595
  --mode <mode> evaluate or parse. Defaults to evaluate.
566
596
  --format <format> text or json. Defaults to text.
567
597
  --policy <policy> Optional query policy: validation.
598
+ --value-semantics <profile>
599
+ Value semantics profile id or locale tag.
568
600
  --disable-transform Disable experimental SANSA.Transform helpers.
569
601
  --max-from-bindings <n>
570
602
  Fail if the from source resolves more than n bindings.