@niscorp/prism 0.2.2 → 0.3.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +203 -0
  2. package/DESIGN.md +9 -8
  3. package/DOCS.md +71 -26
  4. package/README.md +45 -24
  5. package/dist/agent.cjs +7 -9
  6. package/dist/agent.cjs.map +1 -1
  7. package/dist/agent.js +5 -7
  8. package/dist/agent.js.map +1 -1
  9. package/dist/{chunk-26VYDHHC.cjs → chunk-6PD7M2F3.cjs} +266 -112
  10. package/dist/chunk-6PD7M2F3.cjs.map +1 -0
  11. package/dist/{chunk-XRK55NPE.js → chunk-GK4CIKKT.js} +5 -10
  12. package/dist/chunk-GK4CIKKT.js.map +1 -0
  13. package/dist/{chunk-W32JXP33.cjs → chunk-OWKINPR5.cjs} +7 -12
  14. package/dist/chunk-OWKINPR5.cjs.map +1 -0
  15. package/dist/{chunk-O3OJAQWA.js → chunk-WKS4OCKN.js} +260 -113
  16. package/dist/chunk-WKS4OCKN.js.map +1 -0
  17. package/dist/examples/index.cjs +25 -2
  18. package/dist/examples/index.cjs.map +1 -1
  19. package/dist/examples/index.d.cts +1 -1
  20. package/dist/examples/index.d.ts +1 -1
  21. package/dist/examples/index.js +25 -2
  22. package/dist/examples/index.js.map +1 -1
  23. package/dist/index.cjs +1223 -139
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +9 -6
  26. package/dist/index.d.ts +9 -6
  27. package/dist/index.js +1119 -28
  28. package/dist/index.js.map +1 -1
  29. package/dist/migrations/index.cjs +8 -17
  30. package/dist/migrations/index.cjs.map +1 -1
  31. package/dist/migrations/index.d.cts +0 -2
  32. package/dist/migrations/index.d.ts +0 -2
  33. package/dist/migrations/index.js +7 -12
  34. package/dist/migrations/index.js.map +1 -1
  35. package/dist/{profiles-C6r-x-Vj.d.cts → profiles-CPVfysxC.d.cts} +2 -1
  36. package/dist/{profiles-C6r-x-Vj.d.ts → profiles-CPVfysxC.d.ts} +2 -1
  37. package/package.json +7 -7
  38. package/dist/chunk-26VYDHHC.cjs.map +0 -1
  39. package/dist/chunk-O3OJAQWA.js.map +0 -1
  40. package/dist/chunk-V426VIRI.cjs +0 -1168
  41. package/dist/chunk-V426VIRI.cjs.map +0 -1
  42. package/dist/chunk-VC4PRB4H.js +0 -1086
  43. package/dist/chunk-VC4PRB4H.js.map +0 -1
  44. package/dist/chunk-W32JXP33.cjs.map +0 -1
  45. package/dist/chunk-XRK55NPE.js.map +0 -1
  46. package/dist/transform-DcVcOBzQ.d.cts +0 -3
  47. package/dist/transform-DcVcOBzQ.d.ts +0 -3
package/CHANGELOG.md CHANGED
@@ -1,5 +1,208 @@
1
1
  # @niscorp/prism
2
2
 
3
+ ## 0.3.1
4
+
5
+ ### Patch Changes
6
+
7
+ - f55fcbe: DOCS.md and the README state seven facts about the API that were written only in source comments.
8
+
9
+ DOCS.md: a negative index in a `$ref` path is refused, the generated JSON Schema does not carry the `$ref` path rule, and `maxValues` counts a value each time it appears. README: an example's `id` is unique and in kebab-case, an example of several operators has no `op`, which ops `MAPPING_OPS` leaves out, and that the mapping agent's `data` is the config itself.
10
+
11
+ No behaviour changed.
12
+
13
+ **What to change:** nothing.
14
+
15
+ - 89adcc3: The optimizer no longer keeps a local `isPlainObject` that only called `isJsonObject`; its three uses call `isJsonObject`. Prism's own `isPlainObject` means an object with no `$` key, and the local one of the same name meant any JSON object. No behaviour changed.
16
+
17
+ **What to change:** nothing.
18
+
19
+ ## 0.3.0
20
+
21
+ ### Minor Changes
22
+
23
+ - f834f3f: `evaluate` checks a config object once and only evaluates it after that; `prismTransform` is gone. **Breaking.**
24
+
25
+ BREAKING — approved by moccadroid, 2026-10-09: replace `prismTransform` with `evaluate` (`transform: evaluate`), and pass limits as `{ limits: … }`.
26
+
27
+ Prism had three ways to run a config, and the one a host was told to hand to its seam (`prismTransform`) was the one that reported worst, while the hosts on a hot path each wrapped `evaluate`, which checked the config on every call. There are two now, with one job each.
28
+
29
+ **`evaluate(config, source, options?)`** — for a config a program holds.
30
+ - The first time it is handed a config object it checks it and keeps its tree; the second time it prepares the tree as `compile` would; from then on a call only evaluates. Four fields picked and renamed, the same config object again: 3.5 µs before, 0.4 µs now. A nested choice on two fields: 18 µs before, 0.7 µs now. A config that is a new object on every call costs what it did.
31
+ - It is kept **by the object**: a config changed in place after its first call is not read again. Hand over a new object.
32
+ - Both arguments are `unknown`, so it is what a host's transform seam takes: `createTide({ transform: evaluate })`, `createUpgrader(grammars, { transform: evaluate })`.
33
+ - The third argument is `{ limits?, check? }`. Limits were the third argument themselves: `evaluate(config, source, { maxSteps: 100 })` is now `evaluate(config, source, { limits: { maxSteps: 100 } })`.
34
+ - `check: 'always'` is for writing a config, for tests and for tools: nothing is kept, the config is checked on every call, and the source must be plain JSON (a source holding `undefined`, a function, a `Date` or a non-finite number is refused with `E_TYPE`).
35
+ - An invalid config is a `PrismError` (`E_SCHEMA`) naming the part that is wrong, however deep the config. `prismTransform` threw zod's own error, and a `RangeError` for a config nested far past the limit.
36
+
37
+ `evaluateSafe` takes the same arguments.
38
+
39
+ **`compile` and `execute`** — for a config that is stored. Unchanged.
40
+
41
+ **`prismTransform` is removed**, from `@niscorp/prism` and from `@niscorp/prism/migrations`. What it added over `evaluate` was a check that the source is plain JSON; that check is now `check: 'always'`, and a seam's source is taken as it is.
42
+
43
+ **moss, nova, vex, loom, nisc, create-nisc and the cli move with it.** Each has Prism as a peer or a dependency, or has one of those that do, and a Prism at 0.3 is outside the range their last versions accept: an app takes them together. Nothing in vex, loom or the cli changed beyond that range.
44
+
45
+ moss's shell and nova's `$prism` binding called `evaluate` on every use and so paid the check each time: an endpoint's request and response under moss, and a `$prism` value on each draw and for each row of a list, are 8 to 45 times faster for the configs measured. tide's and strata's documentation name `evaluate` where they named `prismTransform`.
46
+
47
+ **What to change**
48
+ - `import { prismTransform } from '@niscorp/prism'` or `'@niscorp/prism/migrations'` → `import { evaluate } from '@niscorp/prism'`, and `transform: prismTransform` → `transform: evaluate`. Every app made by `create-nisc` has this in `src/dev/strata.ts`; the app's typecheck and `npm run strata` both stop on that line until it is changed.
49
+ - A third argument of limits becomes `{ limits: … }`.
50
+ - A wrapper that parsed the config before calling `evaluate` (`evaluate(ConfigSchema.parse(config), …)`) makes a new object on every call and so is checked on every call: hand `evaluate` the config itself.
51
+ - Code that changes a config object in place and evaluates it again must hand over a new object, or pass `{ check: 'always' }`.
52
+ - A host that relied on `prismTransform` refusing a source that is not plain JSON checks it itself, or passes `{ check: 'always' }`.
53
+
54
+ ### Patch Changes
55
+
56
+ - 023bcf9: `compile` no longer reads a `$with` binding or a `$renameKeys` key that is named like an op as that op.
57
+
58
+ A `$with` binding and a `$renameKeys` map are keyed by names, and a name may start with `$`. The optimizer walked those records as nodes, so where a name was an op's, `execute` did not answer as `evaluate` does:
59
+
60
+ ```ts
61
+ { $with: { let: { $upper: 'x' }, value: { $var: '$upper' } } }
62
+ // evaluate: 'x'. execute: "Variable not found: $upper" — the binding had been folded to { $const: 'X' }.
63
+
64
+ { $with: { let: { $ref: 2 }, value: { $var: '$ref' } } }
65
+ // evaluate: 2. compile threw TypeError: path.startsWith is not a function.
66
+
67
+ { $renameKeys: { from: { $ref: '$' }, map: { $upper: 'x' } } } // over { $upper: 1 }
68
+ // evaluate: { x: 1 }. execute: { $upper: 1 } — the key was not renamed.
69
+ ```
70
+
71
+ `execute` now answers all three as `evaluate` does, from a fresh IR and from one read back from storage. A config with no such name compiles to the same core and the same fingerprint as before. One with such a name compiles to a different core, so its fingerprint changes.
72
+
73
+ **What to change:** nothing. An IR compiled earlier from such a config and stored keeps its wrong answer until it is compiled again.
74
+
75
+ - 1db6df4: A plain object template is recognised before the ops are tried, not after: `execute` and `evaluate` are up to four times faster on configs that are templates.
76
+
77
+ A template such as `{ id: { $ref: '$.id' }, name: … }` is not an op, so the compiler attaches no handler to it, and the evaluator reached it only after asking about sixty times whether it was some op. It did that on every evaluation, in a compiled tree too, and once for each row where the template is the body of a `$map`. A template has no `$` key and every op needs one, so asking for the template first changes no answer.
78
+
79
+ Measured, Node 24, one order unless said:
80
+
81
+ | | before | now |
82
+ | -------------------------------------------- | ------- | ------- |
83
+ | `execute`, four fields picked and renamed | 1.32 µs | 0.31 µs |
84
+ | `execute`, a nested shape with mapped lines | 7.63 µs | 1.77 µs |
85
+ | `execute`, three strings built | 3.24 µs | 1.20 µs |
86
+ | `evaluate`, four fields | 4.15 µs | 3.17 µs |
87
+ | `execute`, a total for each of 10,000 orders | 30.4 ms | 19.8 ms |
88
+
89
+ A config whose time is in sorting, filtering or summing is as fast as it was.
90
+
91
+ **What to change:** nothing.
92
+
93
+ - 6d098e4: `execute` hands out a compiled config's constants frozen.
94
+
95
+ Every `execute` of an IR answers with the IR's own constants — a `$const` list or object, and anything the compiler folded because it did not depend on the source. A caller that wrote to one changed the IR, and so every later answer:
96
+
97
+ ```ts
98
+ const ir = await compile({ tags: { $coalesce: [{ $ref: '$.tags' }, { $const: [] }] } });
99
+ const first = execute(ir, { tags: null });
100
+ first.tags.push('x');
101
+ execute(ir, { tags: null }); // { tags: ['x'] } — for the next caller too, whoever it was
102
+ ```
103
+
104
+ Where an IR is kept and its answers go to different requests, as vex does with a query's mapping, that carried one request's change into the next. The constants are now frozen all the way down when a config is compiled, and again when an IR read back from storage first runs. `first.tags.push('x')` throws a `TypeError` where it is written.
105
+
106
+ `evaluate` is as it was: what it answers may be changed. So may everything `execute` builds for the call — a template's object, a `$map`'s list.
107
+
108
+ **What to change:** code that writes into an answer of `execute` (or of a vex read whose mapping has a constant list or object) now throws at that line, where it used to change later answers. Copy the part before changing it: `[...answer.tags, x]`.
109
+
110
+ - 8b4d97e: `$eq` and `$neq` no longer write both values out as JSON to compare two scalars.
111
+
112
+ Two values are equal when their JSON text is, and Prism compared that text for every pair, `'paid'` against `'paid'` included. The text is now only made for two different objects or arrays: the same value is equal, and a scalar is equal to nothing but itself. Every pair is answered as before, keys in another order included.
113
+
114
+ A filter on two fields over 10,000 rows, then a sort and a take: 3.7 ms before, 2.2 ms now. A rule of three comparisons on one row: 361 ns before, 207 ns now.
115
+
116
+ **What to change:** nothing.
117
+
118
+ - b084e30: `$sortBy` gives every key a place: an item whose key is `null`, a boolean, or a string among numbers is no longer left wherever the sort happened to put it.
119
+
120
+ `$sortBy` compared numbers with numbers and strings with strings. Any other pair of keys compared as equal, and an item that is equal to everything has no place in an order: where it ended up depended on which items it was compared with, so the same rows in another order came out differently.
121
+
122
+ Now, where the keys are of more than one kind: numbers first, then strings, then `false` and `true`, and `dir: "desc"` turns that around. An item whose key is `null` is last in both directions. Items with equal keys keep the order they came in.
123
+
124
+ A list whose keys are all numbers, or all strings, sorts exactly as it did.
125
+
126
+ **What to change:** nothing. A list that was sorted by a key that is sometimes `null` now has those items at the end.
127
+
128
+ - 663d724: Three things `execute` did on every call, or for every node, that it did not need to.
129
+ - An op's handler in a compiled tree was a function around the op, so every node was two calls. It is the op.
130
+ - A template built a set of its optional field names and caught errors for each field, whether or not it had a `__optional`. One without it, which is nearly every template, now just evaluates its fields.
131
+ - `execute` primed the path cache from the IR's path table on every call. It does so once for each IR, when it restores the IR's annotations.
132
+
133
+ Four fields picked and renamed: 305 ns before, 232 ns now. A nested shape with mapped lines: 1.56 µs and 1.29 µs. A total for each of 10,000 orders: 13.4 ms and 12.6 ms. Answers are as they were.
134
+
135
+ **What to change:** nothing.
136
+
137
+ - 6512d91: Four additions to Prism, and its grammar is at version 3.
138
+ - **`$toNumber`** — a number from a number or from numeric text, as a form, a CSV or an API often sends it: `{ "$toNumber": { "value": { "$ref": "$.price" } } }`. Text is read when it is a number written in digits (`"42"`, `"-3.5"`, `".5"`, `" 1e3 "`). Anything else — `""`, `"12 kg"`, `"1,234"`, `true`, `null` — throws `E_TYPE`, or answers `fallback` where one is given. No other op converts: `$add` on `"4"` is still an error.
139
+ - **`$mod`** — the remainder of a division: `{ "$mod": [{ "$ref": "$.row" }, 2] }`. It takes the sign of the divisor, so with a positive divisor it is never negative (`[-1, 5]` is `4`, where JavaScript's `%` gives `-1`). Throws `E_DIVISION_BY_ZERO` for a zero divisor.
140
+ - **`$round` takes `mode`** — `"floor"` rounds down and `"ceil"` up, at the same `digits`. Without it, it rounds to the nearest, as before.
141
+ - **`$replace` takes `all`** — `all: true` replaces every occurrence. Without it, the first, as before. `search` is text, not a pattern.
142
+
143
+ `MAPPING_OPS` includes `$mod` and `$toNumber`, and loom's Prism editor lists both under Math.
144
+
145
+ **The grammar.** `nisc.prism` goes from 2 to 3 with one migration that rewrites nothing: these are additions, and a reader at 2 must refuse a config that uses them. The same entry records the narrowing made earlier in this release — a `$ref` path that is not keys and indexes is refused — which the JSON Schema does not show.
146
+
147
+ **What to change:** an app that keeps Prism configs in its source moves its stamp: `npm run strata upgrade`, then `npm run strata verify`. There is nothing to edit; `strata.lock.json` goes to `nisc.prism 3`. A config written before parses to exactly what it did, so a compiled IR's fingerprint does not move.
148
+
149
+ - 7d682b9: A valid config is checked in microseconds: the node schema tries the one member a value can be before it walks its union.
150
+
151
+ `NodeSchema` is a union of 76 members that zod tries in order, and a plain object is the last. Each plain object in a config cost about a quarter of a millisecond to accept, so `evaluate`, `validate` and `compile` each spent about half a millisecond on a config of three operators before doing anything. A value's keys decide what it can be: one `$` key and nothing else is that op, no `$` key is a template. That member is now tried first.
152
+
153
+ On a config of three operators (Node 24, zod 4.6.5; the same on zod 4.2.0):
154
+
155
+ | | before | now |
156
+ | ------------------------ | ------ | ------ |
157
+ | `ConfigSchema.safeParse` | 505 µs | 1.9 µs |
158
+ | `evaluate` | 517 µs | 5.7 µs |
159
+ | `compile` | 652 µs | 79 µs |
160
+
161
+ A config that is refused is then walked as before, so what is refused, and every issue and path of the refusal, is unchanged; a refusal takes a few percent longer than it did (1.27 ms to 1.30–1.38 ms for one small refused config). `getConfigJsonSchema`, `getNodeJsonSchema` and `getProfileJsonSchema` return what they returned, and `NodeSchema` is still a zod union. `safeParseAsync` takes the walk alone and is as fast as it was.
162
+
163
+ The README, DOCS.md and DESIGN.md no longer say `execute` is "2-5x faster" than `evaluate`: it was 6 to 960 times before this change and is 1.7 to 65 times after it, by config.
164
+
165
+ **What to change:** nothing.
166
+
167
+ - d2e9d22: `$map`, `$filter`, `$reduce`, `$sortBy`, `$groupBy` and `$keyBy` make one scope for the loop, not one for each item.
168
+
169
+ Each of them built a new context and a new set of variables for every item, to set the loop's variable. They now make that once, as the loop's own copy, and set the variable in it for each item. What a body sees, and what is outside the loop, is as before: a variable of the same name outside is what it was when the loop is done, and a loop inside the body has a scope of its own.
170
+
171
+ Over 10,000 orders: a total for each, 20.3 ms before and 13.4 ms now; filter, sort and take ten, 2.2 ms and 1.2 ms; a count and a sum by country, 3.6 ms and 2.1 ms; a count, a revenue and twenty rows, 15.6 ms and 9.6 ms.
172
+
173
+ **What to change:** nothing.
174
+
175
+ - e0e8abc: A `$const` is returned as it is written, also where its data has a key named like a sugar op.
176
+
177
+ Before a config runs, the sugar ops (`$sum`, `$avg`, `$count`, `$min`, `$max`, `$pluck`, `$take`, `$drop`, `$match`, `$flatMap`) are rewritten to core ops. That pass walked every object, so it also rewrote what is not a node:
178
+
179
+ ```ts
180
+ { $const: { total: { $sum: 1 } } }
181
+ // answered { total: { $reduce: { … } } }, from evaluate and from execute alike
182
+
183
+ { $with: { let: { $sum: [1, 2] }, value: { $var: '$sum' } } }
184
+ // "Variable not found: __acc" — the binding called $sum was rewritten as a sum
185
+
186
+ { $renameKeys: { from: { $ref: '$' }, map: { $count: 'n' } } } // over { $count: 1 }
187
+ // { $count: 1 } — not renamed
188
+ ```
189
+
190
+ A `$const`'s data, the names of a `$with`'s bindings and a `$renameKeys` map are now left alone; the three answer `{ total: { $sum: 1 } }`, `[1, 2]` and `{ n: 1 }`. Data that holds MongoDB-style operators, or a Prism config kept as data (as a strata migration writes one into a document), comes back as it was written.
191
+
192
+ A config with none of these compiles to the core and fingerprint it had. One that has them compiles differently, so its fingerprint changes.
193
+
194
+ **What to change:** nothing. An IR compiled earlier from such a config keeps its wrong constant until it is compiled again.
195
+
196
+ - 7fe1135: Two things Prism answered wrongly without a word are now refused.
197
+
198
+ **A path it does not read.** A `$ref` path is keys and indexes, as DOCS.md says: `$.rows[0].sku`. The rest of JSONPath — a wildcard `[*]`, a filter `[?(…)]`, a slice `[0:2]`, a negative index, a quoted key `['name']`, empty brackets, `..` — was accepted by the schema, and the parser gave up on it with no segments, which reads as `$`. So `{ "$ref": "$.rows[*].sku" }` answered the whole source, and `$..sku` was read as `$.sku`. Such a path is now refused when the config is checked: `validate`, `evaluate` and `compile` give `E_SCHEMA` at the `$ref`, "Not a path Prism reads: … A path is keys and indexes only …; for every item of a list use $map or $pluck." An IR that already holds one is refused when it runs.
199
+
200
+ **A sort key that is a list or an object.** `$sortBy` compares numbers and strings. For any other key it compared nothing, so `by: [a, b]` handed the list back in the order it came. It now throws `E_TYPE` and says what to write: sort by the second key, then by the first; the sort keeps the order of equal items.
201
+
202
+ `getConfigJsonSchema` and the grammar snapshot are unchanged: the path rule is the parser's, beside the published pattern, not in it.
203
+
204
+ **What to change:** a config with such a path or such a key was already answering wrongly; it now says so. Write the path with `$map` or `$pluck`, and the two-key sort as two sorts. Nothing in this repository, nisc-website, moccadroid-website or midas had one. Still as it was: a sort key that is `null`, a boolean, or a number beside a string compares as equal to everything, so such items keep no defined place.
205
+
3
206
  ## 0.2.2
4
207
 
5
208
  ### Patch Changes
package/DESIGN.md CHANGED
@@ -45,12 +45,12 @@ Input Config (JSON)
45
45
  ```typescript
46
46
  type EvalContext = {
47
47
  source: JsonValue; // Root source data (immutable)
48
- vars: Record<string, JsonValue>; // Scoped variables (immutable)
48
+ vars: Record<string, JsonValue>; // Scoped variables (a loop writes to its own copy only)
49
49
  budget?: Budget; // What this evaluation may still cost (engine/budget.ts)
50
50
  };
51
51
  ```
52
52
 
53
- Context is never mutated. Every scope change (loop variable, `$with` binding) creates a new context via spread. This means ops are pure — same input always produces same output.
53
+ The context an op is given is never written to. A `$with` binding makes a new context via spread. A loop (`$map`, `$filter`, `$reduce`, `$sortBy`, `$groupBy`, `$keyBy`) makes one context of its own for the whole loop and sets its variable in that for each item (`ops/scope.ts`): a new one per item was a fifth of the time of a map over 10,000 rows. Nothing keeps a scope past the evaluation of one body, so ops are still pure — same input always produces same output.
54
54
 
55
55
  ---
56
56
 
@@ -109,14 +109,14 @@ type CompiledIr = {
109
109
  stats: { nodeCount, opCount, maxDepth, optimizations };
110
110
  };
111
111
  tables: {
112
- paths: string[]; // JSONPaths for cache priming
112
+ paths: string[]; // every `$ref` string in the tree, a constant's data included: a listing, not read by execute
113
113
  strings: string[]; // String literals
114
114
  };
115
115
  core: unknown; // Desugared, optimized config
116
116
  };
117
117
  ```
118
118
 
119
- `execute()` skips validation and desugaring — it primes the JSONPath cache from `tables.paths` and evaluates `core` directly. This is 2-5x faster than `evaluate()` for repeated configs.
119
+ `execute()` skips validation and desugaring — it restores each node's handler and each `$ref`'s parsed path once per IR, and evaluates `core` directly. How much that saves over `evaluate()` depends on the config: `pnpm bench` runs five against each other (`test/optimize.bench.ts`), from under 2x for a short map to over 50x where the constants fold.
120
120
 
121
121
  The fingerprint enables cache invalidation: store IRs by name, check the fingerprint to know if the config changed.
122
122
 
@@ -168,8 +168,7 @@ src/
168
168
  │ ├── transform.schema.ts
169
169
  │ └── sugar.schema.ts
170
170
  ├── engine/
171
- │ ├── evaluate.ts # Dispatcher + evaluate / evaluateSafe
172
- │ ├── transform.ts # prismTransform — Prism in the shape a host's transform seam takes
171
+ │ ├── evaluate.ts # Dispatcher + evaluate / evaluateSafe (what a config object was found to be is kept here)
173
172
  │ ├── compile.ts # Config → CompiledIr
174
173
  │ ├── optimize.ts # Compile-time passes (ref segments, handlers, constant folding)
175
174
  │ ├── budget.ts # Limits: steps, string length, result size
@@ -195,7 +194,7 @@ src/
195
194
  │ ├── index.ts
196
195
  │ └── mapping-agent.ts # mappingAgent (Cortex agent definition)
197
196
  ├── migrations/
198
- │ └── index.ts # @niscorp/prism/migrations — PRISM_SEQUENCE, and prismTransform again
197
+ │ └── index.ts # @niscorp/prism/migrations — PRISM_SEQUENCE, PRISM_SCHEMAS
199
198
  └── utils/
200
199
  ├── jsonpath.ts # JSONPath parser + cache
201
200
  ├── compare.ts # Deep equality, ordered comparison
@@ -231,7 +230,7 @@ and a mapping over a thousand rows would otherwise build a thousand of them.
231
230
 
232
231
  4. **SHA256 fingerprint on IR.** Cache invalidation without version numbers. Same config = same fingerprint.
233
232
 
234
- 5. **`evaluate` + `evaluateSafe`.** Throwing for trusted code, Result type for untrusted input. Different call sites have different needs.
233
+ 5. **`evaluate` + `evaluateSafe`.** Throwing for trusted code, Result type for untrusted input. Different call sites have different needs. Both keep what a config object was found to be, by the object: a host hands the same configs over on every request, and checking each again was the whole cost of a small transform. `check: 'always'` is the call that keeps nothing, for writing and testing a config. A separate function for the kept path (`prismTransform`) existed for a while and is gone: it was the one hosts were told to use and the one that reported worst.
235
234
 
236
235
  6. **Ops receive `evaluate` as a parameter.** Breaks the circular import between ops and the dispatcher. Also enables mock-based unit testing of individual ops.
237
236
 
@@ -242,3 +241,5 @@ and a mapping over a thousand rows would otherwise build a thousand of them.
242
241
  9. **`$case` uses `{ branches, else }`.** Clearer than a flat array mixing `{when,then}` and `{else}` objects. Simpler Zod schema.
243
242
 
244
243
  10. **`compile()` is async.** Uses `crypto.subtle.digest` for SHA256, which is async in all runtimes. `evaluate()` stays sync because it doesn't need the fingerprint.
244
+
245
+ 11. **The node union is tried by key before it is walked.** zod tries a union's 76 members in order, and a plain object is the last. One `$` key and nothing else can only be that op, and no `$` key can only be a template, so that member is tried first and a valid config never walks the union. An invalid one is walked as before, from the top, so a refusal is the union's own. The union stays a union: the JSON Schema, the profiles and loom read it as one.
package/DOCS.md CHANGED
@@ -44,7 +44,7 @@ If `$.user.nickname` doesn't exist, the result is `{ "name": "Alice" }` — no e
44
44
 
45
45
  ### `$ref` — Read from source
46
46
 
47
- Resolves a JSONPath against the source data. Supports `.key` and `[index]` syntax.
47
+ Resolves a path against the source data. A path is keys and indexes: `.key` and `[index]`. The rest of JSONPath — a wildcard `[*]`, a filter `[?(…)]`, a slice, a negative index, a quoted key, `..` — is refused when the config is checked (`E_SCHEMA`, "Not a path Prism reads"); for every item of a list use `$map` or `$pluck`. The JSON Schema from `getConfigJsonSchema`, `getNodeJsonSchema` and `getProfileJsonSchema` does not carry this rule: its pattern for `$ref` is `^\$(\..*)?$`, so a path can pass the JSON Schema and still be refused by `validate`.
48
48
 
49
49
  ```json
50
50
  { "$ref": "$.user.name" }
@@ -218,7 +218,7 @@ Source: `{ "tags": ["a", "b", "a", "c", "b"] }` → `["a", "b", "c"]`
218
218
  }
219
219
  ```
220
220
 
221
- `dir` defaults to `"asc"`. Works with numbers and strings.
221
+ `dir` defaults to `"asc"`. A sort key is a number or a string. Where the keys are of more than one kind, numbers come first, then strings, then `false` and `true`, and `"desc"` turns that around; an item whose key is `null` is last in both directions. Items with equal keys keep the order they came in. A key that is a list or an object is refused (`E_TYPE`): to sort by two keys, sort by the second and then by the first — the sort keeps the order of equal items.
222
222
 
223
223
  ---
224
224
 
@@ -247,11 +247,28 @@ All math ops take a `[left, right]` pair. Both operands are evaluated and must b
247
247
  ```
248
248
  Throws `E_DIVISION_BY_ZERO` if the divisor is 0.
249
249
 
250
+ ### `$mod`
251
+ ```json
252
+ { "$mod": [{ "$ref": "$.row" }, 2] }
253
+ ```
254
+ The remainder of the first number divided by the second. It takes the sign of the **second** number, so with a positive divisor `n` the answer is always from `0` up to `n` — `{ "$mod": [-1, 5] }` is `4`, where JavaScript's `%` gives `-1`. Throws `E_DIVISION_BY_ZERO` if the divisor is 0.
255
+
250
256
  ### `$round`
251
257
  ```json
252
258
  { "$round": { "value": { "$const": 3.14159 }, "digits": 2 } }
253
259
  ```
254
- Result: `3.14`. `digits` defaults to 0.
260
+ Result: `3.14`. `digits` defaults to 0. `mode` is `"nearest"` unless given: `"floor"` rounds down (toward negative infinity) and `"ceil"` rounds up, at the same `digits`.
261
+
262
+ ```json
263
+ { "$round": { "value": { "$div": [{ "$ref": "$.minutes" }, 60] }, "mode": "floor" } }
264
+ ```
265
+
266
+ ### `$toNumber` — A number from text
267
+ ```json
268
+ { "$toNumber": { "value": { "$ref": "$.price" } } }
269
+ { "$toNumber": { "value": { "$ref": "$.discount" }, "fallback": 0 } }
270
+ ```
271
+ A number is answered as it is. Text is read as a number when it is one written in digits, with spaces around it allowed: `"42"`, `"-3.5"`, `".5"`, `" 1e3 "`. Everything else — `""`, `"12 kg"`, `"1,234"`, `"0x10"`, `true`, `null`, a list — throws `E_TYPE`, or answers `fallback` where it is given. The other ops do not convert: `$add` on `"4"` is still an error.
255
272
 
256
273
  ---
257
274
 
@@ -314,10 +331,12 @@ Result: `"hello"`
314
331
  ```
315
332
  Result: `["a", "b", "c"]`
316
333
 
317
- ### `$replace` — Replace first occurrence
334
+ ### `$replace` — Replace a substring
318
335
  ```json
319
336
  { "$replace": { "value": { "$ref": "$.text" }, "search": "world", "replacement": "there" } }
337
+ { "$replace": { "value": { "$ref": "$.phone" }, "search": " ", "replacement": "", "all": true } }
320
338
  ```
339
+ The first occurrence of `search`, or every occurrence with `all: true`. `search` is plain text, not a pattern.
321
340
 
322
341
  ---
323
342
 
@@ -721,47 +740,71 @@ const ir = await compile(config, { name: 'user-transform', version: '1.0.0' });
721
740
  // - Desugared config (sugar ops already resolved)
722
741
  // - SHA256 fingerprint (for cache invalidation)
723
742
  // - Stats (node count, op frequency, max depth, optimizations applied)
724
- // - Tables (all JSONPaths and string literals for cache priming)
743
+ // - Tables (every $ref string and string literal in the tree)
725
744
 
726
745
  const result1 = execute(ir, source1); // No validation, no desugaring
727
- const result2 = execute(ir, source2); // 2-5x faster than evaluate()
746
+ const result2 = execute(ir, source2); // Each op's handler already attached
728
747
  ```
729
748
 
730
749
  The IR is JSON-serializable — store it in a database, cache in Redis, send over a wire.
731
750
 
732
- ## As a host's transform
751
+ **A constant in an answer is frozen.** Every `execute` of an IR hands out the IR's own constants: a `$const` that is a list or an object, and anything the compiler worked out ahead of time because it did not depend on the source (`{ "$split": { "value": "a,b", "sep": "," } }` is a constant list). They are frozen, all the way down, so one caller cannot change what the next is given: `answer.tags.push(x)` on a list that came from `{ "$const": [] }` throws a `TypeError`. To change an answer, copy the part first (`[...answer.tags, x]`). Everything built for the call — a template's object, a `$map`'s list — is the caller's own. `evaluate` does not freeze: what it answers may be changed.
752
+
753
+ ## evaluate
733
754
 
734
755
  ```typescript
735
- prismTransform(config: unknown, source: unknown): unknown
756
+ evaluate(config: unknown, source: unknown, options?: { limits?: Partial<Limits>; check?: 'always' }): JsonValue
757
+ evaluateSafe(config, source, options?): { ok: true, data } | { ok: false, error }
736
758
  ```
737
759
 
738
- Prism in the shape a host's transform seam takes. nova's shell (`transform`),
760
+ A config and a source in, the answer out.
761
+
762
+ - **The config** is checked against the schema the first time its object is
763
+ handed over, and refused with a `PrismError` (`E_SCHEMA`) that names the part
764
+ that is wrong. Its tree is kept: the second call with the same object prepares
765
+ it as `compile` would (handlers attached, paths parsed, constants folded), and
766
+ every call after that only evaluates. It is kept by the object, so a config
767
+ changed in place after its first call is not read again — hand over a new
768
+ object. A config that is a new object on every call is checked on every call,
769
+ and is not prepared: that would cost more than it saves.
770
+ - **The source** is taken as it is. Nothing checks it.
771
+ - **The answer** is the caller's to change: a constant is handed out as a copy.
772
+
773
+ It is the function a host's transform seam takes. nova's shell (`transform`),
739
774
  tide's engine (`transform`) and strata's upgrader (`{ transform }`) each run a
740
- config through a function they are handed and know nothing of Prism; this is the
741
- function to hand them.
775
+ config through a function they are handed and know nothing of Prism:
742
776
 
743
777
  ```typescript
744
- import { prismTransform } from '@niscorp/prism';
778
+ import { evaluate } from '@niscorp/prism';
745
779
 
746
- const tide = createTide({ store, transform: prismTransform, effects });
780
+ const tide = createTide({ store, transform: evaluate, effects });
747
781
  ```
748
782
 
749
- - **The config** is parsed against `ConfigSchema` where it comes in — once for
750
- each config object, so a config a host keeps and passes again is not parsed
751
- again.
752
- - **The source** must be plain JSON: `null`, strings, booleans, finite numbers,
753
- and arrays and objects of those. One that holds `undefined`, a function or a
754
- non-finite number is refused — `The source of a transform must be plain JSON.`
755
- - **The result** is what `evaluate` answers.
783
+ ### `check: 'always'`
756
784
 
757
- `evaluate` itself is typed for a `JsonValue` source and checks none, so it does
758
- not fit a seam that hands over `unknown`. `@niscorp/prism/migrations` exports the
759
- same function.
785
+ ```typescript
786
+ evaluate(config, source, { check: 'always' })
787
+ ```
788
+
789
+ For writing a config, for tests and for tools. Nothing is kept and nothing is
790
+ taken on trust: the config is checked on this call whatever was checked before,
791
+ and the source must be plain JSON — `null`, strings, booleans, finite numbers,
792
+ and arrays and plain objects of those. One that holds `undefined`, a function,
793
+ a `Date` or a non-finite number is refused: `E_TYPE`, "The source must be plain
794
+ JSON."
795
+
796
+ ### Which call
797
+
798
+ | You have | Call |
799
+ |---|---|
800
+ | a config your program holds, run again and again | `evaluate(config, source)` |
801
+ | a config being written, a test, a tool | `evaluate(config, source, { check: 'always' })` |
802
+ | a config that is stored, or that must run without its checks | `compile` once, `execute` the IR |
760
803
 
761
804
  ## Limits
762
805
 
763
- `evaluate`, `evaluateSafe` and `execute` take an optional third argument, a
764
- `Partial<Limits>`, merged over `DEFAULT_LIMITS`:
806
+ `evaluate` and `evaluateSafe` take them as `options.limits`, `execute` as its
807
+ third argument: a `Partial<Limits>`, merged over `DEFAULT_LIMITS`:
765
808
 
766
809
  | Limit | Default | Counts |
767
810
  |-------|---------|--------|
@@ -769,7 +812,9 @@ same function.
769
812
  | `maxStringLength` | `1_000_000` | Characters in any one string a node produces |
770
813
  | `maxValues` | `1_000_000` | Values (scalars, array items, object fields) in a `$reduce` accumulator, a `$with` binding, or the result |
771
814
 
772
- Past any of them the evaluation throws `E_BUDGET`.
815
+ Past any of them the evaluation throws `E_BUDGET`. `maxValues` counts a value
816
+ each time it appears, as it would be serialized: a `$reduce` whose body is
817
+ `[{ "$var": "acc" }, { "$var": "acc" }]` doubles its count with every item.
773
818
 
774
819
  ## Error Codes
775
820
 
package/README.md CHANGED
@@ -49,14 +49,13 @@ const result = evaluate(
49
49
  ## API
50
50
 
51
51
  ```typescript
52
- // One-shot evaluation
53
- evaluate(config, source, limits?) → JsonValue
54
- evaluateSafe(config, source, limits?) → { ok: true, data } | { ok: false, error }
52
+ // A config and a source in, the answer out. A config object is checked the first
53
+ // time it is seen and only evaluated after that.
54
+ evaluate(config, source, options?) → JsonValue
55
+ evaluateSafe(config, source, options?) → { ok: true, data } | { ok: false, error }
56
+ // options: { limits?, check?: 'always' } — 'always' checks everything on every call
55
57
 
56
- // The same, in the shape a host's transform seam takes
57
- prismTransform(config: unknown, source: unknown) → unknown
58
-
59
- // Compile once, execute many (2-5x faster for repeated configs)
58
+ // For a config that is stored: compile once, keep the IR, execute it
60
59
  compile(config, options?) → Promise<CompiledIr>
61
60
  execute(ir, source, limits?) → JsonValue
62
61
 
@@ -68,31 +67,49 @@ getNodeJsonSchema(target?) → object
68
67
  getConfigJsonSchema(target?) → object
69
68
  ```
70
69
 
71
- ## As a host's transform
70
+ ## Which call
71
+
72
+ **`evaluate(config, source)`** is the call for a config a program holds. The
73
+ first time it is handed a config object it checks it against the schema, and
74
+ refuses with the part that is wrong; the second time it prepares it as `compile`
75
+ would; from then on a call only evaluates. So a host that keeps its configs and
76
+ hands the same objects over on every request pays the check once. It is kept by
77
+ the object: a config changed in place after its first call is not read again —
78
+ hand over a new object.
72
79
 
80
+ Both arguments are `unknown`, so it is also what a host's transform seam takes.
73
81
  nova's shell, tide's engine and strata's upgrader each run a config through a
74
- transform they are handed, `(config, source) => unknown`, and know nothing of
75
- Prism. `prismTransform` is Prism in that shape:
82
+ function they are handed, `(config, source) => unknown`, and know nothing of
83
+ Prism:
76
84
 
77
85
  ```typescript
78
- import { prismTransform } from '@niscorp/prism';
86
+ import { evaluate } from '@niscorp/prism';
79
87
 
80
- createTide({ store, transform: prismTransform, effects }); // @niscorp/tide
81
- createUpgrader(grammars, { transform: prismTransform }); // @niscorp/strata
88
+ createTide({ store, transform: evaluate, effects }); // @niscorp/tide
89
+ createUpgrader(grammars, { transform: evaluate }); // @niscorp/strata
82
90
  ```
83
91
 
84
- Both sides arrive untyped, so both are checked: the config is parsed against
85
- `ConfigSchema` (once for each config object), and the source must be plain JSON
86
- — a source holding `undefined`, a function or a non-finite number is refused.
87
- `evaluate` is typed for a `JsonValue` and checks no source, which is why it
88
- cannot be handed to a seam as it is. A host that adds values of its own to the
89
- source first (the app's "today", the session's principal) wraps it.
92
+ A host that adds values of its own to the source first (the app's "today", the
93
+ session's principal) wraps it: `(config, source) => evaluate(config, { ...source, today })`.
94
+
95
+ **`evaluate(config, source, { check: 'always' })`** is for writing a config, for
96
+ tests and for tools. It keeps nothing: the config is checked on every call, and
97
+ so is the source, which must be plain JSON — one holding `undefined`, a
98
+ function, a `Date` or a non-finite number is refused.
99
+
100
+ **`compile` and `execute`** are for a config that is stored. The IR is JSON with
101
+ a fingerprint: keep it beside what it belongs to, and `execute` runs it without
102
+ checking anything again — in another process, on another day. It is the only
103
+ form that does not need the config object to be the same one.
90
104
 
91
105
  ## Examples
92
106
 
93
107
  `@niscorp/prism/examples` is the reference as data: one example for each
94
108
  operator, named by the operator — a config, the source it is given, and what
95
109
  comes out — then a few configs of several operators working together.
110
+ Each `id` is unique across the set and in kebab-case (`sort-by` for `$sortBy`),
111
+ so an address can be built on it. An example of several operators working
112
+ together has no `op`.
96
113
 
97
114
  ```typescript
98
115
  import { evaluate } from '@niscorp/prism';
@@ -116,9 +133,14 @@ own. So whatever shows them — a documentation page, an agent reading
116
133
  `getProfileJsonSchema(ops, target?)` is the config JSON Schema documenting only
117
134
  the ops you name — derived from the full schema, never restated. `MAPPING_OPS`
118
135
  is the set a mapping uses (rows into a shape), about 28% less prompt than the
119
- whole grammar; the mapping agent is documented with it. A profile narrows what
120
- a prompt teaches, never what Prism accepts: validation is always the full
136
+ whole grammar; the mapping agent is documented with it. That agent's `data` is
137
+ the Prism config itself, and its `reasoning` is one sentence on the mapping. A
138
+ profile narrows what a prompt teaches, never what Prism accepts: validation is always the full
121
139
  `ConfigSchema`, and a config using an op outside the profile is still valid.
140
+ `MAPPING_OPS` leaves out the transform ops (`$has`, `$renameKeys`, `$update`,
141
+ `$assert`, `$walk`) and `$fill`, `$replace`, `$keyBy`, `$entriesOf`,
142
+ `$fromEntries`, `$keys`, `$values`, `$type`, `$flatten`, `$flatMap`, `$match`,
143
+ `$drop`, `$dateAdd`, `$startsWith` and `$endsWith`.
122
144
 
123
145
  ## Transform ops and the grammar
124
146
 
@@ -128,9 +150,8 @@ rules) — see [DOCS.md § Transform Operations](./DOCS.md#transform-operations)
128
150
  They are what strata's document migrations are written in.
129
151
 
130
152
  **`@niscorp/prism/migrations`** publishes Prism's own grammar — `PRISM_SEQUENCE`
131
- (`nisc.prism`, kind `nisc.prism/config`), `PRISM_SCHEMAS` — and exports
132
- `prismTransform` as well, the evaluator a migration runs through (strata injects
133
- it): the same function as the main entry's.
153
+ (`nisc.prism`, kind `nisc.prism/config`), `PRISM_SCHEMAS`. The evaluator a
154
+ migration runs through is `evaluate`, from the main entry (strata injects it).
134
155
 
135
156
  **The op set only ever grows.** Configs are stored — endpoint requests, vex
136
157
  mappings, migrations — and a migration cannot be migrated by the language it is
package/dist/agent.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var chunkW32JXP33_cjs = require('./chunk-W32JXP33.cjs');
4
- var chunk26VYDHHC_cjs = require('./chunk-26VYDHHC.cjs');
3
+ var chunkOWKINPR5_cjs = require('./chunk-OWKINPR5.cjs');
4
+ var chunk6PD7M2F3_cjs = require('./chunk-6PD7M2F3.cjs');
5
5
  var zod = require('zod');
6
6
  var cortex = require('@niscorp/cortex');
7
7
 
@@ -21,17 +21,15 @@ Worked example (illustrative only \u2014 read the schema for op details):
21
21
  INPUT { "sampleInput": { "first": "Ada", "last": "Lovelace" }, "targetShape": { "fullName": "" } }
22
22
  data { "fullName": { "$interpolate": { "template": "{{f}} {{l}}", "values": { "f": { "$ref": "$.first" }, "l": { "$ref": "$.last" } } } } }`;
23
23
  var OUTPUT_DOC = `OUTPUT SCHEMA \u2014 your output MUST validate against this JSON Schema:
24
- ${JSON.stringify(chunkW32JXP33_cjs.getProfileJsonSchema(chunkW32JXP33_cjs.MAPPING_OPS, "draft-7"))}`;
24
+ ${JSON.stringify(chunkOWKINPR5_cjs.getProfileJsonSchema(chunkOWKINPR5_cjs.MAPPING_OPS, "draft-7"))}`;
25
25
  var mappingAgent = cortex.defineAgent({
26
26
  id: "prism.mapping",
27
27
  description: "Generates a Prism transformation config from a sample input row and a target shape.",
28
28
  instructions: INSTRUCTIONS,
29
- // Validated against the FULL grammar — a config using any op is accepted,
30
- // exactly as before — but documented with the mapping profile: the ops a
31
- // mapping uses, about 28% less prompt than the whole grammar
32
- // (schemas/profiles.ts). The heading is cortex's own (context/schema-doc.ts),
33
- // so the finish protocol's "OUTPUT SCHEMA" still names it.
34
- output: { schema: chunk26VYDHHC_cjs.ConfigSchema, doc: OUTPUT_DOC }
29
+ // Validated against the full grammar, documented with the mapping profile:
30
+ // a config using an op outside the profile is still accepted. The doc keeps
31
+ // cortex's own heading, "OUTPUT SCHEMA", which its finish protocol names.
32
+ output: { schema: chunk6PD7M2F3_cjs.ConfigSchema, doc: OUTPUT_DOC }
35
33
  });
36
34
 
37
35
  exports.MappingAgentInputSchema = MappingAgentInputSchema;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/agent/mapping-agent.ts"],"names":["z","getProfileJsonSchema","MAPPING_OPS","defineAgent","ConfigSchema"],"mappings":";;;;;;;AA6CO,IAAM,uBAAA,GAA0BA,MAAE,MAAA,CAAO;AAAA,EAC9C,WAAA,EAAaA,KAAA,CACV,MAAA,CAAOA,KAAA,CAAE,MAAA,EAAO,EAAGA,KAAA,CAAE,OAAA,EAAS,CAAA,CAC9B,QAAA,CAAS,qFAAqF,CAAA;AAAA,EACjG,WAAA,EAAaA,KAAA,CACV,OAAA,EAAQ,CACR,QAAA;AAAA,IACC;AAAA,GACF;AAAA,EACF,iBAAA,EAAmBA,KAAA,CAChB,MAAA,CAAOA,KAAA,CAAE,MAAA,EAAO,EAAGA,KAAA,CAAE,MAAA,EAAQ,CAAA,CAC7B,QAAA,EAAS,CACT,SAAS,sFAAsF,CAAA;AAAA,EAClG,OAAOA,KAAA,CACJ,MAAA,GACA,QAAA,EAAS,CACT,SAAS,8DAA8D;AAC5E,CAAC;AAiBD,IAAM,YAAA,GAAe,CAAA;;AAAA;;AAAA;AAAA;AAAA,6IAAA,CAAA;AAQrB,IAAM,UAAA,GAAa,CAAA;AAAA,EAAwE,KAAK,SAAA,CAAUC,sCAAA,CAAqBC,6BAAA,EAAa,SAAS,CAAC,CAAC,CAAA,CAAA;AAMhJ,IAAM,eAAwCC,kBAAA,CAAoB;AAAA,EACvE,EAAA,EAAI,eAAA;AAAA,EACJ,WAAA,EAAa,qFAAA;AAAA,EACb,YAAA,EAAc,YAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMd,MAAA,EAAQ,EAAE,MAAA,EAAQC,8BAAA,EAAc,KAAK,UAAA;AACvC,CAAC","file":"agent.cjs","sourcesContent":["// ═══════════════════════════════════════════════════════════\n// @niscorp/prism/agent — Prism mapping agent\n// ═══════════════════════════════════════════════════════════\n//\n// Given a sample input row and a target shape, the mapping agent\n// produces a Prism Config that transforms input → target.\n//\n// This is the canonical \"package owns its agent, runs it on Cortex\"\n// pattern. Cortex is an optional peer dep: the rest of @niscorp/prism\n// does not need it.\n//\n// Usage:\n//\n// import { createSignal } from '@niscorp/signal';\n// import { mappingAgent } from '@niscorp/prism/agent';\n// import { evaluate } from '@niscorp/prism';\n//\n// const llm = createSignal('groq', { apiKey }); // qwen/qwen3.8-27b, the registry default\n// const result = await mappingAgent.run({\n// sampleInput: { first: 'Ada', last: 'Lovelace' },\n// targetShape: { fullName: '' },\n// }, { llm }).result;\n//\n// if (result.ok) {\n// // result.output.data is a fully-validated Prism Config;\n// // result.output.reasoning is the model's one-line why.\n// const output = evaluate(result.output.data, sampleInput);\n// }\n//\n// The Config schema itself is NOT embedded in this prompt — cortex\n// injects it (output.doc 'auto' → schemaDoc(ConfigSchema)) because the\n// recursive Node union can't ride the respond tool's params. One\n// source of truth, zero hand-maintained schema prose.\n\nimport { z } from 'zod';\nimport { defineAgent, type AgentDefinition } from '@niscorp/cortex';\n\nimport { ConfigSchema, type Config } from '../schemas';\nimport { MAPPING_OPS } from '../schemas/profiles';\nimport { getProfileJsonSchema } from '../engine/documentation';\n\n// ───────────────────────────────────────────────────────────\n// Input schema\n// ───────────────────────────────────────────────────────────\n\nexport const MappingAgentInputSchema = z.object({\n sampleInput: z\n .record(z.string(), z.unknown())\n .describe('A representative input row. The transformation will run against rows of this shape.'),\n targetShape: z\n .unknown()\n .describe(\n 'A JSON example of the desired output shape. Field values are placeholders; the agent infers the structure from this example.',\n ),\n fieldDescriptions: z\n .record(z.string(), z.string())\n .optional()\n .describe('Optional human-readable descriptions for fields the agent might not infer correctly.'),\n notes: z\n .string()\n .optional()\n .describe('Free-form additional context (data quirks, semantics, etc.).'),\n});\n\nexport type MappingAgentInput = z.infer<typeof MappingAgentInputSchema>;\n\n// The agent's payload IS the Prism Config. The model's explanation\n// rides the envelope's `reasoning` field — no wrapper schema.\nexport type MappingAgentOutput = Config;\n\n// ───────────────────────────────────────────────────────────\n// System prompt — role + worked example, nothing else\n// ───────────────────────────────────────────────────────────\n//\n// Per niscorp/STYLE_GUIDE.md: every operation, constraint and gotcha\n// lives in the Prism schema's .describe() calls, and the prompt carries\n// the JSON Schema (OUTPUT_DOC below). If the model gets an op wrong,\n// sharpen the relevant .describe() in @niscorp/prism — do not add prose here.\n\nconst INSTRUCTIONS = `You are the Prism mapping agent. Given a sample input row and a target output shape, produce a Prism Config that maps rows of the input shape into the target shape.\n\nYour envelope's \\`data\\` is the Prism Config; \\`reasoning\\` is a one-sentence explanation of the mapping. The config must validate against the OUTPUT SCHEMA below (every constraint, format rule and example is in the schema's field descriptions).\n\nWorked example (illustrative only — read the schema for op details):\nINPUT { \"sampleInput\": { \"first\": \"Ada\", \"last\": \"Lovelace\" }, \"targetShape\": { \"fullName\": \"\" } }\ndata { \"fullName\": { \"$interpolate\": { \"template\": \"{{f}} {{l}}\", \"values\": { \"f\": { \"$ref\": \"$.first\" }, \"l\": { \"$ref\": \"$.last\" } } } } }`;\n\nconst OUTPUT_DOC = `OUTPUT SCHEMA — your output MUST validate against this JSON Schema:\\n${JSON.stringify(getProfileJsonSchema(MAPPING_OPS, 'draft-7'))}`;\n\n// ───────────────────────────────────────────────────────────\n// Agent definition — the entire public surface\n// ───────────────────────────────────────────────────────────\n\nexport const mappingAgent: AgentDefinition<Config> = defineAgent<Config>({\n id: 'prism.mapping',\n description: 'Generates a Prism transformation config from a sample input row and a target shape.',\n instructions: INSTRUCTIONS,\n // Validated against the FULL grammar — a config using any op is accepted,\n // exactly as before — but documented with the mapping profile: the ops a\n // mapping uses, about 28% less prompt than the whole grammar\n // (schemas/profiles.ts). The heading is cortex's own (context/schema-doc.ts),\n // so the finish protocol's \"OUTPUT SCHEMA\" still names it.\n output: { schema: ConfigSchema, doc: OUTPUT_DOC },\n});\n"]}
1
+ {"version":3,"sources":["../src/agent/mapping-agent.ts"],"names":["z","getProfileJsonSchema","MAPPING_OPS","defineAgent","ConfigSchema"],"mappings":";;;;;;;AAOO,IAAM,uBAAA,GAA0BA,MAAE,MAAA,CAAO;AAAA,EAC9C,WAAA,EAAaA,KAAA,CACV,MAAA,CAAOA,KAAA,CAAE,MAAA,EAAO,EAAGA,KAAA,CAAE,OAAA,EAAS,CAAA,CAC9B,QAAA,CAAS,qFAAqF,CAAA;AAAA,EACjG,WAAA,EAAaA,KAAA,CACV,OAAA,EAAQ,CACR,QAAA;AAAA,IACC;AAAA,GACF;AAAA,EACF,iBAAA,EAAmBA,KAAA,CAChB,MAAA,CAAOA,KAAA,CAAE,MAAA,EAAO,EAAGA,KAAA,CAAE,MAAA,EAAQ,CAAA,CAC7B,QAAA,EAAS,CACT,SAAS,sFAAsF,CAAA;AAAA,EAClG,OAAOA,KAAA,CACJ,MAAA,GACA,QAAA,EAAS,CACT,SAAS,8DAA8D;AAC5E,CAAC;AAMD,IAAM,YAAA,GAAe,CAAA;;AAAA;;AAAA;AAAA;AAAA,6IAAA,CAAA;AAQrB,IAAM,UAAA,GAAa,CAAA;AAAA,EAAwE,KAAK,SAAA,CAAUC,sCAAA,CAAqBC,6BAAA,EAAa,SAAS,CAAC,CAAC,CAAA,CAAA;AAEhJ,IAAM,eAAwCC,kBAAA,CAAoB;AAAA,EACvE,EAAA,EAAI,eAAA;AAAA,EACJ,WAAA,EAAa,qFAAA;AAAA,EACb,YAAA,EAAc,YAAA;AAAA;AAAA;AAAA;AAAA,EAId,MAAA,EAAQ,EAAE,MAAA,EAAQC,8BAAA,EAAc,KAAK,UAAA;AACvC,CAAC","file":"agent.cjs","sourcesContent":["import { z } from 'zod';\nimport { defineAgent, type AgentDefinition } from '@niscorp/cortex';\n\nimport { ConfigSchema, type Config } from '../schemas';\nimport { MAPPING_OPS } from '../schemas/profiles';\nimport { getProfileJsonSchema } from '../engine/documentation';\n\nexport const MappingAgentInputSchema = z.object({\n sampleInput: z\n .record(z.string(), z.unknown())\n .describe('A representative input row. The transformation will run against rows of this shape.'),\n targetShape: z\n .unknown()\n .describe(\n 'A JSON example of the desired output shape. Field values are placeholders; the agent infers the structure from this example.',\n ),\n fieldDescriptions: z\n .record(z.string(), z.string())\n .optional()\n .describe('Optional human-readable descriptions for fields the agent might not infer correctly.'),\n notes: z\n .string()\n .optional()\n .describe('Free-form additional context (data quirks, semantics, etc.).'),\n});\n\nexport type MappingAgentInput = z.infer<typeof MappingAgentInputSchema>;\n\nexport type MappingAgentOutput = Config;\n\nconst INSTRUCTIONS = `You are the Prism mapping agent. Given a sample input row and a target output shape, produce a Prism Config that maps rows of the input shape into the target shape.\n\nYour envelope's \\`data\\` is the Prism Config; \\`reasoning\\` is a one-sentence explanation of the mapping. The config must validate against the OUTPUT SCHEMA below (every constraint, format rule and example is in the schema's field descriptions).\n\nWorked example (illustrative only — read the schema for op details):\nINPUT { \"sampleInput\": { \"first\": \"Ada\", \"last\": \"Lovelace\" }, \"targetShape\": { \"fullName\": \"\" } }\ndata { \"fullName\": { \"$interpolate\": { \"template\": \"{{f}} {{l}}\", \"values\": { \"f\": { \"$ref\": \"$.first\" }, \"l\": { \"$ref\": \"$.last\" } } } } }`;\n\nconst OUTPUT_DOC = `OUTPUT SCHEMA — your output MUST validate against this JSON Schema:\\n${JSON.stringify(getProfileJsonSchema(MAPPING_OPS, 'draft-7'))}`;\n\nexport const mappingAgent: AgentDefinition<Config> = defineAgent<Config>({\n id: 'prism.mapping',\n description: 'Generates a Prism transformation config from a sample input row and a target shape.',\n instructions: INSTRUCTIONS,\n // Validated against the full grammar, documented with the mapping profile:\n // a config using an op outside the profile is still accepted. The doc keeps\n // cortex's own heading, \"OUTPUT SCHEMA\", which its finish protocol names.\n output: { schema: ConfigSchema, doc: OUTPUT_DOC },\n});\n"]}