@eyeoverthink/sva-gate 2.0.2 → 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,204 +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
- const re = /(\$\s?)?(?<![\w.])(-?\d+(?:\.\d+)?)(\s*%|\s?percent\b)?(?:\s?([a-z]+(?:\/[a-z]+)?))?/gi;
22
- let m;
23
- while ((m = re.exec(s))) {
24
- const end = m.index + (m[1] || '').length + m[2].length + (m[3] || '').length;
25
- const rest = s.slice(end).split(/[,;:?!]|\.(?!\d)|\d/)[0].toLowerCase();
26
- const ctx = (rest.match(/[a-z]{3,}/g) || []).filter((w) => !STOPC.includes(w)).slice(0, 3);
27
- out.push({ v: Number(m[2]), kind: m[1] ? 'currency' : m[3] ? 'percent' : 'plain', unit: !m[1] && !m[3] && m[4] ? m[4].toLowerCase() : null, ctx });
28
- }
29
- return out;
30
- }
31
-
32
- export const shapeOf = (toks) => KINDS.map((k) => toks.filter((t) => t.kind === k).length).join(',');
33
-
34
- /** Content words of the question sentence (the last sentence with a "?", else the last sentence). Self-contained. */
35
- export function questionWords(task) {
36
- 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'];
37
- const parts = String(task).split(/(?<=[.!?])\s+/);
38
- const q = [...parts].reverse().find((x) => x.includes('?')) || parts[parts.length - 1] || '';
39
- return (q.toLowerCase().match(/[a-z]{3,}/g) || []).filter((w) => !STOPW.includes(w));
40
- }
41
-
42
- const declaresDecimal = (p) => /\b(decimal|fraction)\b/i.test(`${p?.description || ''} ${p?.items?.description || ''}`);
43
- 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));
44
-
45
- function pick(toks, s) {
46
- const list = toks.filter((t) => s.kind === 'any' || t.kind === s.kind);
47
- if (s.all) return list.map((t) => round(t.v * s.scale));
48
- const t = s.k >= 0 ? list[s.k] : list[list.length + s.k];
49
- if (t === undefined || (s.units && !s.units.includes(t.unit))) return undefined;
50
- return round(t.v * s.scale);
51
- }
52
-
53
- /** Induce a binding spec from positive examples; null-safe. Returns { spec } or { error }. */
54
- export function induce(pos, neg, skill) {
55
- if (!pos.length) return { error: 'no positive examples' };
56
- const props = skill.params?.properties || {};
57
- const keys = Object.keys(pos[0].input || {}).filter((k) => pos.every((e) => e.input && k in e.input));
58
- if (!keys.length) return { error: 'examples share no input keys' };
59
- const toks = pos.map((e) => numberTokens(e.task));
60
- const shapes = [...new Set(toks.map(shapeOf))];
61
- if (shapes.length > 2) return { error: `examples have ${shapes.length} different number shapes` };
62
- const maxN = Math.max(...toks.map((t) => t.length));
63
- const params = {};
64
- for (const key of keys) {
65
- const p = props[key] || {};
66
- const scales = declaresDecimal(p) ? [0.01, 1] : [1];
67
- const cands = [];
68
- for (const kind of [...KINDS, 'any']) for (const scale of scales) {
69
- if (p.type === 'array' || Array.isArray(pos[0].input[key])) cands.push({ kind, all: true, scale });
70
- else for (let k = 0; k < maxN; k++) cands.push({ kind, k, scale }, { kind, k: -(k + 1), scale });
71
- }
72
- const hit = cands.find((s) => pos.every((e, i) => eq(pick(toks[i], s), e.input[key])));
73
- if (!hit) return { error: `no single rule finds ${key} in every example` };
74
- // Plain numbers carry their units: measured, positions alone could not tell "40 mph ... 60 mph" from
75
- // "120 miles in 2 hours", so the speed binder was (correctly) refused until units were learned.
76
- if (hit.kind === 'plain' || hit.kind === 'any') {
77
- 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; });
78
- if (units.every(Boolean)) hit.units = [...new Set(units)].sort();
79
- }
80
- params[key] = hit;
81
- }
82
- return { spec: { shapes, params, ...learnBlocks(pos, neg) } };
83
- }
84
-
85
- /**
86
- * What the skill's refusals teach, independent of any binder: question block words, and body block words after
87
- * numbers of a "role-marked" kind. Used by induction AND directly by the model binder's gate, so a lesson survives
88
- * even when the binder that misrouted is retired and its replacement is not (yet) admitted.
89
- */
90
- export function learnBlocks(pos, neg) {
91
- // A block word must never occur anywhere in a positive task: measured, a single counter-example otherwise taught
92
- // the binder to refuse every task containing 'off'.
93
- const posQ = new Set(pos.flatMap((e) => String(e.task).toLowerCase().match(/[a-z]{3,}/g) || []));
94
- const blockWords = [...new Set(neg.flatMap((e) => questionWords(e.task)))].filter((w) => !posQ.has(w)).sort();
95
- // Body block words (Phase 12). Measured in Phase 11: "20% off and then 5% sales tax is added" got past every
96
- // binder, because the tax is in the body, not the question. The words right after a number name its role ("20% OFF",
97
- // "5% sales TAX"), but only for number kinds whose role wording REPEATS across good examples (a closed vocabulary:
98
- // "off" follows a percentage in most discount tasks). After "$90 jacket" comes an item noun that differs in every
99
- // task (an open vocabulary), so a refused jacket task never teaches the binder to refuse jackets.
100
- const ctxOf = (task, kind) => numberTokens(task).filter((t) => t.kind === kind).flatMap((t) => t.ctx);
101
- // With few examples, "half" is a coincidence: measured on the demo rehearsal, 2 of a composed skill's 3 positives said
102
- // "$… dinner", so "$" looked role-marked and a fresh "$250 birthday dinner" task was refused as unverified wording.
103
- // 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.
104
- const need = Math.max(2, Math.min(pos.length, 3), Math.ceil(pos.length / 2));
105
- const kinds = KINDS.filter((k) => {
106
- const n = new Map();
107
- for (const e of pos) for (const w of new Set(ctxOf(e.task, k))) n.set(w, (n.get(w) || 0) + 1);
108
- return [...n.values()].some((c) => c >= need);
109
- });
110
- const words = [...new Set(neg.flatMap((e) => kinds.flatMap((k) => ctxOf(e.task, k))))].filter((w) => !posQ.has(w)).sort();
111
- return { blockWords, contextBlock: { kinds, words } };
112
- }
113
-
114
- /**
115
- * A confirmed failure contests the positives that look like it. Measured on the live home: four sales-tax misroutes
116
- * had been stored as POSITIVE examples (no gate could see them), and because a block word may never occur in a
117
- * positive task, they made "tax" impossible to learn: the misroute had immunized itself. When the critic rejects a
118
- * route, the rejected task's RARE role words (after a role-marked number, in under 25% of positives: "tax", not "off")
119
- * mark every positive that shares them as disputed. If that would contest over a third of the positives, the evidence
120
- * conflicts too much and nothing is demoted.
121
- */
122
- export function contested(pos, task) {
123
- const { kinds } = learnBlocks(pos, []).contextBlock;
124
- const ctx = (t) => new Set(numberTokens(t).filter((x) => kinds.includes(x.kind)).flatMap((x) => x.ctx));
125
- const sets = pos.map((e) => ctx(e.task));
126
- const words = [...ctx(task)].filter((w) => sets.filter((s) => s.has(w)).length < pos.length * 0.25).sort();
127
- const hit = pos.filter((_, i) => words.some((w) => sets[i].has(w)));
128
- return hit.length > pos.length / 3 ? { words, examples: [], tooMany: hit.length } : { words, examples: hit };
129
- }
130
-
131
- /** The words that say what a task's numbers MEAN: role words after role-marked numbers, plus its question words. */
132
- export function wordingOf(task, kinds) {
133
- // Role words carry their position: which occurrence of which number kind they follow. Measured in Phase 14: a
134
- // tax-then-split skill had verified "off" (after the 1st %) and "sales tax added" (after the 2nd), so a discount task
135
- // ("off" after BOTH) looked fully verified and was routed to it with zero calls. "off" after the 2nd % is new wording.
136
- // Occurrences are counted in the task's fullest line: mission prompts restate the goal on other lines (Phase 11).
137
- const SIGN = { percent: '%', currency: '$', plain: 'number' };
138
- const seen = {};
139
- const fullest = String(task).split(/\n+/).reduce((a, b) => (numberTokens(b).length > numberTokens(a).length ? b : a), '');
140
- const roles = numberTokens(fullest).filter((t) => kinds.includes(t.kind)).flatMap((t) => {
141
- seen[t.kind] = (seen[t.kind] || 0) + 1;
142
- return t.ctx.map((w) => `${w} after ${SIGN[t.kind]} #${seen[t.kind]}`);
143
- });
144
- return [...new Set([...roles, ...questionWords(task)])];
145
- }
146
-
147
- /**
148
- * Wording never seen in a positive example. Measured in Phase 12: every misroute any binder made was recorded as a
149
- * positive and then shielded itself, so a binding is only trusted when its wording has been verified before. Novel
150
- * wording ("8% tax", "an 18% tip") is not routed; the agent loop answers it, and the answers are compared.
151
- */
152
- export function novelWording(pos, task) {
153
- const { kinds } = learnBlocks(pos, []).contextBlock;
154
- const known = new Set(pos.flatMap((e) => wordingOf(e.task, kinds)));
155
- return wordingOf(task, kinds).filter((w) => !known.has(w));
156
- }
157
-
158
- /** Apply a spec to a task (the same logic the compiled binder runs). */
159
- export function applySpec(spec, task) {
160
- const toks = numberTokens(task);
161
- if (!spec.shapes.includes(shapeOf(toks))) return null;
162
- const q = questionWords(task);
163
- if (spec.blockWords.some((w) => q.includes(w))) return null;
164
- const cb = spec.contextBlock;
165
- if (cb && toks.some((t) => cb.kinds.includes(t.kind) && t.ctx.some((w) => cb.words.includes(w)))) return null;
166
- const out = {};
167
- for (const [k, s] of Object.entries(spec.params)) { const v = pick(toks, s); if (v === undefined) return null; out[k] = v; }
168
- return out;
169
- }
170
-
171
- /** Leave-one-out: every example must be predicted by the spec induced from all the others. */
172
- export function leaveOneOut(pos, neg, skill) {
173
- return pos.map((e, i) => {
174
- const rest = pos.filter((_, j) => j !== i);
175
- const r = induce(rest, neg, skill);
176
- const got = r.spec ? applySpec(r.spec, e.task) : null;
177
- const ok = Boolean(got) && Object.keys(e.input).every((k) => eq(got[k], e.input[k]));
178
- // A miss only because the held-out example has a unit no other example has ("knots") is novelty, not contradiction.
179
- let novel = false;
180
- if (!ok && r.spec) {
181
- const loose = { ...r.spec, params: Object.fromEntries(Object.entries(r.spec.params).map(([k, p]) => [k, { ...p, units: undefined }])) };
182
- const g2 = applySpec(loose, e.task);
183
- novel = Boolean(g2) && Object.keys(e.input).every((k) => eq(g2[k], e.input[k]));
184
- }
185
- return { task: e.task, ok, novel, got, error: r.error };
186
- });
187
- }
188
-
189
- /** Compile a spec into a self-contained, sandbox-runnable `function bind(task)`. */
190
- export function compileSpec(spec) {
191
- return [
192
- 'function bind(task) {',
193
- ` const SPEC = ${JSON.stringify(spec)};`,
194
- ` const KINDS = ${JSON.stringify(KINDS)};`,
195
- ` const round = ${round.toString()};`,
196
- ` ${numberTokens.toString()}`,
197
- ` ${questionWords.toString()}`,
198
- ` const shapeOf = ${shapeOf.toString()};`,
199
- ` ${pick.toString()}`,
200
- ` ${applySpec.toString()}`,
201
- ' return applySpec(SPEC, task);',
202
- '}',
203
- ].join('\n');
204
- }
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
+ }
@@ -16,11 +16,16 @@ function luhn(digits) {
16
16
 
17
17
  const DETECTORS = [
18
18
  ['SECRET', /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g],
19
- ['SECRET', /\b(?:sk|pk|rk)-[A-Za-z0-9_-]{20,}\b|\bgh[pousr]_[A-Za-z0-9]{30,}\b|\bAIza[0-9A-Za-z_-]{30,}\b|\bxox[abpr]-[A-Za-z0-9-]{10,}\b|\bAKIA[0-9A-Z]{16}\b/g],
19
+ ['SECRET', /\b(?:sk|pk|rk)-[A-Za-z0-9_-]{20,}\b|\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b|\bgh[pousr]_[A-Za-z0-9]{30,}\b|\bgithub_pat_[A-Za-z0-9_]{30,}\b|\bhf_[A-Za-z0-9]{30,}\b|\bAIza[0-9A-Za-z_-]{30,}\b|\bxox[abpr]-[A-Za-z0-9-]{10,}\b|\bAKIA[0-9A-Z]{16}\b/g],
20
+ // Bearer credentials: only the token after the scheme is sealed. Bounded whitespace keeps it linear.
21
+ ['SECRET', /(?<=\bBearer[ \t]{1,4})[A-Za-z0-9._~+/=-]{16,}/g],
20
22
  ['SECRET', /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g],
21
- ['SECRET', /(?<=\b(?:password|passwd|passcode|pin|secret|api[_-]?key|token)\s*(?:is|[:=])\s*["']?)[^\s"',;]{4,}/gi],
23
+ // Bounded look-behind whitespace ({0,8}) keeps this linear on long whitespace runs; the value may contain quotes
24
+ // (ab"cd1234) and ends before an optional closing quote.
25
+ ['SECRET', /(?<=\b(?:password|passwd|passcode|pin|secret|api[_-]?key|token)\s{0,8}(?:is|[:=])\s{0,8}["']?)(?!["'])[^\s,;]{4,}?(?=["']?(?:[\s,;]|$))/gi],
22
26
  ['URL', /\bhttps?:\/\/[^\s<>"')]+[?&](?:token|key|sig|signature|auth|access_token|password)=[^\s<>"')]+/gi],
23
- ['EMAIL', /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g],
27
+ // RFC 5321 length limits (64 local, 253 domain) bound each attempt, so "a." x 50k is linear, not quadratic.
28
+ ['EMAIL', /\b[A-Za-z0-9_.%+-]{1,64}@[A-Za-z0-9.-]{1,253}\.[A-Za-z]{2,24}\b/g],
24
29
  ['IBAN', /\b[A-Z]{2}\d{2}(?:\s?[A-Z0-9]{4}){2,7}(?:\s?[A-Z0-9]{1,4})?\b/g],
25
30
  ['CARD', /\b(?:\d[ -]?){12,18}\d\b/g],
26
31
  ['SSN', /\b\d{3}-\d{2}-\d{4}\b/g],
@@ -29,7 +34,7 @@ const DETECTORS = [
29
34
  ['PERSON', /\b(?:Dr|Mr|Mrs|Ms|Mx|Prof|Sr|Sra|Herr|Frau)\.?\s+[A-Z][a-z'’-]+(?:\s+[A-Z][a-z'’-]+){0,2}/g],
30
35
  ['ADDRESS', /\b\d{1,6}\s+(?:[A-Z][a-z]+\s+){1,4}(?:Street|St|Avenue|Ave|Road|Rd|Boulevard|Blvd|Lane|Ln|Drive|Way|Court|Ct|Place|Pl|Terrace|Parkway|Pkwy|Highway|Hwy)\b\.?(?:,\s*[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)?/g],
31
36
  ['ID', /\b[A-Z]{2,5}-\d{5,}\b/g],
32
- ['ID', /(?<=\b(?:account|acct|patient|customer|member|policy|case|invoice)\s*(?:no\.?|number|#|id)?\s*[:#]?\s*)\d{5,}\b/gi],
37
+ ['ID', /(?<=\b(?:account|acct|patient|customer|member|policy|case|invoice)\s{0,8}(?:no\.?|number|#|id)?\s{0,8}[:#]?\s{0,8})\d{5,}\b/gi],
33
38
  ];
34
39
 
35
40
  const VALIDATE = {
@@ -77,7 +82,9 @@ export class SealSession {
77
82
  constructor() { this.byValue = new Map(); this.byPlaceholder = new Map(); this.counts = {}; }
78
83
 
79
84
  placeholder(type, value) {
80
- const key = value.toLowerCase();
85
+ // Only e-mail addresses are case-insensitive. Secrets, IDs and names that differ in case are different
86
+ // values and must get different placeholders (sk-ABCD... and sk-abcd... used to share one).
87
+ const key = type === 'EMAIL' ? `${type}:${value.toLowerCase()}` : `${type}:${value}`;
81
88
  if (this.byValue.has(key)) return this.byValue.get(key);
82
89
  this.counts[type] = (this.counts[type] || 0) + 1;
83
90
  const ph = `${OPEN}${type}_${this.counts[type]}${CLOSE}`;
@@ -95,15 +102,34 @@ export class SealSession {
95
102
  get size() { return this.byPlaceholder.size; }
96
103
  values() { return [...this.byPlaceholder.values()]; }
97
104
 
98
- unseal(text, { json = false } = {}) {
99
- let s = String(text ?? '');
100
- for (const [ph, { type, value }] of this.byPlaceholder) {
101
- const n = ph.slice(OPEN.length + type.length + 1, -CLOSE.length);
102
- const re = new RegExp(`(?:${OPEN}|\\[\\[?|«|<)?\\b${type}_${n}\\b(?:${CLOSE}|\\]\\]?|»|>)?`, 'g');
103
- const rep = json ? JSON.stringify(value).slice(1, -1) : value;
104
- s = s.replace(re, () => rep);
105
- }
106
- return s;
105
+ /**
106
+ * Put the real values back.
107
+ *
108
+ * Default (lenient) mode restores every form that names a placeholder issued by THIS session:
109
+ * the exact ⟦EMAIL_1⟧, mangled forms such as [EMAIL_1], [[EMAIL_1]], «EMAIL_1», <EMAIL_1>, and the bare word
110
+ * EMAIL_1. That is what makes a model's slightly-mangled reply round-trip, and it is also a risk: a model (or
111
+ * text it copied from an attacker) that writes "EMAIL_1" anywhere receives the real address. Placeholders that
112
+ * were never issued in this session (EMAIL_9) are never touched in either mode.
113
+ *
114
+ * `strict: true` restores only the exact ⟦TYPE_n⟧ tokens this session issued. Use it for any text a model wrote
115
+ * that will be shown to someone other than the person whose data was sealed.
116
+ *
117
+ * Replacement is a single pass: a restored value is never rewritten again, even if it contains text that looks
118
+ * like another placeholder (PHONE_1@corp.example).
119
+ */
120
+ unseal(text, { json = false, strict = false } = {}) {
121
+ const s = String(text ?? '');
122
+ if (this.byPlaceholder.size === 0) return s;
123
+ const ids = new Map();
124
+ for (const [ph, entry] of this.byPlaceholder) ids.set(ph.slice(OPEN.length, -CLOSE.length), entry);
125
+ const alt = [...ids.keys()].sort((a, b) => b.length - a.length).join('|');
126
+ const re = strict
127
+ ? new RegExp(`${OPEN}(${alt})${CLOSE}`, 'g')
128
+ : new RegExp(`(?:${OPEN}|\\[\\[?|«|<)?\\b(${alt})\\b(?:${CLOSE}|\\]\\]?|»|>)?`, 'g');
129
+ return s.replace(re, (_m, id) => {
130
+ const { value } = ids.get(id);
131
+ return json ? JSON.stringify(value).slice(1, -1) : value;
132
+ });
107
133
  }
108
134
 
109
135
  audit(payload) {