@altopelago/sansa 0.9.0 → 0.9.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.
@@ -0,0 +1,1308 @@
1
+ import { applyMutationPlan, planInstruction, planMutation, resolveAddress, validateMutationPlanTarget } from '../../src/index.js';
2
+ import { namespaceFromAeonSource } from '../query-web/runtime.mjs';
3
+
4
+ const HANDLE_PROPERTY = '__sansaMutateWorkbenchHandle';
5
+ const HANDLE_PREFIX = 'mutate-workbench';
6
+ const AEON_IDENTIFIER_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
7
+ const WORKBENCH_POLICY_TOP_LEVEL_FIELDS = new Set(['default', 'rules']);
8
+ const WORKBENCH_POLICY_RULE_FIELDS = new Set([
9
+ 'allow',
10
+ 'operations',
11
+ 'operation',
12
+ 'target',
13
+ 'parent',
14
+ 'container',
15
+ 'source',
16
+ 'anchor',
17
+ 'names',
18
+ 'name',
19
+ 'datatypes',
20
+ 'datatype',
21
+ 'kinds',
22
+ 'kind',
23
+ 'values',
24
+ 'value',
25
+ ]);
26
+
27
+ export async function runMutationForWorkbench({
28
+ source,
29
+ requestSource,
30
+ requestKind = 'structured',
31
+ mode = 'plan',
32
+ options = {},
33
+ }) {
34
+ const targetProfile = describeMutationTargetProfile(options.targetFormat);
35
+ const namespaceResult = await namespaceFromAeonSource(source);
36
+ if (!namespaceResult.ok) {
37
+ return {
38
+ ...namespaceResult,
39
+ mode,
40
+ };
41
+ }
42
+
43
+ const root = getRoot(namespaceResult.namespace);
44
+ assignStableHandles(root);
45
+ const namespace = mutableNamespace(namespaceResult.namespace);
46
+ const planOptions = mutationPlanOptions(options);
47
+ const applyOptions = mutationApplyOptions(options);
48
+ const planResult = requestKind === 'instruction'
49
+ ? planInstruction(String(requestSource ?? ''), namespace, planOptions)
50
+ : planStructuredWorkbenchRequest(requestSource, namespace, planOptions);
51
+
52
+ if (!planResult.ok) {
53
+ const errors = normalizeDiagnostics(planResult.errors);
54
+ return {
55
+ ok: false,
56
+ mode,
57
+ requestKind: requestKind === 'instruction' ? 'instruction' : 'structured',
58
+ phase: primaryDiagnosticPhase(errors, planResult.phase ?? 'plan'),
59
+ ...(planResult.loweredRequest === undefined ? {} : { loweredRequest: planResult.loweredRequest }),
60
+ text: renderDiagnosticText(planResult.errors, { fallbackPhase: planResult.phase ?? 'plan' }),
61
+ errors,
62
+ targetProfile,
63
+ source: renderBindingTree(root),
64
+ };
65
+ }
66
+
67
+ const policyResult = enforceMutationPolicyForWorkbench(planResult.plan, namespace, options.policySource);
68
+ if (!policyResult.ok) {
69
+ return {
70
+ ok: false,
71
+ mode,
72
+ requestKind: requestKind === 'instruction' ? 'instruction' : 'structured',
73
+ phase: 'policy',
74
+ ...(planResult.loweredRequest === undefined ? {} : { loweredRequest: planResult.loweredRequest }),
75
+ text: renderDiagnosticText(policyResult.errors),
76
+ errors: normalizeDiagnostics(policyResult.errors),
77
+ plan: summarizePlan(planResult.plan),
78
+ targetProfile,
79
+ source: renderBindingTree(root),
80
+ };
81
+ }
82
+
83
+ const targetResult = enforceTargetSurfaceForWorkbench(planResult.plan, targetProfile.id);
84
+ if (!targetResult.ok) {
85
+ return {
86
+ ok: false,
87
+ mode,
88
+ requestKind: requestKind === 'instruction' ? 'instruction' : 'structured',
89
+ phase: 'target',
90
+ ...(planResult.loweredRequest === undefined ? {} : { loweredRequest: planResult.loweredRequest }),
91
+ text: renderDiagnosticText(targetResult.errors),
92
+ errors: normalizeDiagnostics(targetResult.errors),
93
+ plan: summarizePlan(planResult.plan),
94
+ targetProfile,
95
+ source: renderBindingTree(root),
96
+ };
97
+ }
98
+
99
+ const plan = summarizePlan(planResult.plan);
100
+ if (mode !== 'apply') {
101
+ return {
102
+ ok: true,
103
+ mode: 'plan',
104
+ requestKind: requestKind === 'instruction' ? 'instruction' : 'structured',
105
+ text: renderPlanText(planResult.plan),
106
+ plan,
107
+ ...(planResult.loweredRequest === undefined ? {} : { loweredRequest: planResult.loweredRequest }),
108
+ targetProfile,
109
+ source: renderBindingTree(root),
110
+ diagnostics: normalizeDiagnostics(planResult.diagnostics ?? []),
111
+ };
112
+ }
113
+
114
+ const applied = applyMutationPlan(planResult.plan, namespace, applyOptions);
115
+ if (!applied.ok) {
116
+ return {
117
+ ok: false,
118
+ mode: 'apply',
119
+ text: renderDiagnosticText(applied.errors),
120
+ plan,
121
+ errors: normalizeDiagnostics(applied.errors),
122
+ operationResults: summarizeOperationResults(applied.operationResults ?? []),
123
+ targetProfile,
124
+ source: renderBindingTree(root),
125
+ };
126
+ }
127
+
128
+ return {
129
+ ok: true,
130
+ mode: 'apply',
131
+ requestKind: requestKind === 'instruction' ? 'instruction' : 'structured',
132
+ text: renderApplyText(applied),
133
+ plan,
134
+ ...(planResult.loweredRequest === undefined ? {} : { loweredRequest: planResult.loweredRequest }),
135
+ targetProfile,
136
+ result: {
137
+ planId: applied.planId,
138
+ stateBefore: sanitizeJsonValue(applied.stateBefore),
139
+ stateAfter: sanitizeJsonValue(applied.stateAfter),
140
+ operationResults: summarizeOperationResults(applied.operationResults),
141
+ diagnostics: normalizeDiagnostics(applied.diagnostics ?? []),
142
+ },
143
+ source: renderBindingTree(root),
144
+ };
145
+ }
146
+
147
+ export function enforceMutationPolicyForWorkbench(plan, namespace, policySource) {
148
+ if (policySource === undefined || policySource === null || String(policySource).trim().length === 0) {
149
+ return { ok: true, diagnostics: [] };
150
+ }
151
+
152
+ let policy;
153
+ try {
154
+ policy = JSON.parse(String(policySource));
155
+ } catch (error) {
156
+ return {
157
+ ok: false,
158
+ errors: [workbenchPolicyError(
159
+ 'SANSA_MUTATE_POLICY_INVALID_JSON',
160
+ error instanceof Error ? error.message : 'Mutation policy JSON is invalid',
161
+ )],
162
+ };
163
+ }
164
+
165
+ const normalized = normalizeWorkbenchPolicy(policy);
166
+ if (!normalized.ok) return { ok: false, errors: [normalized.error] };
167
+
168
+ for (let operationIndex = 0; operationIndex < plan.operations.length; operationIndex += 1) {
169
+ const operation = plan.operations[operationIndex];
170
+ const decision = authorizeWorkbenchOperation(operation, operationIndex, normalized.policy, namespace);
171
+ if (!decision.ok) return { ok: false, errors: [decision.error] };
172
+ }
173
+ return { ok: true, diagnostics: [] };
174
+ }
175
+
176
+ function enforceTargetSurfaceForWorkbench(plan, targetFormat) {
177
+ return validateMutationPlanTarget(plan, targetFormat ?? 'aeon');
178
+ }
179
+
180
+ function describeMutationTargetProfile(targetFormat) {
181
+ const id = targetFormat === 'json' || targetFormat === 'json-compatible' ? 'json' : 'aeon';
182
+ if (id === 'json') {
183
+ return {
184
+ id,
185
+ boundary: 'representability',
186
+ summary: 'JSON-compatible target surface: accepts ordinary JSON-compatible values and rejects AEON-only representation features.',
187
+ };
188
+ }
189
+ return {
190
+ id,
191
+ boundary: 'representability',
192
+ summary: 'AEON target surface: accepts AEON-representable datatype, kind, and value intent before apply.',
193
+ };
194
+ }
195
+
196
+ function normalizeWorkbenchPolicy(policy) {
197
+ if (!policy || typeof policy !== 'object' || Array.isArray(policy)) {
198
+ return {
199
+ ok: false,
200
+ error: workbenchPolicyError('SANSA_MUTATE_POLICY_INVALID', 'Mutation policy must be an object'),
201
+ };
202
+ }
203
+ const unsupportedTopLevelField = Object.keys(policy).find((field) => !WORKBENCH_POLICY_TOP_LEVEL_FIELDS.has(field));
204
+ if (unsupportedTopLevelField !== undefined) {
205
+ return {
206
+ ok: false,
207
+ error: workbenchPolicyError(
208
+ 'SANSA_MUTATE_POLICY_INVALID',
209
+ `Mutation policy field '${unsupportedTopLevelField}' is not supported`,
210
+ { policyScope: 'topLevel', policyField: unsupportedTopLevelField },
211
+ ),
212
+ };
213
+ }
214
+ if (policy.default !== undefined && policy.default !== 'allow' && policy.default !== 'deny') {
215
+ return {
216
+ ok: false,
217
+ error: workbenchPolicyError(
218
+ 'SANSA_MUTATE_POLICY_INVALID',
219
+ 'Mutation policy default must be "allow" or "deny"',
220
+ { policyScope: 'topLevel', policyField: 'default' },
221
+ ),
222
+ };
223
+ }
224
+ if (!Array.isArray(policy.rules)) {
225
+ return {
226
+ ok: false,
227
+ error: workbenchPolicyError(
228
+ 'SANSA_MUTATE_POLICY_INVALID',
229
+ 'Mutation policy rules must be a list',
230
+ { policyScope: 'topLevel', policyField: 'rules' },
231
+ ),
232
+ };
233
+ }
234
+ for (let ruleIndex = 0; ruleIndex < policy.rules.length; ruleIndex += 1) {
235
+ const rule = policy.rules[ruleIndex];
236
+ if (!rule || typeof rule !== 'object' || Array.isArray(rule)) {
237
+ return {
238
+ ok: false,
239
+ error: workbenchPolicyError(
240
+ 'SANSA_MUTATE_POLICY_INVALID',
241
+ 'Mutation policy rules must be objects',
242
+ { ruleIndex, policyScope: 'rule' },
243
+ ),
244
+ };
245
+ }
246
+ const unsupportedRuleField = Object.keys(rule).find((field) => !WORKBENCH_POLICY_RULE_FIELDS.has(field));
247
+ if (unsupportedRuleField !== undefined) {
248
+ return {
249
+ ok: false,
250
+ error: workbenchPolicyError(
251
+ 'SANSA_MUTATE_POLICY_INVALID',
252
+ `Mutation policy rule field '${unsupportedRuleField}' is not supported`,
253
+ { ruleIndex, policyScope: 'rule', policyField: unsupportedRuleField },
254
+ ),
255
+ };
256
+ }
257
+ if (rule.allow !== true && rule.allow !== false) {
258
+ return {
259
+ ok: false,
260
+ error: workbenchPolicyError(
261
+ 'SANSA_MUTATE_POLICY_INVALID',
262
+ 'Mutation policy rules must declare allow as true or false',
263
+ { ruleIndex, policyScope: 'rule', policyField: 'allow' },
264
+ ),
265
+ };
266
+ }
267
+ }
268
+ return {
269
+ ok: true,
270
+ policy: {
271
+ default: policy.default ?? 'deny',
272
+ rules: policy.rules,
273
+ },
274
+ };
275
+ }
276
+
277
+ function authorizeWorkbenchOperation(operation, operationIndex, policy, namespace) {
278
+ for (let ruleIndex = 0; ruleIndex < policy.rules.length; ruleIndex += 1) {
279
+ const rule = policy.rules[ruleIndex];
280
+ const match = workbenchPolicyRuleMatches(operation, rule, namespace);
281
+ if (!match.ok) {
282
+ const { ok: _ok, matched: _matched, code, message, ...details } = match;
283
+ return {
284
+ ok: false,
285
+ error: workbenchPolicyError(code, message, { ...details, operationIndex, ruleIndex }),
286
+ };
287
+ }
288
+ if (!match.matched) continue;
289
+ if (rule.allow === false) {
290
+ return {
291
+ ok: false,
292
+ error: workbenchPolicyError(
293
+ 'SANSA_MUTATE_POLICY_DENIED',
294
+ `Mutation policy rule ${ruleIndex} denies ${operation.op}`,
295
+ { operationIndex, ruleIndex },
296
+ ),
297
+ };
298
+ }
299
+ return { ok: true };
300
+ }
301
+
302
+ if (policy.default === 'allow') return { ok: true };
303
+ return {
304
+ ok: false,
305
+ error: workbenchPolicyError(
306
+ 'SANSA_MUTATE_POLICY_DENIED',
307
+ `Mutation policy has no allow rule for ${operation.op}`,
308
+ { operationIndex },
309
+ ),
310
+ };
311
+ }
312
+
313
+ function workbenchPolicyRuleMatches(operation, rule, namespace) {
314
+ if (!matchesPolicyList(rule.operations ?? rule.operation, operation.op)) return { ok: true, matched: false };
315
+ if (!matchesPolicyList(rule.names ?? rule.name, operation.name)) return { ok: true, matched: false };
316
+ if (!matchesPolicyList(rule.datatypes ?? rule.datatype, effectiveMutationDatatype(operation))) return { ok: true, matched: false };
317
+ if (!matchesPolicyList(rule.kinds ?? rule.kind, effectiveMutationKind(operation))) return { ok: true, matched: false };
318
+ if (!matchesPolicyValue(rule.values ?? rule.value, operation.value)) return { ok: true, matched: false };
319
+
320
+ for (const role of ['target', 'parent', 'source', 'container']) {
321
+ if (rule[role] === undefined) continue;
322
+ const target = operation[role];
323
+ if (!target?.canonicalAddress) return { ok: true, matched: false };
324
+ const addressMatch = workbenchPolicyAddressMatches(rule[role], target.canonicalAddress, namespace, role);
325
+ if (!addressMatch.ok || !addressMatch.matched) return addressMatch;
326
+ }
327
+ if (rule.anchor !== undefined) {
328
+ const anchor = operation.placement?.anchor;
329
+ if (!anchor?.canonicalAddress) return { ok: true, matched: false };
330
+ const addressMatch = workbenchPolicyAddressMatches(rule.anchor, anchor.canonicalAddress, namespace, 'anchor');
331
+ if (!addressMatch.ok || !addressMatch.matched) return addressMatch;
332
+ }
333
+ return { ok: true, matched: true };
334
+ }
335
+
336
+ function workbenchPolicyAddressMatches(expression, canonicalAddress, namespace, policyField) {
337
+ if (typeof expression !== 'string' || expression.trim().length === 0) {
338
+ return {
339
+ ok: false,
340
+ code: 'SANSA_MUTATE_POLICY_INVALID',
341
+ message: 'Mutation policy address matchers must be non-empty strings',
342
+ policyScope: 'matcher',
343
+ policyField,
344
+ };
345
+ }
346
+ const resolved = resolveAddress(expression, namespace);
347
+ if (!resolved.ok) {
348
+ return {
349
+ ok: false,
350
+ code: 'SANSA_MUTATE_POLICY_INVALID_ADDRESS',
351
+ message: `Mutation policy address matcher '${expression}' is invalid or unsupported`,
352
+ policyScope: 'matcher',
353
+ policyField,
354
+ policyAddress: expression,
355
+ };
356
+ }
357
+ return {
358
+ ok: true,
359
+ matched: resolved.bindings.some((binding) => binding.address === canonicalAddress),
360
+ };
361
+ }
362
+
363
+ function matchesPolicyList(expected, actual) {
364
+ if (expected === undefined) return true;
365
+ const expectedList = Array.isArray(expected) ? expected : [expected];
366
+ if (expectedList.includes('*')) return true;
367
+ if (actual === undefined) return false;
368
+ return expectedList.includes(actual);
369
+ }
370
+
371
+ function matchesPolicyValue(expected, actual) {
372
+ if (expected === undefined) return true;
373
+ const expectedList = Array.isArray(expected) ? expected : [expected];
374
+ return expectedList.some((entry) => Object.is(entry, actual));
375
+ }
376
+
377
+ function effectiveMutationDatatype(operation) {
378
+ if (operation.datatype !== undefined) return operation.datatype;
379
+ if (operation.op === 'replace') return operation.target?.binding?.semanticType;
380
+ if (operation.op === 'create' || operation.op === 'insert') return semanticTypeFromJsonValue(operation.value);
381
+ return undefined;
382
+ }
383
+
384
+ function effectiveMutationKind(operation) {
385
+ if (operation.kind !== undefined) return operation.kind;
386
+ if (operation.op === 'replace') {
387
+ return operation.target?.binding?.scalarKind
388
+ ?? operation.target?.binding?.representationKind
389
+ ?? operation.target?.binding?.semanticType;
390
+ }
391
+ if (operation.op === 'create' || operation.op === 'insert') return semanticTypeFromJsonValue(operation.value);
392
+ return undefined;
393
+ }
394
+
395
+ function workbenchPolicyError(code, message, details = {}) {
396
+ return {
397
+ code,
398
+ message,
399
+ phase: 'policy',
400
+ ...details,
401
+ };
402
+ }
403
+
404
+ function planStructuredWorkbenchRequest(requestSource, namespace, planOptions) {
405
+ let request;
406
+ try {
407
+ request = JSON.parse(requestSource);
408
+ } catch (error) {
409
+ return {
410
+ ok: false,
411
+ errors: [{
412
+ code: 'SANSA_MUTATE_WORKBENCH_INVALID_MUTATION_JSON',
413
+ message: error.message,
414
+ phase: 'parse',
415
+ }],
416
+ };
417
+ }
418
+ return planMutation(request, namespace, planOptions);
419
+ }
420
+
421
+ function mutableNamespace(namespace) {
422
+ const root = getRoot(namespace);
423
+ return {
424
+ ...namespace,
425
+ root,
426
+ attributeSpace: (binding) => binding.attributeSpace ?? ensureAttributeSpace(binding),
427
+ mutate: {
428
+ supportsCreate: true,
429
+ supportsReplace: true,
430
+ supportsRemove: true,
431
+ supportsOrderedInsert: true,
432
+ supportsMove: true,
433
+ supportsStableBindingIdentity: true,
434
+ supportsAtomicApply: true,
435
+ bindingHandle: (binding) => binding[HANDLE_PROPERTY],
436
+ observedState: (binding) => binding.revision ?? 0,
437
+ sameBinding: (left, right) => left === right || left?.[HANDLE_PROPERTY] === right?.[HANDLE_PROPERTY],
438
+ create(parent, name, value, operation) {
439
+ const validation = validateAeonWorkbenchValue(value, operation);
440
+ if (!validation.ok) return validation;
441
+ const child = bindingFromJsonValue(value, {
442
+ name,
443
+ datatype: operation.datatype,
444
+ kind: operation.kind,
445
+ address: appendMember(parent.address ?? '$', name),
446
+ parent,
447
+ });
448
+ parent.children = [...(parent.children ?? []), child];
449
+ bump(parent);
450
+ return { binding: child, resultingAddress: child.address };
451
+ },
452
+ replace(target, value, operation) {
453
+ const validation = validateAeonWorkbenchValue(value, operation);
454
+ if (!validation.ok) return validation;
455
+ const replacement = bindingFromJsonValue(value, {
456
+ name: target.name,
457
+ index: target.index,
458
+ datatype: operation.datatype,
459
+ kind: operation.kind,
460
+ address: target.address,
461
+ parent: target.parent,
462
+ handle: target[HANDLE_PROPERTY],
463
+ });
464
+ replaceBindingContents(target, replacement);
465
+ bump(target);
466
+ return { binding: target, resultingAddress: target.address };
467
+ },
468
+ remove(target) {
469
+ const parent = target.parent;
470
+ if (parent) {
471
+ parent.children = (parent.children ?? []).filter((child) => child !== target);
472
+ if (parent.representationKind === 'list') reindexOrderedChildren(parent);
473
+ bump(parent);
474
+ }
475
+ return { binding: target, affectedAddress: target.address };
476
+ },
477
+ insert(container, placement, value, operation) {
478
+ const validation = validateAeonWorkbenchValue(value, operation);
479
+ if (!validation.ok) return validation;
480
+ const child = bindingFromJsonValue(value, {
481
+ datatype: operation.datatype,
482
+ kind: operation.kind,
483
+ address: `${container.address ?? '$'}[new]`,
484
+ parent: container,
485
+ });
486
+ container.children = [...(container.children ?? [])];
487
+ container.children.splice(placementIndex(container, placement), 0, child);
488
+ reindexOrderedChildren(container);
489
+ bump(container);
490
+ return { binding: child, resultingAddress: child.address };
491
+ },
492
+ move(source, container, placement) {
493
+ container.children = (container.children ?? []).filter((child) => child !== source);
494
+ container.children.splice(placementIndex(container, placement), 0, source);
495
+ source.parent = container;
496
+ reindexOrderedChildren(container);
497
+ bump(container);
498
+ return { binding: source, resultingAddress: source.address };
499
+ },
500
+ },
501
+ };
502
+ }
503
+
504
+ function getRoot(namespace) {
505
+ return typeof namespace.root === 'function' ? namespace.root() : namespace.root;
506
+ }
507
+
508
+ function assignStableHandles(binding, counter = { value: 0 }) {
509
+ if (!binding || typeof binding !== 'object') return;
510
+ if (!Object.hasOwn(binding, HANDLE_PROPERTY)) {
511
+ Object.defineProperty(binding, HANDLE_PROPERTY, {
512
+ value: `${HANDLE_PREFIX}:${counter.value}`,
513
+ enumerable: false,
514
+ configurable: true,
515
+ });
516
+ counter.value += 1;
517
+ }
518
+ for (const child of binding.children ?? []) {
519
+ child.parent = binding;
520
+ assignStableHandles(child, counter);
521
+ }
522
+ if (binding.attributeSpace) {
523
+ binding.attributeSpace.parent = binding;
524
+ assignStableHandles(binding.attributeSpace, counter);
525
+ }
526
+ }
527
+
528
+ function ensureAttributeSpace(binding) {
529
+ if (!binding || typeof binding !== 'object') return undefined;
530
+ if (binding.representationKind === 'attributeSpace') return undefined;
531
+ binding.attributeSpace = {
532
+ address: `${binding.address ?? '$'}.@`,
533
+ representationKind: 'attributeSpace',
534
+ parent: binding,
535
+ revision: 0,
536
+ children: [],
537
+ };
538
+ Object.defineProperty(binding.attributeSpace, HANDLE_PROPERTY, {
539
+ value: `${HANDLE_PREFIX}:attribute:${binding[HANDLE_PROPERTY] ?? binding.address ?? Math.random().toString(36).slice(2)}`,
540
+ enumerable: false,
541
+ configurable: true,
542
+ });
543
+ return binding.attributeSpace;
544
+ }
545
+
546
+ function validateAeonWorkbenchValue(value, hints = {}, path = 'value') {
547
+ const representation = representationKindFromHints(hints);
548
+ if (representation === 'node') return validateAeonWorkbenchNodeValue(value, path);
549
+ const scalarValidation = validateAeonWorkbenchScalarValue(value, representation, path);
550
+ if (!scalarValidation.ok) return scalarValidation;
551
+ if (Array.isArray(value)) {
552
+ for (let index = 0; index < value.length; index += 1) {
553
+ const result = validateAeonWorkbenchValue(value[index], {}, `${path}[${index}]`);
554
+ if (!result.ok) return result;
555
+ }
556
+ return { ok: true };
557
+ }
558
+ if (value && typeof value === 'object') {
559
+ for (const [key, entry] of Object.entries(value)) {
560
+ const entryPath = `${path}${renderWorkbenchValuePathSegment(key)}`;
561
+ if (key.length === 0) return invalidAeonWorkbenchValue('Keys must not be empty', entryPath);
562
+ const result = validateAeonWorkbenchValue(entry, {}, entryPath);
563
+ if (!result.ok) return result;
564
+ }
565
+ }
566
+ return { ok: true };
567
+ }
568
+
569
+ function validateAeonWorkbenchNodeValue(value, path) {
570
+ if (value === undefined || value === null) return { ok: true };
571
+ if (Array.isArray(value)) return validateAeonWorkbenchValue(value, {}, `${path}.children`);
572
+ if (typeof value !== 'object') {
573
+ return invalidAeonWorkbenchValue('Node values must be an object with tag/children or an array of children', path);
574
+ }
575
+ if (value.tag !== undefined && !validNodeTag(value.tag)) {
576
+ return invalidAeonWorkbenchValue('Node tags must be non-empty AEON identifiers', `${path}.tag`);
577
+ }
578
+ if (value.children !== undefined && !Array.isArray(value.children)) {
579
+ return invalidAeonWorkbenchValue('Node children must be a list when provided', `${path}.children`);
580
+ }
581
+ if (Array.isArray(value.children)) {
582
+ for (let index = 0; index < value.children.length; index += 1) {
583
+ const result = validateAeonWorkbenchValue(value.children[index], {}, `${path}.children[${index}]`);
584
+ if (!result.ok) return result;
585
+ }
586
+ }
587
+ if (value.attributes !== undefined) {
588
+ if (!value.attributes || typeof value.attributes !== 'object' || Array.isArray(value.attributes)) {
589
+ return invalidAeonWorkbenchValue('Node attributes must be an object when provided', `${path}.attributes`);
590
+ }
591
+ for (const [key, entry] of Object.entries(value.attributes)) {
592
+ const entryPath = `${path}.attributes${renderWorkbenchValuePathSegment(key)}`;
593
+ if (key.length === 0) return invalidAeonWorkbenchValue('Keys must not be empty', entryPath);
594
+ const result = validateAeonWorkbenchValue(entry, {}, entryPath);
595
+ if (!result.ok) return result;
596
+ }
597
+ }
598
+ return { ok: true };
599
+ }
600
+
601
+ function invalidAeonWorkbenchValue(message, path) {
602
+ return {
603
+ ok: false,
604
+ message: `SANSA_MUTATE_WORKBENCH_INVALID_AEON_VALUE: ${message} at ${path}`,
605
+ };
606
+ }
607
+
608
+ function renderWorkbenchValuePathSegment(key) {
609
+ return AEON_IDENTIFIER_PATTERN.test(String(key)) ? `.${key}` : `[${JSON.stringify(String(key))}]`;
610
+ }
611
+
612
+ function validateAeonWorkbenchScalarValue(value, representation, path) {
613
+ if (representation === undefined || ['object', 'list', 'tuple', 'node'].includes(representation)) {
614
+ return { ok: true };
615
+ }
616
+ switch (representation) {
617
+ case 'string':
618
+ return typeof value === 'string'
619
+ ? { ok: true }
620
+ : invalidAeonWorkbenchValue('String literals must use JSON string payloads', path);
621
+ case 'number':
622
+ return typeof value === 'number' && Number.isFinite(value)
623
+ ? { ok: true }
624
+ : invalidAeonWorkbenchValue('Number literals must use finite JSON number payloads', path);
625
+ case 'boolean':
626
+ return typeof value === 'boolean'
627
+ ? { ok: true }
628
+ : invalidAeonWorkbenchValue('Boolean literals must use JSON boolean payloads', path);
629
+ case 'hex':
630
+ return typeof value === 'string' && /^[0-9A-Fa-f]+$/.test(value)
631
+ ? { ok: true }
632
+ : invalidAeonWorkbenchValue('Hex literals must be non-empty hexadecimal text without the # prefix', path);
633
+ case 'radix':
634
+ return typeof value === 'string' && /^[A-Za-z0-9_]+$/.test(value)
635
+ ? { ok: true }
636
+ : invalidAeonWorkbenchValue('Radix literals must be non-empty ASCII radix text without the % prefix', path);
637
+ case 'encoding':
638
+ return typeof value === 'string' && value.length > 0
639
+ ? { ok: true }
640
+ : invalidAeonWorkbenchValue('Encoding literals must be non-empty text without the & prefix', path);
641
+ case 'separator':
642
+ return typeof value === 'string' && value.length > 0
643
+ ? { ok: true }
644
+ : invalidAeonWorkbenchValue('Separator literals must be non-empty text without the ^ prefix', path);
645
+ case 'sansa':
646
+ case 'sansaAddress':
647
+ return typeof value === 'string' && value.length > 0
648
+ ? { ok: true }
649
+ : invalidAeonWorkbenchValue('SANSA literals must be non-empty address text', path);
650
+ case 'toggle':
651
+ return ['yes', 'no', 'on', 'off'].includes(value)
652
+ ? { ok: true }
653
+ : invalidAeonWorkbenchValue('Toggle literals must be one of yes, no, on, or off', path);
654
+ case 'null':
655
+ return value === null || (typeof value === 'string' && AEON_IDENTIFIER_PATTERN.test(value))
656
+ ? { ok: true }
657
+ : invalidAeonWorkbenchValue('Null literals must be null or an AEON identifier reason', path);
658
+ case 'nan':
659
+ return value === null || value === 'NaN'
660
+ ? { ok: true }
661
+ : invalidAeonWorkbenchValue('NaN literals must use null or "NaN" as the JSON payload', path);
662
+ case 'infinity':
663
+ return ['Infinity', '+Infinity', '-Infinity'].includes(value)
664
+ ? { ok: true }
665
+ : invalidAeonWorkbenchValue('Infinity literals must use "Infinity", "+Infinity", or "-Infinity"', path);
666
+ case 'date':
667
+ case 'time':
668
+ case 'datetime':
669
+ case 'zrut':
670
+ return typeof value === 'string' && value.length > 0
671
+ ? { ok: true }
672
+ : invalidAeonWorkbenchValue(`${representation} literals must be non-empty text`, path);
673
+ case 'cloneReference':
674
+ case 'pointerReference':
675
+ case 'referenceForm':
676
+ return typeof value === 'string' && value.length > 0
677
+ ? { ok: true }
678
+ : invalidAeonWorkbenchValue('Reference literals must be non-empty target text', path);
679
+ default:
680
+ return { ok: true };
681
+ }
682
+ }
683
+
684
+ function bindingFromJsonValue(value, { name, index, datatype, kind, address, parent, handle } = {}) {
685
+ const representation = representationKindFromHints({ datatype, kind });
686
+ const binding = {
687
+ ...(name === undefined ? {} : { name }),
688
+ ...(index === undefined ? {} : { index }),
689
+ address,
690
+ parent,
691
+ revision: 0,
692
+ children: [],
693
+ };
694
+ Object.defineProperty(binding, HANDLE_PROPERTY, {
695
+ value: handle ?? `${HANDLE_PREFIX}:new:${Math.random().toString(36).slice(2)}`,
696
+ enumerable: false,
697
+ configurable: true,
698
+ });
699
+
700
+ if (representation === 'node') {
701
+ return assignNodeBinding(binding, value, { datatype, kind }, address);
702
+ }
703
+
704
+ if (Array.isArray(value)) {
705
+ binding.semanticType = datatype ?? 'list';
706
+ binding.representationKind = representation === 'tuple' ? 'tuple' : 'list';
707
+ binding.children = value.map((entry, childIndex) => bindingFromJsonValue(entry, {
708
+ index: childIndex,
709
+ address: `${address}[${childIndex}]`,
710
+ parent: binding,
711
+ }));
712
+ return binding;
713
+ }
714
+
715
+ if (value && typeof value === 'object') {
716
+ binding.semanticType = datatype ?? 'object';
717
+ binding.representationKind = 'object';
718
+ binding.children = Object.entries(value).map(([key, entry]) => bindingFromJsonValue(entry, {
719
+ name: key,
720
+ address: appendMember(address, key),
721
+ parent: binding,
722
+ }));
723
+ return binding;
724
+ }
725
+
726
+ const scalarValue = scalarValueFromHints(value, { datatype, kind });
727
+ binding.value = scalarValue.value;
728
+ if (scalarValue.nullReason !== undefined) binding.nullReason = scalarValue.nullReason;
729
+ binding.semanticType = datatype ?? semanticTypeFromRepresentationKind(representation) ?? semanticTypeFromJsonValue(value);
730
+ binding.representationKind = scalarValue.representationKind ?? representation ?? semanticTypeFromJsonValue(value);
731
+ binding.scalarKind = scalarValue.scalarKind ?? scalarKindFromHints({ datatype, kind }) ?? binding.representationKind;
732
+ return binding;
733
+ }
734
+
735
+ function scalarValueFromHints(value, hints) {
736
+ const representation = representationKindFromHints(hints);
737
+ if (representation === 'null' && typeof value === 'string') {
738
+ return { value: null, nullReason: value, scalarKind: 'null', representationKind: 'null' };
739
+ }
740
+ if (representation === 'nan') {
741
+ return { value: Number.NaN, scalarKind: 'nan', representationKind: 'nan' };
742
+ }
743
+ if (representation === 'infinity') {
744
+ return {
745
+ value: value === '-Infinity' ? -Infinity : Infinity,
746
+ scalarKind: 'infinity',
747
+ representationKind: 'infinity',
748
+ };
749
+ }
750
+ if (representation === 'cloneReference' || representation === 'pointerReference' || representation === 'referenceForm') {
751
+ const canonical = referenceCanonicalFromWorkbenchValue(value, representation);
752
+ return {
753
+ value: {
754
+ type: canonical.startsWith('~>') ? 'PointerReference' : 'CloneReference',
755
+ canonical,
756
+ },
757
+ scalarKind: 'referenceForm',
758
+ representationKind: canonical.startsWith('~>') ? 'pointerReference' : 'cloneReference',
759
+ };
760
+ }
761
+ return { value };
762
+ }
763
+
764
+ function referenceCanonicalFromWorkbenchValue(value, representation) {
765
+ const text = String(value);
766
+ if (text.startsWith('~>') || text.startsWith('~')) return text;
767
+ return `${representation === 'pointerReference' ? '~>' : '~'}${text}`;
768
+ }
769
+
770
+ function assignNodeBinding(binding, value, hints, address) {
771
+ const node = value && typeof value === 'object' && !Array.isArray(value)
772
+ ? value
773
+ : { children: Array.isArray(value) ? value : [] };
774
+ binding.semanticType = hints.datatype ?? 'node';
775
+ binding.representationKind = 'node';
776
+ binding.nodeTag = validNodeTag(node.tag) ? node.tag : 'node';
777
+ const children = Array.isArray(node.children) ? node.children : [];
778
+ binding.children = children.map((entry, childIndex) => bindingFromJsonValue(entry, {
779
+ index: childIndex,
780
+ address: `${address}[${childIndex}]`,
781
+ parent: binding,
782
+ }));
783
+ if (node.attributes && typeof node.attributes === 'object' && !Array.isArray(node.attributes)) {
784
+ const attributeSpace = {
785
+ address: `${address}.@`,
786
+ representationKind: 'attributeSpace',
787
+ parent: binding,
788
+ revision: 0,
789
+ children: [],
790
+ };
791
+ attributeSpace.children = Object.entries(node.attributes).map(([key, entry]) => bindingFromJsonValue(entry, {
792
+ name: key,
793
+ address: appendMember(`${address}.@`, key),
794
+ parent: attributeSpace,
795
+ }));
796
+ binding.attributeSpace = attributeSpace;
797
+ }
798
+ return binding;
799
+ }
800
+
801
+ function replaceBindingContents(target, replacement) {
802
+ const preserved = {
803
+ name: target.name,
804
+ index: target.index,
805
+ address: target.address,
806
+ parent: target.parent,
807
+ handle: target[HANDLE_PROPERTY],
808
+ attributeSpace: target.attributeSpace,
809
+ };
810
+ for (const key of Object.keys(target)) delete target[key];
811
+ Object.assign(target, replacement, {
812
+ ...(preserved.name === undefined ? {} : { name: preserved.name }),
813
+ ...(preserved.index === undefined ? {} : { index: preserved.index }),
814
+ address: preserved.address,
815
+ parent: preserved.parent,
816
+ attributeSpace: replacement.attributeSpace ?? preserved.attributeSpace,
817
+ });
818
+ Object.defineProperty(target, HANDLE_PROPERTY, {
819
+ value: preserved.handle,
820
+ enumerable: false,
821
+ configurable: true,
822
+ });
823
+ for (const child of target.children ?? []) child.parent = target;
824
+ if (target.attributeSpace) target.attributeSpace.parent = target;
825
+ }
826
+
827
+ function placementIndex(container, placement) {
828
+ if (placement.kind === 'first') return 0;
829
+ if (placement.kind === 'last') return (container.children ?? []).length;
830
+ const anchorIndex = (container.children ?? []).indexOf(placement.anchor.binding);
831
+ return Math.max(0, anchorIndex + (placement.kind === 'after' ? 1 : 0));
832
+ }
833
+
834
+ function reindexOrderedChildren(container) {
835
+ if (!['list', 'tuple', 'node'].includes(container.representationKind)) return;
836
+ container.children = (container.children ?? []).map((child, index) => {
837
+ child.index = index;
838
+ child.name = undefined;
839
+ child.address = `${container.address}[${index}]`;
840
+ child.parent = container;
841
+ readdressDescendants(child);
842
+ return child;
843
+ });
844
+ }
845
+
846
+ function readdressDescendants(binding) {
847
+ for (const child of binding.children ?? []) {
848
+ child.parent = binding;
849
+ child.address = child.name === undefined
850
+ ? `${binding.address}[${child.index}]`
851
+ : appendMember(binding.address, child.name);
852
+ readdressDescendants(child);
853
+ }
854
+ }
855
+
856
+ function bump(binding) {
857
+ binding.revision = (binding.revision ?? 0) + 1;
858
+ }
859
+
860
+ function mutationPlanOptions(options) {
861
+ return {
862
+ ...mutationBudgetOptions(options),
863
+ ...parseLimitOption(options),
864
+ };
865
+ }
866
+
867
+ function mutationApplyOptions(options) {
868
+ return {
869
+ ...mutationBudgetOptions(options),
870
+ ...(options?.requireAtomic === true ? { requireAtomic: true } : {}),
871
+ ...(options?.recheckPreconditions === false ? { recheckPreconditions: false } : {}),
872
+ };
873
+ }
874
+
875
+ function mutationBudgetOptions(options) {
876
+ const budget = {};
877
+ for (const key of ['maxOperations', 'maxPreconditions', 'maxValueNodes', 'maxValueDepth', 'maxStringLength']) {
878
+ if (Number.isSafeInteger(options?.[key]) && options[key] >= 0) budget[key] = options[key];
879
+ }
880
+ return Object.keys(budget).length === 0 ? {} : { budget };
881
+ }
882
+
883
+ function parseLimitOption(options) {
884
+ if (!Number.isSafeInteger(options?.maxPositionIndex) || options.maxPositionIndex < 0) return {};
885
+ return { parse: { maxPositionIndex: options.maxPositionIndex } };
886
+ }
887
+
888
+ function summarizePlan(plan) {
889
+ return {
890
+ type: plan.type,
891
+ planVersion: plan.planVersion,
892
+ planId: plan.planId,
893
+ namespaceState: sanitizeJsonValue(plan.namespaceState),
894
+ operations: plan.operations.map(summarizeOperation),
895
+ preconditions: plan.preconditions.map((precondition) => ({
896
+ expression: precondition.expression,
897
+ canonical: precondition.canonical,
898
+ ...(precondition.target ? { target: summarizeTarget(precondition.target) } : {}),
899
+ })),
900
+ sourceProvenance: sanitizeJsonValue(plan.sourceProvenance),
901
+ portabilityWarnings: normalizeDiagnostics(plan.portabilityWarnings ?? []),
902
+ diagnostics: normalizeDiagnostics(plan.diagnostics ?? []),
903
+ };
904
+ }
905
+
906
+ function summarizeOperation(operation) {
907
+ return {
908
+ op: operation.op,
909
+ ...(operation.target ? { target: summarizeTarget(operation.target) } : {}),
910
+ ...(operation.parent ? { parent: summarizeTarget(operation.parent) } : {}),
911
+ ...(operation.source ? { source: summarizeTarget(operation.source) } : {}),
912
+ ...(operation.container ? { container: summarizeTarget(operation.container) } : {}),
913
+ ...(operation.placement ? { placement: summarizePlacement(operation.placement) } : {}),
914
+ ...(operation.name === undefined ? {} : { name: operation.name }),
915
+ ...(operation.datatype === undefined ? {} : { datatype: operation.datatype }),
916
+ ...(operation.kind === undefined ? {} : { kind: operation.kind }),
917
+ ...(operation.value === undefined ? {} : { value: sanitizeJsonValue(operation.value) }),
918
+ ...(operation.provenance === undefined ? {} : { provenance: sanitizeJsonValue(operation.provenance) }),
919
+ };
920
+ }
921
+
922
+ function summarizePlacement(placement) {
923
+ return {
924
+ kind: placement.kind,
925
+ ...(placement.anchor ? { anchor: summarizeTarget(placement.anchor) } : {}),
926
+ };
927
+ }
928
+
929
+ function summarizeTarget(target) {
930
+ return {
931
+ requestedAddress: target.requestedAddress,
932
+ canonicalAddress: target.canonicalAddress,
933
+ bindingHandle: sanitizeJsonValue(target.bindingHandle),
934
+ observedState: sanitizeJsonValue(target.observedState),
935
+ portabilityWarnings: normalizeDiagnostics(target.portabilityWarnings ?? []),
936
+ };
937
+ }
938
+
939
+ function summarizeOperationResults(results) {
940
+ return results.map((entry) => ({
941
+ operationIndex: entry.operationIndex,
942
+ status: entry.status,
943
+ targetAddress: entry.targetAddress,
944
+ parentAddress: entry.parentAddress,
945
+ containerAddress: entry.containerAddress,
946
+ sourceAddress: entry.sourceAddress,
947
+ anchorAddress: entry.anchorAddress,
948
+ previousAddress: entry.previousAddress,
949
+ affectedAddress: entry.affectedAddress,
950
+ resultingAddress: entry.resultingAddress,
951
+ affectedBinding: entry.affectedBinding ? summarizeBinding(entry.affectedBinding) : undefined,
952
+ }));
953
+ }
954
+
955
+ function summarizeBinding(binding) {
956
+ return {
957
+ address: binding.address,
958
+ name: binding.name,
959
+ index: binding.index,
960
+ semanticType: binding.semanticType,
961
+ representationKind: binding.representationKind,
962
+ scalarKind: binding.scalarKind,
963
+ nullReason: binding.nullReason,
964
+ nodeTag: binding.nodeTag,
965
+ value: sanitizeJsonValue(binding.value),
966
+ };
967
+ }
968
+
969
+ function renderPlanText(plan) {
970
+ const lines = [
971
+ `planVersion: ${plan.planVersion}`,
972
+ `operations: ${plan.operations.length}`,
973
+ ];
974
+ for (const [index, operation] of plan.operations.entries()) {
975
+ const target = operation.target ?? operation.parent ?? operation.source ?? operation.container;
976
+ lines.push(`${index}: ${operation.op} ${target?.canonicalAddress ?? ''}`.trim());
977
+ }
978
+ if (plan.sourceProvenance?.reason !== undefined || plan.sourceProvenance?.claimedAuthor !== undefined) {
979
+ lines.push('', 'provenance:');
980
+ if (plan.sourceProvenance.reason !== undefined) lines.push(`because ${JSON.stringify(plan.sourceProvenance.reason)}`);
981
+ if (plan.sourceProvenance.claimedAuthor !== undefined) lines.push(`by ${JSON.stringify(plan.sourceProvenance.claimedAuthor)}`);
982
+ }
983
+ if ((plan.preconditions ?? []).length > 0) {
984
+ lines.push('', `preconditions: ${plan.preconditions.length}`);
985
+ for (const [index, precondition] of plan.preconditions.entries()) {
986
+ lines.push(`${index}: require ${precondition.canonical}${precondition.target?.canonicalAddress === undefined ? '' : ` at ${precondition.target.canonicalAddress}`}`);
987
+ }
988
+ }
989
+ if ((plan.portabilityWarnings ?? []).length > 0) {
990
+ lines.push('', 'portabilityWarnings:', ...plan.portabilityWarnings.map((warning) => `- ${warning.code}: ${warning.message}`));
991
+ }
992
+ return lines.join('\n');
993
+ }
994
+
995
+ function renderApplyText(result) {
996
+ return [
997
+ `applied: ${result.operationResults.length}`,
998
+ ...result.operationResults.map((entry) => (
999
+ `${entry.operationIndex}: ${entry.status} ${entry.previousAddress ?? entry.parentAddress ?? entry.containerAddress ?? ''} -> ${entry.resultingAddress ?? entry.affectedAddress ?? '(none)'}`
1000
+ )),
1001
+ ].join('\n');
1002
+ }
1003
+
1004
+ function renderBindingTree(root) {
1005
+ return (root.children ?? []).flatMap((child) => renderNamedBinding(child, 0)).join('\n');
1006
+ }
1007
+
1008
+ function renderNamedBinding(binding, depth) {
1009
+ const indent = ' '.repeat(depth);
1010
+ const label = binding.name === undefined ? renderAnonymousPrefix(binding) : renderBindingName(binding.name);
1011
+ const datatype = renderDatatype(binding);
1012
+ const head = `${indent}${label}${renderInlineAttributes(binding)}:${datatype} = `;
1013
+ return renderBindingAssignment(binding, depth, head);
1014
+ }
1015
+
1016
+ function renderAnonymousBinding(binding, depth) {
1017
+ const indent = ' '.repeat(depth);
1018
+ const datatype = renderDatatype(binding);
1019
+ const attributes = renderInlineAttributes(binding);
1020
+ const head = attributes
1021
+ ? `${indent}${attributes}:${datatype} = `
1022
+ : `${indent}`;
1023
+ return renderBindingAssignment(binding, depth, head);
1024
+ }
1025
+
1026
+ function renderBindingAssignment(binding, depth, head) {
1027
+ if (isContainerBinding(binding)) {
1028
+ return renderContainerAssignment(binding, depth, head);
1029
+ }
1030
+ return [`${head}${renderScalarValue(binding)}`];
1031
+ }
1032
+
1033
+ function isContainerBinding(binding) {
1034
+ return ['object', 'list', 'tuple', 'node'].includes(binding.representationKind);
1035
+ }
1036
+
1037
+ function renderContainerAssignment(binding, depth, head) {
1038
+ const indent = ' '.repeat(depth);
1039
+ const kind = binding.representationKind;
1040
+ if (kind === 'list') {
1041
+ return [
1042
+ `${head}[`,
1043
+ ...(binding.children ?? []).flatMap((child) => renderAnonymousBinding(child, depth + 1)),
1044
+ `${indent}]`,
1045
+ ];
1046
+ }
1047
+ if (kind === 'tuple') {
1048
+ return [
1049
+ `${head}(`,
1050
+ ...(binding.children ?? []).flatMap((child) => renderAnonymousBinding(child, depth + 1)),
1051
+ `${indent})`,
1052
+ ];
1053
+ }
1054
+ if (kind === 'node') {
1055
+ const tag = validNodeTag(binding.nodeTag) ? binding.nodeTag : 'node';
1056
+ if ((binding.children ?? []).length === 0) return [`${head}<${tag}>`];
1057
+ return [
1058
+ `${head}<${tag}(`,
1059
+ ...(binding.children ?? []).flatMap((child) => renderAnonymousBinding(child, depth + 1)),
1060
+ `${indent})>`,
1061
+ ];
1062
+ }
1063
+ return [
1064
+ `${head}{`,
1065
+ ...(binding.children ?? []).flatMap((child) => renderNamedBinding(child, depth + 1)),
1066
+ `${indent}}`,
1067
+ ];
1068
+ }
1069
+
1070
+ function renderAnonymousPrefix(binding) {
1071
+ if (binding.index !== undefined) return `[${binding.index}]`;
1072
+ return renderBindingName(String(binding.name ?? 'value'));
1073
+ }
1074
+
1075
+ function renderBindingName(name) {
1076
+ return AEON_IDENTIFIER_PATTERN.test(name) ? name : JSON.stringify(String(name));
1077
+ }
1078
+
1079
+ function renderDatatype(binding) {
1080
+ return binding.semanticType ?? semanticTypeFromJsonValue(binding.value);
1081
+ }
1082
+
1083
+ function renderInlineAttributes(binding) {
1084
+ const attributes = binding.attributeSpace?.children ?? [];
1085
+ if (attributes.length === 0) return '';
1086
+ return `@{${attributes.map(renderAttributeBinding).join(', ')}}`;
1087
+ }
1088
+
1089
+ function validNodeTag(value) {
1090
+ return typeof value === 'string' && AEON_IDENTIFIER_PATTERN.test(value);
1091
+ }
1092
+
1093
+ function renderAttributeBinding(binding) {
1094
+ return `${renderBindingName(binding.name)}:${renderDatatype(binding)} = ${renderScalarValue(binding)}`;
1095
+ }
1096
+
1097
+ function renderScalarValue(binding) {
1098
+ const value = binding.value;
1099
+ const kind = binding.scalarKind ?? binding.valueKind ?? binding.literalKind ?? binding.representationKind ?? binding.kind ?? binding.type;
1100
+ const datatypeBase = typeof binding.semanticType === 'string'
1101
+ ? binding.semanticType.split(/[<\[]/, 1)[0]
1102
+ : undefined;
1103
+ if (['trimtick', 'prose'].includes(datatypeBase)) return renderBlockString(value);
1104
+ if ((kind === 'null' || value === null) && typeof binding.nullReason === 'string') return `!${binding.nullReason}`;
1105
+ if (kind === 'nan' || (typeof value === 'number' && Number.isNaN(value))) return 'NaN';
1106
+ if (value === -Infinity) return '-Infinity';
1107
+ if (kind === 'infinity' || value === Infinity) return 'Infinity';
1108
+ if (kind === 'toggle') return String(value);
1109
+ if (kind === 'hex') return `#${value}`;
1110
+ if (kind === 'radix') return `%${value}`;
1111
+ if (kind === 'encoding') return `&${value}`;
1112
+ if (kind === 'separator') return `^${value}`;
1113
+ if (['date', 'time', 'datetime', 'zrut'].includes(kind)) return String(value);
1114
+ if (kind === 'sansaAddress' || kind === 'sansa') {
1115
+ return value?.canonical ?? value?.address?.canonical ?? value?.address ?? String(value);
1116
+ }
1117
+ if (kind === 'referenceForm') return value?.canonical ?? JSON.stringify(value);
1118
+ if (typeof value === 'string') return JSON.stringify(value);
1119
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
1120
+ if (value === null) return 'null';
1121
+ return JSON.stringify(value);
1122
+ }
1123
+
1124
+ function renderBlockString(value) {
1125
+ const text = String(value ?? '').replace(/\\/g, '\\\\').replace(/`/g, '\\`');
1126
+ return `>\`${text}\``;
1127
+ }
1128
+
1129
+ function renderDiagnosticText(errors, options = {}) {
1130
+ if (!Array.isArray(errors) || errors.length === 0) return '(no diagnostics)';
1131
+ const lines = [];
1132
+ if (options.includeSummary !== false) {
1133
+ const summary = renderDiagnosticPhaseSummary(errors, options.fallbackPhase);
1134
+ if (summary) lines.push(summary, '');
1135
+ }
1136
+ lines.push(...errors.map((error) => {
1137
+ const phase = typeof error.phase === 'string' ? ` [${error.phase}]` : '';
1138
+ const operation = Number.isInteger(error.operationIndex) ? ` operation ${error.operationIndex}` : '';
1139
+ const rule = Number.isInteger(error.ruleIndex) ? ` rule ${error.ruleIndex}` : '';
1140
+ const budget = typeof error.budget === 'string' ? ` ${error.budget}` : '';
1141
+ const location = Number.isInteger(error.index) ? ` index ${error.index}` : '';
1142
+ const details = renderDiagnosticDetails(error);
1143
+ const cause = error.cause && typeof error.cause === 'object'
1144
+ ? `\n cause ${renderDiagnosticText([error.cause], { includeSummary: false })}`
1145
+ : '';
1146
+ return `${error.code}${phase}${operation}${rule}${budget}${location}${details}: ${error.message}${cause}`;
1147
+ }));
1148
+ return lines.join('\n');
1149
+ }
1150
+
1151
+ function renderDiagnosticPhaseSummary(errors, fallbackPhase) {
1152
+ const phase = primaryDiagnosticPhase(normalizeDiagnostics(errors), fallbackPhase);
1153
+ if (phase === 'target') {
1154
+ const targetFormat = errors.find((error) => typeof error?.targetFormat === 'string')?.targetFormat;
1155
+ const suffix = targetFormat ? ` for target '${targetFormat}'` : '';
1156
+ return `target-surface: plan produced; selected target cannot represent the planned intent${suffix}`;
1157
+ }
1158
+ if (phase === 'plan') return 'plan: mutation request could not be planned';
1159
+ if (phase === 'policy') return 'policy: planned operation was rejected by workbench policy';
1160
+ if (phase === 'apply') return 'apply: plan could not be applied by the mutation adapter';
1161
+ if (phase === 'parse') return 'parse: request source could not be parsed';
1162
+ if (phase === 'lower') return 'lower: instruction source could not be lowered to exact mutation intent';
1163
+ return '';
1164
+ }
1165
+
1166
+ function renderDiagnosticDetails(error) {
1167
+ const parts = [];
1168
+ if (typeof error.targetFormat === 'string') parts.push(`target ${error.targetFormat}`);
1169
+ if (typeof error.datatype === 'string') parts.push(`datatype ${error.datatype}`);
1170
+ if (typeof error.valuePath === 'string') parts.push(`value ${error.valuePath}`);
1171
+ if (typeof error.policyField === 'string') parts.push(`field ${error.policyField}`);
1172
+ if (typeof error.policyScope === 'string') parts.push(`scope ${error.policyScope}`);
1173
+ if (typeof error.policyAddress === 'string') parts.push(`address ${error.policyAddress}`);
1174
+ return parts.length === 0 ? '' : ` (${parts.join(', ')})`;
1175
+ }
1176
+
1177
+ function normalizeDiagnostics(errors) {
1178
+ return (errors ?? []).map((error) => ({
1179
+ code: error.code,
1180
+ message: error.message,
1181
+ ...(typeof error.phase === 'string' ? { phase: error.phase } : {}),
1182
+ ...(Number.isInteger(error.operationIndex) ? { operationIndex: error.operationIndex } : {}),
1183
+ ...(Number.isInteger(error.preconditionIndex) ? { preconditionIndex: error.preconditionIndex } : {}),
1184
+ ...(Number.isInteger(error.ruleIndex) ? { ruleIndex: error.ruleIndex } : {}),
1185
+ ...(typeof error.policyField === 'string' ? { policyField: error.policyField } : {}),
1186
+ ...(typeof error.policyScope === 'string' ? { policyScope: error.policyScope } : {}),
1187
+ ...(typeof error.policyAddress === 'string' ? { policyAddress: error.policyAddress } : {}),
1188
+ ...(typeof error.budget === 'string' ? { budget: error.budget } : {}),
1189
+ ...(typeof error.targetFormat === 'string' ? { targetFormat: error.targetFormat } : {}),
1190
+ ...(typeof error.datatype === 'string' ? { datatype: error.datatype } : {}),
1191
+ ...(typeof error.valuePath === 'string' ? { valuePath: error.valuePath } : {}),
1192
+ ...(Number.isSafeInteger(error.limit) ? { limit: error.limit } : {}),
1193
+ ...(Number.isSafeInteger(error.observed) ? { observed: error.observed } : {}),
1194
+ ...(Number.isInteger(error.index) ? { index: error.index } : {}),
1195
+ ...(error.cause ? { cause: normalizeDiagnostics([error.cause])[0] } : {}),
1196
+ }));
1197
+ }
1198
+
1199
+ function primaryDiagnosticPhase(errors, fallback) {
1200
+ const first = Array.isArray(errors) ? errors[0] : null;
1201
+ if (typeof first?.phase === 'string') return first.phase;
1202
+ if (typeof fallback === 'string') return fallback;
1203
+ return undefined;
1204
+ }
1205
+
1206
+ function errorResult(code, message, mode) {
1207
+ const errors = [{ code, message }];
1208
+ return {
1209
+ ok: false,
1210
+ mode,
1211
+ text: renderDiagnosticText(errors),
1212
+ errors,
1213
+ };
1214
+ }
1215
+
1216
+ function appendMember(base, name) {
1217
+ return AEON_IDENTIFIER_PATTERN.test(name)
1218
+ ? `${base}.${name}`
1219
+ : `${base}.[${JSON.stringify(name)}]`;
1220
+ }
1221
+
1222
+ function semanticTypeFromJsonValue(value) {
1223
+ if (value === null) return 'null';
1224
+ if (Array.isArray(value)) return 'list';
1225
+ return typeof value;
1226
+ }
1227
+
1228
+ function semanticTypeFromRepresentationKind(kind) {
1229
+ if (typeof kind !== 'string') return undefined;
1230
+ switch (kind) {
1231
+ case 'string':
1232
+ case 'number':
1233
+ case 'boolean':
1234
+ case 'toggle':
1235
+ case 'hex':
1236
+ case 'radix':
1237
+ case 'encoding':
1238
+ case 'separator':
1239
+ case 'sansa':
1240
+ case 'date':
1241
+ case 'time':
1242
+ case 'datetime':
1243
+ case 'zrut':
1244
+ case 'null':
1245
+ case 'nan':
1246
+ case 'infinity':
1247
+ case 'cloneReference':
1248
+ case 'pointerReference':
1249
+ case 'referenceForm':
1250
+ return kind === 'sansa' ? 'sansa' : kind;
1251
+ default:
1252
+ return undefined;
1253
+ }
1254
+ }
1255
+
1256
+ function representationKindFromHints({ datatype, kind } = {}) {
1257
+ return kind === undefined
1258
+ ? representationKindFromName(datatype, { allowUnknown: false })
1259
+ : representationKindFromName(kind, { allowUnknown: true });
1260
+ }
1261
+
1262
+ function representationKindFromName(name, { allowUnknown = false } = {}) {
1263
+ const base = datatypeBaseName(name);
1264
+ const lowered = typeof base === 'string' ? base.toLowerCase() : base;
1265
+ if (['object', 'obj', 'o', 'envelope'].includes(base)) return 'object';
1266
+ if (base === 'list') return 'list';
1267
+ if (base === 'tuple') return 'tuple';
1268
+ if (base === 'node') return 'node';
1269
+ if (['string', 'trimtick', 'prose'].includes(base)) return 'string';
1270
+ if (['number', 'int', 'uint', 'float', 'n'].includes(base)) return 'number';
1271
+ if (base === 'bool' || base === 'boolean') return 'boolean';
1272
+ if (base === 'toggle') return 'toggle';
1273
+ if (base === 'hex') return 'hex';
1274
+ if (lowered === 'radix' || /^radix\d+$/.test(lowered)) return 'radix';
1275
+ if (base === 'nan') return 'nan';
1276
+ if (base === 'infinity') return 'infinity';
1277
+ if (base === 'null') return 'null';
1278
+ if (base === 'sep' || base === 'separator' || base === 'kadot') return 'separator';
1279
+ if (base === 'sansa') return 'sansa';
1280
+ if (base === 'encoding' || ['base64', 'embed', 'inline'].includes(base)) return 'encoding';
1281
+ if (['date', 'time', 'datetime', 'zrut'].includes(base)) return base;
1282
+ if (['cloneReference', 'pointerReference', 'referenceForm'].includes(base)) return base;
1283
+ return allowUnknown ? base : undefined;
1284
+ }
1285
+
1286
+ function scalarKindFromHints(hints) {
1287
+ const kind = representationKindFromHints(hints);
1288
+ if (kind === 'sansa') return 'sansaAddress';
1289
+ return kind;
1290
+ }
1291
+
1292
+ function datatypeBaseName(datatype) {
1293
+ if (typeof datatype !== 'string') return undefined;
1294
+ const genericCut = datatype.indexOf('<');
1295
+ const argumentCut = datatype.indexOf('[');
1296
+ const cut = [genericCut, argumentCut].filter((index) => index >= 0).sort((left, right) => left - right)[0];
1297
+ return (cut === undefined ? datatype : datatype.slice(0, cut)).trim();
1298
+ }
1299
+
1300
+ function sanitizeJsonValue(value) {
1301
+ if (value === undefined) return undefined;
1302
+ if (typeof value === 'number' && !Number.isFinite(value)) return String(value);
1303
+ if (Array.isArray(value)) return value.map(sanitizeJsonValue);
1304
+ if (value && typeof value === 'object') {
1305
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, sanitizeJsonValue(entry)]));
1306
+ }
1307
+ return value;
1308
+ }