@eyeoverthink/sva-gate 2.1.0 → 2.1.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.
@@ -1,267 +1,267 @@
1
- // Binder induction: learn how to bind a skill from its own recorded bindings, with no model at all.
2
- //
3
- // Measured in Phase 11: a 7B code model asked to write a regex parser from examples produced parsers that returned
4
- // null on 6-7 of 7 recorded bindings (one was not even valid JavaScript). But the examples themselves already say how
5
- // binding works ("original_price is the number after $, discount1 is the first percentage / 100"). Induction finds,
6
- // for every parameter, ONE selector (number kind x position x scale) consistent with every example, records the
7
- // task "shape" (how many numbers of each kind), and learns question words that only ever appeared in tasks the skill
8
- // must refuse. Leave-one-out: each example must be predicted by the spec induced from all the others.
9
- // The spec compiles to a self-contained `function bind(task)` so it runs, hashes and verifies like any binder.
10
-
11
- const KINDS = ['currency', 'percent', 'plain'];
12
- const round = (x) => Math.round(x * 1e9) / 1e9;
13
-
14
- /**
15
- * Numbers in a task, each tagged by kind: "$40" currency, "25%" percent, anything else plain. Each also carries its
16
- * context: up to 3 content words right after it, within its clause ("5% sales tax is added" -> sales, tax, added).
17
- */
18
- export function numberTokens(task) {
19
- const s = String(task), out = [];
20
- const STOPC = ['and', 'then', 'the', 'that', 'this', 'for', 'with', 'from', 'are', 'was', 'its', 'your'];
21
- // 1.3.0: "$1,200" is one number (thousands separators), and EUR/GBP/JPY signs mark currency like "$".
22
- const re = /([$\u20ac\u00a3\u00a5]\s?)?(?<![\w.])(-?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?)(\s*%|\s?percent\b)?(?:\s?([a-z]+(?:\/[a-z]+)?))?/gi;
23
- let m;
24
- while ((m = re.exec(s))) {
25
- const end = m.index + (m[1] || '').length + m[2].length + (m[3] || '').length;
26
- const rest = s.slice(end).split(/[,;:?!]|\.(?!\d)|\d/)[0].toLowerCase();
27
- const ctx = (rest.match(/[a-z]{3,}/g) || []).filter((w) => !STOPC.includes(w)).slice(0, 3);
28
- out.push({ v: Number(m[2].replace(/,/g, '')), kind: m[1] ? 'currency' : m[3] ? 'percent' : 'plain', unit: !m[1] && !m[3] && m[4] ? m[4].toLowerCase() : null, ctx });
29
- }
30
- return out;
31
- }
32
-
33
- export const shapeOf = (toks) => KINDS.map((k) => toks.filter((t) => t.kind === k).length).join(',');
34
-
35
- /**
36
- * Words that change what the numbers mean without being numbers: quantities written as words ("Two $240 coats"),
37
- * distributive words ("each", "per"), and negations ("is not 25% off"). 1.2.0 never gated words BEFORE a number, so
38
- * "Two $240 coats are each 25% off..." routed and answered 162 (correct: 324). A task that uses a modifier no positive
39
- * example used is refused. Self-contained so compileSpec can inline it.
40
- */
41
- export function modifierWords(task) {
42
- const MOD = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve',
43
- 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty', 'thirty', 'forty',
44
- 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', 'hundred', 'thousand', 'million', 'dozen', 'dozens', 'half',
45
- 'halves', 'quarter', 'double', 'doubled', 'twice', 'triple', 'tripled', 'thrice', 'couple', 'several', 'both', 'each', 'every', 'per', 'apiece',
46
- 'not', 'no', 'never', 'none', 'nor', 'neither', 'without', 'except', 'instead', 'excluding'];
47
- const words = String(task).toLowerCase().replace(/[\u2019']/g, "'").match(/[a-z]+(?:'[a-z]+)?/g) || [];
48
- const out = new Set();
49
- for (const w of words) {
50
- if (MOD.includes(w)) out.add(w);
51
- else if (/n't$/.test(w)) out.add("n't");
52
- }
53
- return [...out].sort();
54
- }
55
-
56
- /** Content words of the question sentence (the last sentence with a "?", else the last sentence). Self-contained. */
57
- export function questionWords(task) {
58
- const STOPW = ['the', 'and', 'for', 'with', 'that', 'this', 'what', 'how', 'much', 'many', 'does', 'did', 'was', 'are', 'its', 'their', 'your', 'you', 'now', 'then', 'after', 'from', 'into', 'over', 'whole', 'all'];
59
- const parts = String(task).split(/(?<=[.!?])\s+/);
60
- const q = [...parts].reverse().find((x) => x.includes('?')) || parts[parts.length - 1] || '';
61
- return (q.toLowerCase().match(/[a-z]{3,}/g) || []).filter((w) => !STOPW.includes(w));
62
- }
63
-
64
- const declaresDecimal = (p) => /\b(decimal|fraction)\b/i.test(`${p?.description || ''} ${p?.items?.description || ''}`);
65
- const eq = (a, b) => (Array.isArray(a) ? Array.isArray(b) && a.length === b.length && a.every((x, i) => eq(x, b[i])) : typeof a === 'number' && typeof b === 'number' && Math.abs(a - b) <= Math.max(1e-9, Math.abs(a) * 1e-9));
66
-
67
- function pick(toks, s) {
68
- const list = toks.filter((t) => s.kind === 'any' || t.kind === s.kind);
69
- if (s.all) return list.map((t) => round(t.v * s.scale));
70
- const t = s.k >= 0 ? list[s.k] : list[list.length + s.k];
71
- if (t === undefined || (s.units && !s.units.includes(t.unit))) return undefined;
72
- return round(t.v * s.scale);
73
- }
74
-
75
- /** Induce a binding spec from positive examples; null-safe. Returns { spec } or { error }. */
76
- export function induce(pos, neg, skill) {
77
- if (!pos.length) return { error: 'no positive examples' };
78
- const props = skill.params?.properties || {};
79
- const keys = Object.keys(pos[0].input || {}).filter((k) => pos.every((e) => e.input && k in e.input));
80
- if (!keys.length) return { error: 'examples share no input keys' };
81
- const toks = pos.map((e) => numberTokens(e.task));
82
- const shapes = [...new Set(toks.map(shapeOf))];
83
- if (shapes.length > 2) return { error: `examples have ${shapes.length} different number shapes` };
84
- const maxN = Math.max(...toks.map((t) => t.length));
85
- const params = {};
86
- const alternatives = {};
87
- for (const key of keys) {
88
- const p = props[key] || {};
89
- const scales = declaresDecimal(p) ? [0.01, 1] : [1];
90
- const cands = [];
91
- for (const kind of [...KINDS, 'any']) for (const scale of scales) {
92
- if (p.type === 'array' || Array.isArray(pos[0].input[key])) cands.push({ kind, all: true, scale });
93
- else for (let k = 0; k < maxN; k++) cands.push({ kind, k, scale }, { kind, k: -(k + 1), scale });
94
- }
95
- const fits = cands.filter((s) => pos.every((e, i) => eq(pick(toks[i], s), e.input[key])));
96
- if (!fits.length) return { error: `no single rule finds ${key} in every example` };
97
- // Plain numbers carry their units: measured, positions alone could not tell "40 mph ... 60 mph" from
98
- // "120 miles in 2 hours", so the speed binder was (correctly) refused until units were learned.
99
- for (const hit of fits) {
100
- if (hit.all || (hit.kind !== 'plain' && hit.kind !== 'any')) continue;
101
- const units = toks.map((t) => { const l = t.filter((x) => hit.kind === 'any' || x.kind === hit.kind); return (hit.k >= 0 ? l[hit.k] : l[l.length + hit.k])?.unit; });
102
- if (units.every(Boolean)) hit.units = [...new Set(units)].sort();
103
- }
104
- // 1.3.0 ambiguity check. 1.2.0 kept the first rule that fit, silently: with examples where d1 = d2, "first %"
105
- // and "second %" both fit, and "40% off, then 10% off" was bound as {d1: 0.4, d2: 0.4}. A rule that picks a
106
- // DIFFERENT number in some example (equal values by coincidence) is kept as an alternative; applySpec refuses a
107
- // task on which the alternatives disagree. Rules that pick the same number in every example are the same rule.
108
- const which = (t, s) => { const l = t.filter((x) => s.kind === 'any' || x.kind === s.kind); return s.all ? l : (s.k >= 0 ? l[s.k] : l[l.length + s.k]); };
109
- const same = (a, b) => toks.every((t) => { const x = which(t, a), y = which(t, b); return Array.isArray(x) ? Array.isArray(y) && x.length === y.length && x.every((v, j) => v === y[j]) : x === y; });
110
- const [hit, ...rest] = fits;
111
- const alts = [];
112
- for (const c of rest) if (!same(c, hit) && !alts.some((a) => same(a, c))) alts.push(c);
113
- params[key] = hit;
114
- if (alts.length) alternatives[key] = alts;
115
- }
116
- const modifiers = [...new Set(pos.flatMap((e) => modifierWords(e.task)))].sort();
117
- return { spec: { shapes, params, alternatives, modifiers, ...learnBlocks(pos, neg) } };
118
- }
119
-
120
- /**
121
- * What the skill's refusals teach, independent of any binder: question block words, and body block words after
122
- * numbers of a "role-marked" kind. Used by induction AND directly by the model binder's gate, so a lesson survives
123
- * even when the binder that misrouted is retired and its replacement is not (yet) admitted.
124
- */
125
- export function learnBlocks(pos, neg) {
126
- // A block word must never occur anywhere in a positive task: measured, a single counter-example otherwise taught
127
- // the binder to refuse every task containing 'off'.
128
- const posQ = new Set(pos.flatMap((e) => String(e.task).toLowerCase().match(/[a-z]{3,}/g) || []));
129
- const blockWords = [...new Set(neg.flatMap((e) => questionWords(e.task)))].filter((w) => !posQ.has(w)).sort();
130
- // Body block words (Phase 12). Measured in Phase 11: "20% off and then 5% sales tax is added" got past every
131
- // binder, because the tax is in the body, not the question. The words right after a number name its role ("20% OFF",
132
- // "5% sales TAX"), but only for number kinds whose role wording REPEATS across good examples (a closed vocabulary:
133
- // "off" follows a percentage in most discount tasks). After "$90 jacket" comes an item noun that differs in every
134
- // task (an open vocabulary), so a refused jacket task never teaches the binder to refuse jackets.
135
- const ctxOf = (task, kind) => numberTokens(task).filter((t) => t.kind === kind).flatMap((t) => t.ctx);
136
- // With few examples, "half" is a coincidence: measured on the demo rehearsal, 2 of a composed skill's 3 positives said
137
- // "$… dinner", so "$" looked role-marked and a fresh "$250 birthday dinner" task was refused as unverified wording.
138
- // A role word must repeat in at least 3 positives (all of them when there are only 2), and in half of a large set.
139
- const need = Math.max(2, Math.min(pos.length, 3), Math.ceil(pos.length / 2));
140
- const kinds = KINDS.filter((k) => {
141
- const n = new Map();
142
- for (const e of pos) for (const w of new Set(ctxOf(e.task, k))) n.set(w, (n.get(w) || 0) + 1);
143
- return [...n.values()].some((c) => c >= need);
144
- });
145
- const words = [...new Set(neg.flatMap((e) => kinds.flatMap((k) => ctxOf(e.task, k))))].filter((w) => !posQ.has(w)).sort();
146
- return { blockWords, contextBlock: { kinds, words } };
147
- }
148
-
149
- /**
150
- * A confirmed failure contests the positives that look like it. Measured on the live home: four sales-tax misroutes
151
- * had been stored as POSITIVE examples (no gate could see them), and because a block word may never occur in a
152
- * positive task, they made "tax" impossible to learn: the misroute had immunized itself. When the critic rejects a
153
- * route, the rejected task's RARE role words (after a role-marked number, in under 25% of positives: "tax", not "off")
154
- * mark every positive that shares them as disputed. If that would contest over a third of the positives, the evidence
155
- * conflicts too much and nothing is demoted.
156
- */
157
- export function contested(pos, task) {
158
- const { kinds } = learnBlocks(pos, []).contextBlock;
159
- const ctx = (t) => new Set(numberTokens(t).filter((x) => kinds.includes(x.kind)).flatMap((x) => x.ctx));
160
- const sets = pos.map((e) => ctx(e.task));
161
- const words = [...ctx(task)].filter((w) => sets.filter((s) => s.has(w)).length < pos.length * 0.25).sort();
162
- const hit = pos.filter((_, i) => words.some((w) => sets[i].has(w)));
163
- return hit.length > pos.length / 3 ? { words, examples: [], tooMany: hit.length } : { words, examples: hit };
164
- }
165
-
166
- /** The words that say what a task's numbers MEAN: role words after role-marked numbers, plus its question words. */
167
- export function wordingOf(task, kinds) {
168
- // Role words carry their position: which occurrence of which number kind they follow. Measured in Phase 14: a
169
- // tax-then-split skill had verified "off" (after the 1st %) and "sales tax added" (after the 2nd), so a discount task
170
- // ("off" after BOTH) looked fully verified and was routed to it with zero calls. "off" after the 2nd % is new wording.
171
- // Occurrences are counted in the task's fullest line: mission prompts restate the goal on other lines (Phase 11).
172
- const SIGN = { percent: '%', currency: '$', plain: 'number' };
173
- const seen = {};
174
- const fullest = String(task).split(/\n+/).reduce((a, b) => (numberTokens(b).length > numberTokens(a).length ? b : a), '');
175
- const roles = numberTokens(fullest).filter((t) => kinds.includes(t.kind)).flatMap((t) => {
176
- seen[t.kind] = (seen[t.kind] || 0) + 1;
177
- return t.ctx.map((w) => `${w} after ${SIGN[t.kind]} #${seen[t.kind]}`);
178
- });
179
- return [...new Set([...roles, ...questionWords(task)])];
180
- }
181
-
182
- /**
183
- * Wording never seen in a positive example. Measured in Phase 12: every misroute any binder made was recorded as a
184
- * positive and then shielded itself, so a binding is only trusted when its wording has been verified before. Novel
185
- * wording ("8% tax", "an 18% tip") is not routed; the agent loop answers it, and the answers are compared.
186
- */
187
- export function novelWording(pos, task) {
188
- const { kinds } = learnBlocks(pos, []).contextBlock;
189
- const known = new Set(pos.flatMap((e) => wordingOf(e.task, kinds)));
190
- const knownMods = new Set(pos.flatMap((e) => modifierWords(e.task)));
191
- return [
192
- ...wordingOf(task, kinds).filter((w) => !known.has(w)),
193
- ...modifierWords(task).filter((w) => !knownMods.has(w)).map((w) => `${w} (quantity or negation)`),
194
- ];
195
- }
196
-
197
- /**
198
- * Apply a spec and say why when it refuses: `{ input, refused }`, where `refused` is null when the task binds, else one
199
- * of 'shape', 'block-word', 'context-block', 'modifier', 'ambiguous', 'missing'. Same logic the compiled binder runs.
200
- */
201
- export function explainApply(spec, task) {
202
- const no = (refused, detail) => ({ input: null, refused, detail });
203
- const toks = numberTokens(task);
204
- if (!spec.shapes.includes(shapeOf(toks))) return no('shape', shapeOf(toks));
205
- const q = questionWords(task);
206
- const bw = spec.blockWords.filter((w) => q.includes(w));
207
- if (bw.length) return no('block-word', bw);
208
- const cb = spec.contextBlock;
209
- if (cb && toks.some((t) => cb.kinds.includes(t.kind) && t.ctx.some((w) => cb.words.includes(w)))) return no('context-block', cb.words);
210
- // Specs induced before 1.3.0 carry no `modifiers`; they are treated as having seen none, which is the safe side.
211
- const mods = modifierWords(task).filter((w) => !(spec.modifiers || []).includes(w));
212
- if (mods.length) return no('modifier', mods);
213
- const out = {};
214
- for (const [k, s] of Object.entries(spec.params)) {
215
- const v = pick(toks, s);
216
- if (v === undefined) return no('missing', k);
217
- for (const a of (spec.alternatives || {})[k] || []) {
218
- const w = pick(toks, a);
219
- if (w === undefined || JSON.stringify(w) !== JSON.stringify(v)) return no('ambiguous', k);
220
- }
221
- out[k] = v;
222
- }
223
- return { input: out, refused: null, detail: null };
224
- }
225
-
226
- /** Apply a spec to a task; null when it refuses (see explainApply for the reason). */
227
- export function applySpec(spec, task) {
228
- return explainApply(spec, task).input;
229
- }
230
-
231
- /** Leave-one-out: every example must be predicted by the spec induced from all the others. */
232
- export function leaveOneOut(pos, neg, skill) {
233
- return pos.map((e, i) => {
234
- const rest = pos.filter((_, j) => j !== i);
235
- const r = induce(rest, neg, skill);
236
- const got = r.spec ? applySpec(r.spec, e.task) : null;
237
- const ok = Boolean(got) && Object.keys(e.input).every((k) => eq(got[k], e.input[k]));
238
- // A miss only because the held-out example has a unit no other example has ("knots") is novelty, not contradiction.
239
- let novel = false;
240
- if (!ok && r.spec) {
241
- // A modifier word ("each") only the held-out example uses is novelty too.
242
- const loose = { ...r.spec, modifiers: [...(r.spec.modifiers || []), ...modifierWords(e.task)], params: Object.fromEntries(Object.entries(r.spec.params).map(([k, p]) => [k, { ...p, units: undefined }])) };
243
- const g2 = applySpec(loose, e.task);
244
- novel = Boolean(g2) && Object.keys(e.input).every((k) => eq(g2[k], e.input[k]));
245
- }
246
- return { task: e.task, ok, novel, got, error: r.error };
247
- });
248
- }
249
-
250
- /** Compile a spec into a self-contained, sandbox-runnable `function bind(task)`. */
251
- export function compileSpec(spec) {
252
- return [
253
- 'function bind(task) {',
254
- ` const SPEC = ${JSON.stringify(spec)};`,
255
- ` const KINDS = ${JSON.stringify(KINDS)};`,
256
- ` const round = ${round.toString()};`,
257
- ` ${numberTokens.toString()}`,
258
- ` ${questionWords.toString()}`,
259
- ` const shapeOf = ${shapeOf.toString()};`,
260
- ` ${modifierWords.toString()}`,
261
- ` ${pick.toString()}`,
262
- ` ${explainApply.toString()}`,
263
- ` ${applySpec.toString()}`,
264
- ' return applySpec(SPEC, task);',
265
- '}',
266
- ].join('\n');
267
- }
1
+ // Binder induction: learn how to bind a skill from its own recorded bindings, with no model at all.
2
+ //
3
+ // Measured in Phase 11: a 7B code model asked to write a regex parser from examples produced parsers that returned
4
+ // null on 6-7 of 7 recorded bindings (one was not even valid JavaScript). But the examples themselves already say how
5
+ // binding works ("original_price is the number after $, discount1 is the first percentage / 100"). Induction finds,
6
+ // for every parameter, ONE selector (number kind x position x scale) consistent with every example, records the
7
+ // task "shape" (how many numbers of each kind), and learns question words that only ever appeared in tasks the skill
8
+ // must refuse. Leave-one-out: each example must be predicted by the spec induced from all the others.
9
+ // The spec compiles to a self-contained `function bind(task)` so it runs, hashes and verifies like any binder.
10
+
11
+ const KINDS = ['currency', 'percent', 'plain'];
12
+ const round = (x) => Math.round(x * 1e9) / 1e9;
13
+
14
+ /**
15
+ * Numbers in a task, each tagged by kind: "$40" currency, "25%" percent, anything else plain. Each also carries its
16
+ * context: up to 3 content words right after it, within its clause ("5% sales tax is added" -> sales, tax, added).
17
+ */
18
+ export function numberTokens(task) {
19
+ const s = String(task), out = [];
20
+ const STOPC = ['and', 'then', 'the', 'that', 'this', 'for', 'with', 'from', 'are', 'was', 'its', 'your'];
21
+ // 1.3.0: "$1,200" is one number (thousands separators), and EUR/GBP/JPY signs mark currency like "$".
22
+ const re = /([$\u20ac\u00a3\u00a5]\s?)?(?<![\w.])(-?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?)(\s*%|\s?percent\b)?(?:\s?([a-z]+(?:\/[a-z]+)?))?/gi;
23
+ let m;
24
+ while ((m = re.exec(s))) {
25
+ const end = m.index + (m[1] || '').length + m[2].length + (m[3] || '').length;
26
+ const rest = s.slice(end).split(/[,;:?!]|\.(?!\d)|\d/)[0].toLowerCase();
27
+ const ctx = (rest.match(/[a-z]{3,}/g) || []).filter((w) => !STOPC.includes(w)).slice(0, 3);
28
+ out.push({ v: Number(m[2].replace(/,/g, '')), kind: m[1] ? 'currency' : m[3] ? 'percent' : 'plain', unit: !m[1] && !m[3] && m[4] ? m[4].toLowerCase() : null, ctx });
29
+ }
30
+ return out;
31
+ }
32
+
33
+ export const shapeOf = (toks) => KINDS.map((k) => toks.filter((t) => t.kind === k).length).join(',');
34
+
35
+ /**
36
+ * Words that change what the numbers mean without being numbers: quantities written as words ("Two $240 coats"),
37
+ * distributive words ("each", "per"), and negations ("is not 25% off"). 1.2.0 never gated words BEFORE a number, so
38
+ * "Two $240 coats are each 25% off..." routed and answered 162 (correct: 324). A task that uses a modifier no positive
39
+ * example used is refused. Self-contained so compileSpec can inline it.
40
+ */
41
+ export function modifierWords(task) {
42
+ const MOD = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve',
43
+ 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty', 'thirty', 'forty',
44
+ 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', 'hundred', 'thousand', 'million', 'dozen', 'dozens', 'half',
45
+ 'halves', 'quarter', 'double', 'doubled', 'twice', 'triple', 'tripled', 'thrice', 'couple', 'several', 'both', 'each', 'every', 'per', 'apiece',
46
+ 'not', 'no', 'never', 'none', 'nor', 'neither', 'without', 'except', 'instead', 'excluding'];
47
+ const words = String(task).toLowerCase().replace(/[\u2019']/g, "'").match(/[a-z]+(?:'[a-z]+)?/g) || [];
48
+ const out = new Set();
49
+ for (const w of words) {
50
+ if (MOD.includes(w)) out.add(w);
51
+ else if (/n't$/.test(w)) out.add("n't");
52
+ }
53
+ return [...out].sort();
54
+ }
55
+
56
+ /** Content words of the question sentence (the last sentence with a "?", else the last sentence). Self-contained. */
57
+ export function questionWords(task) {
58
+ const STOPW = ['the', 'and', 'for', 'with', 'that', 'this', 'what', 'how', 'much', 'many', 'does', 'did', 'was', 'are', 'its', 'their', 'your', 'you', 'now', 'then', 'after', 'from', 'into', 'over', 'whole', 'all'];
59
+ const parts = String(task).split(/(?<=[.!?])\s+/);
60
+ const q = [...parts].reverse().find((x) => x.includes('?')) || parts[parts.length - 1] || '';
61
+ return (q.toLowerCase().match(/[a-z]{3,}/g) || []).filter((w) => !STOPW.includes(w));
62
+ }
63
+
64
+ const declaresDecimal = (p) => /\b(decimal|fraction)\b/i.test(`${p?.description || ''} ${p?.items?.description || ''}`);
65
+ const eq = (a, b) => (Array.isArray(a) ? Array.isArray(b) && a.length === b.length && a.every((x, i) => eq(x, b[i])) : typeof a === 'number' && typeof b === 'number' && Math.abs(a - b) <= Math.max(1e-9, Math.abs(a) * 1e-9));
66
+
67
+ function pick(toks, s) {
68
+ const list = toks.filter((t) => s.kind === 'any' || t.kind === s.kind);
69
+ if (s.all) return list.map((t) => round(t.v * s.scale));
70
+ const t = s.k >= 0 ? list[s.k] : list[list.length + s.k];
71
+ if (t === undefined || (s.units && !s.units.includes(t.unit))) return undefined;
72
+ return round(t.v * s.scale);
73
+ }
74
+
75
+ /** Induce a binding spec from positive examples; null-safe. Returns { spec } or { error }. */
76
+ export function induce(pos, neg, skill) {
77
+ if (!pos.length) return { error: 'no positive examples' };
78
+ const props = skill.params?.properties || {};
79
+ const keys = Object.keys(pos[0].input || {}).filter((k) => pos.every((e) => e.input && k in e.input));
80
+ if (!keys.length) return { error: 'examples share no input keys' };
81
+ const toks = pos.map((e) => numberTokens(e.task));
82
+ const shapes = [...new Set(toks.map(shapeOf))];
83
+ if (shapes.length > 2) return { error: `examples have ${shapes.length} different number shapes` };
84
+ const maxN = Math.max(...toks.map((t) => t.length));
85
+ const params = {};
86
+ const alternatives = {};
87
+ for (const key of keys) {
88
+ const p = props[key] || {};
89
+ const scales = declaresDecimal(p) ? [0.01, 1] : [1];
90
+ const cands = [];
91
+ for (const kind of [...KINDS, 'any']) for (const scale of scales) {
92
+ if (p.type === 'array' || Array.isArray(pos[0].input[key])) cands.push({ kind, all: true, scale });
93
+ else for (let k = 0; k < maxN; k++) cands.push({ kind, k, scale }, { kind, k: -(k + 1), scale });
94
+ }
95
+ const fits = cands.filter((s) => pos.every((e, i) => eq(pick(toks[i], s), e.input[key])));
96
+ if (!fits.length) return { error: `no single rule finds ${key} in every example` };
97
+ // Plain numbers carry their units: measured, positions alone could not tell "40 mph ... 60 mph" from
98
+ // "120 miles in 2 hours", so the speed binder was (correctly) refused until units were learned.
99
+ for (const hit of fits) {
100
+ if (hit.all || (hit.kind !== 'plain' && hit.kind !== 'any')) continue;
101
+ const units = toks.map((t) => { const l = t.filter((x) => hit.kind === 'any' || x.kind === hit.kind); return (hit.k >= 0 ? l[hit.k] : l[l.length + hit.k])?.unit; });
102
+ if (units.every(Boolean)) hit.units = [...new Set(units)].sort();
103
+ }
104
+ // 1.3.0 ambiguity check. 1.2.0 kept the first rule that fit, silently: with examples where d1 = d2, "first %"
105
+ // and "second %" both fit, and "40% off, then 10% off" was bound as {d1: 0.4, d2: 0.4}. A rule that picks a
106
+ // DIFFERENT number in some example (equal values by coincidence) is kept as an alternative; applySpec refuses a
107
+ // task on which the alternatives disagree. Rules that pick the same number in every example are the same rule.
108
+ const which = (t, s) => { const l = t.filter((x) => s.kind === 'any' || x.kind === s.kind); return s.all ? l : (s.k >= 0 ? l[s.k] : l[l.length + s.k]); };
109
+ const same = (a, b) => toks.every((t) => { const x = which(t, a), y = which(t, b); return Array.isArray(x) ? Array.isArray(y) && x.length === y.length && x.every((v, j) => v === y[j]) : x === y; });
110
+ const [hit, ...rest] = fits;
111
+ const alts = [];
112
+ for (const c of rest) if (!same(c, hit) && !alts.some((a) => same(a, c))) alts.push(c);
113
+ params[key] = hit;
114
+ if (alts.length) alternatives[key] = alts;
115
+ }
116
+ const modifiers = [...new Set(pos.flatMap((e) => modifierWords(e.task)))].sort();
117
+ return { spec: { shapes, params, alternatives, modifiers, ...learnBlocks(pos, neg) } };
118
+ }
119
+
120
+ /**
121
+ * What the skill's refusals teach, independent of any binder: question block words, and body block words after
122
+ * numbers of a "role-marked" kind. Used by induction AND directly by the model binder's gate, so a lesson survives
123
+ * even when the binder that misrouted is retired and its replacement is not (yet) admitted.
124
+ */
125
+ export function learnBlocks(pos, neg) {
126
+ // A block word must never occur anywhere in a positive task: measured, a single counter-example otherwise taught
127
+ // the binder to refuse every task containing 'off'.
128
+ const posQ = new Set(pos.flatMap((e) => String(e.task).toLowerCase().match(/[a-z]{3,}/g) || []));
129
+ const blockWords = [...new Set(neg.flatMap((e) => questionWords(e.task)))].filter((w) => !posQ.has(w)).sort();
130
+ // Body block words (Phase 12). Measured in Phase 11: "20% off and then 5% sales tax is added" got past every
131
+ // binder, because the tax is in the body, not the question. The words right after a number name its role ("20% OFF",
132
+ // "5% sales TAX"), but only for number kinds whose role wording REPEATS across good examples (a closed vocabulary:
133
+ // "off" follows a percentage in most discount tasks). After "$90 jacket" comes an item noun that differs in every
134
+ // task (an open vocabulary), so a refused jacket task never teaches the binder to refuse jackets.
135
+ const ctxOf = (task, kind) => numberTokens(task).filter((t) => t.kind === kind).flatMap((t) => t.ctx);
136
+ // With few examples, "half" is a coincidence: measured on the demo rehearsal, 2 of a composed skill's 3 positives said
137
+ // "$… dinner", so "$" looked role-marked and a fresh "$250 birthday dinner" task was refused as unverified wording.
138
+ // A role word must repeat in at least 3 positives (all of them when there are only 2), and in half of a large set.
139
+ const need = Math.max(2, Math.min(pos.length, 3), Math.ceil(pos.length / 2));
140
+ const kinds = KINDS.filter((k) => {
141
+ const n = new Map();
142
+ for (const e of pos) for (const w of new Set(ctxOf(e.task, k))) n.set(w, (n.get(w) || 0) + 1);
143
+ return [...n.values()].some((c) => c >= need);
144
+ });
145
+ const words = [...new Set(neg.flatMap((e) => kinds.flatMap((k) => ctxOf(e.task, k))))].filter((w) => !posQ.has(w)).sort();
146
+ return { blockWords, contextBlock: { kinds, words } };
147
+ }
148
+
149
+ /**
150
+ * A confirmed failure contests the positives that look like it. Measured on the live home: four sales-tax misroutes
151
+ * had been stored as POSITIVE examples (no gate could see them), and because a block word may never occur in a
152
+ * positive task, they made "tax" impossible to learn: the misroute had immunized itself. When the critic rejects a
153
+ * route, the rejected task's RARE role words (after a role-marked number, in under 25% of positives: "tax", not "off")
154
+ * mark every positive that shares them as disputed. If that would contest over a third of the positives, the evidence
155
+ * conflicts too much and nothing is demoted.
156
+ */
157
+ export function contested(pos, task) {
158
+ const { kinds } = learnBlocks(pos, []).contextBlock;
159
+ const ctx = (t) => new Set(numberTokens(t).filter((x) => kinds.includes(x.kind)).flatMap((x) => x.ctx));
160
+ const sets = pos.map((e) => ctx(e.task));
161
+ const words = [...ctx(task)].filter((w) => sets.filter((s) => s.has(w)).length < pos.length * 0.25).sort();
162
+ const hit = pos.filter((_, i) => words.some((w) => sets[i].has(w)));
163
+ return hit.length > pos.length / 3 ? { words, examples: [], tooMany: hit.length } : { words, examples: hit };
164
+ }
165
+
166
+ /** The words that say what a task's numbers MEAN: role words after role-marked numbers, plus its question words. */
167
+ export function wordingOf(task, kinds) {
168
+ // Role words carry their position: which occurrence of which number kind they follow. Measured in Phase 14: a
169
+ // tax-then-split skill had verified "off" (after the 1st %) and "sales tax added" (after the 2nd), so a discount task
170
+ // ("off" after BOTH) looked fully verified and was routed to it with zero calls. "off" after the 2nd % is new wording.
171
+ // Occurrences are counted in the task's fullest line: mission prompts restate the goal on other lines (Phase 11).
172
+ const SIGN = { percent: '%', currency: '$', plain: 'number' };
173
+ const seen = {};
174
+ const fullest = String(task).split(/\n+/).reduce((a, b) => (numberTokens(b).length > numberTokens(a).length ? b : a), '');
175
+ const roles = numberTokens(fullest).filter((t) => kinds.includes(t.kind)).flatMap((t) => {
176
+ seen[t.kind] = (seen[t.kind] || 0) + 1;
177
+ return t.ctx.map((w) => `${w} after ${SIGN[t.kind]} #${seen[t.kind]}`);
178
+ });
179
+ return [...new Set([...roles, ...questionWords(task)])];
180
+ }
181
+
182
+ /**
183
+ * Wording never seen in a positive example. Measured in Phase 12: every misroute any binder made was recorded as a
184
+ * positive and then shielded itself, so a binding is only trusted when its wording has been verified before. Novel
185
+ * wording ("8% tax", "an 18% tip") is not routed; the agent loop answers it, and the answers are compared.
186
+ */
187
+ export function novelWording(pos, task) {
188
+ const { kinds } = learnBlocks(pos, []).contextBlock;
189
+ const known = new Set(pos.flatMap((e) => wordingOf(e.task, kinds)));
190
+ const knownMods = new Set(pos.flatMap((e) => modifierWords(e.task)));
191
+ return [
192
+ ...wordingOf(task, kinds).filter((w) => !known.has(w)),
193
+ ...modifierWords(task).filter((w) => !knownMods.has(w)).map((w) => `${w} (quantity or negation)`),
194
+ ];
195
+ }
196
+
197
+ /**
198
+ * Apply a spec and say why when it refuses: `{ input, refused }`, where `refused` is null when the task binds, else one
199
+ * of 'shape', 'block-word', 'context-block', 'modifier', 'ambiguous', 'missing'. Same logic the compiled binder runs.
200
+ */
201
+ export function explainApply(spec, task) {
202
+ const no = (refused, detail) => ({ input: null, refused, detail });
203
+ const toks = numberTokens(task);
204
+ if (!spec.shapes.includes(shapeOf(toks))) return no('shape', shapeOf(toks));
205
+ const q = questionWords(task);
206
+ const bw = spec.blockWords.filter((w) => q.includes(w));
207
+ if (bw.length) return no('block-word', bw);
208
+ const cb = spec.contextBlock;
209
+ if (cb && toks.some((t) => cb.kinds.includes(t.kind) && t.ctx.some((w) => cb.words.includes(w)))) return no('context-block', cb.words);
210
+ // Specs induced before 1.3.0 carry no `modifiers`; they are treated as having seen none, which is the safe side.
211
+ const mods = modifierWords(task).filter((w) => !(spec.modifiers || []).includes(w));
212
+ if (mods.length) return no('modifier', mods);
213
+ const out = {};
214
+ for (const [k, s] of Object.entries(spec.params)) {
215
+ const v = pick(toks, s);
216
+ if (v === undefined) return no('missing', k);
217
+ for (const a of (spec.alternatives || {})[k] || []) {
218
+ const w = pick(toks, a);
219
+ if (w === undefined || JSON.stringify(w) !== JSON.stringify(v)) return no('ambiguous', k);
220
+ }
221
+ out[k] = v;
222
+ }
223
+ return { input: out, refused: null, detail: null };
224
+ }
225
+
226
+ /** Apply a spec to a task; null when it refuses (see explainApply for the reason). */
227
+ export function applySpec(spec, task) {
228
+ return explainApply(spec, task).input;
229
+ }
230
+
231
+ /** Leave-one-out: every example must be predicted by the spec induced from all the others. */
232
+ export function leaveOneOut(pos, neg, skill) {
233
+ return pos.map((e, i) => {
234
+ const rest = pos.filter((_, j) => j !== i);
235
+ const r = induce(rest, neg, skill);
236
+ const got = r.spec ? applySpec(r.spec, e.task) : null;
237
+ const ok = Boolean(got) && Object.keys(e.input).every((k) => eq(got[k], e.input[k]));
238
+ // A miss only because the held-out example has a unit no other example has ("knots") is novelty, not contradiction.
239
+ let novel = false;
240
+ if (!ok && r.spec) {
241
+ // A modifier word ("each") only the held-out example uses is novelty too.
242
+ const loose = { ...r.spec, modifiers: [...(r.spec.modifiers || []), ...modifierWords(e.task)], params: Object.fromEntries(Object.entries(r.spec.params).map(([k, p]) => [k, { ...p, units: undefined }])) };
243
+ const g2 = applySpec(loose, e.task);
244
+ novel = Boolean(g2) && Object.keys(e.input).every((k) => eq(g2[k], e.input[k]));
245
+ }
246
+ return { task: e.task, ok, novel, got, error: r.error };
247
+ });
248
+ }
249
+
250
+ /** Compile a spec into a self-contained, sandbox-runnable `function bind(task)`. */
251
+ export function compileSpec(spec) {
252
+ return [
253
+ 'function bind(task) {',
254
+ ` const SPEC = ${JSON.stringify(spec)};`,
255
+ ` const KINDS = ${JSON.stringify(KINDS)};`,
256
+ ` const round = ${round.toString()};`,
257
+ ` ${numberTokens.toString()}`,
258
+ ` ${questionWords.toString()}`,
259
+ ` const shapeOf = ${shapeOf.toString()};`,
260
+ ` ${modifierWords.toString()}`,
261
+ ` ${pick.toString()}`,
262
+ ` ${explainApply.toString()}`,
263
+ ` ${applySpec.toString()}`,
264
+ ' return applySpec(SPEC, task);',
265
+ '}',
266
+ ].join('\n');
267
+ }