assignment-user-matcher 1.15.0 → 1.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +378 -9
- package/dist/index.d.ts +5 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -1
- package/dist/learning/atomic-ingestion.d.ts +11 -0
- package/dist/learning/atomic-ingestion.d.ts.map +1 -0
- package/dist/learning/atomic-ingestion.js +187 -0
- package/dist/learning/auto-weights.d.ts +13 -2
- package/dist/learning/auto-weights.d.ts.map +1 -1
- package/dist/learning/auto-weights.js +203 -35
- package/dist/learning/features.d.ts +5 -3
- package/dist/learning/features.d.ts.map +1 -1
- package/dist/learning/features.js +105 -4
- package/dist/learning/policy.d.ts +57 -0
- package/dist/learning/policy.d.ts.map +1 -0
- package/dist/learning/policy.js +71 -0
- package/dist/managers/LearningManager.d.ts +312 -35
- package/dist/managers/LearningManager.d.ts.map +1 -1
- package/dist/managers/LearningManager.js +1006 -168
- package/dist/matcher.class.d.ts +98 -11
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +247 -40
- package/dist/scheduling/constraints/cost.d.ts.map +1 -1
- package/dist/scheduling/constraints/cost.js +3 -2
- package/dist/scheduling/constraints/employee-scope.d.ts +5 -0
- package/dist/scheduling/constraints/employee-scope.d.ts.map +1 -0
- package/dist/scheduling/constraints/employee-scope.js +157 -0
- package/dist/scheduling/constraints/notice.d.ts.map +1 -1
- package/dist/scheduling/constraints/notice.js +8 -5
- package/dist/scheduling/constraints/rest-days.d.ts.map +1 -1
- package/dist/scheduling/constraints/rest-days.js +6 -6
- package/dist/scheduling/cost.d.ts.map +1 -1
- package/dist/scheduling/cost.js +2 -1
- package/dist/scheduling/engine/construction.d.ts +11 -3
- package/dist/scheduling/engine/construction.d.ts.map +1 -1
- package/dist/scheduling/engine/construction.js +31 -6
- package/dist/scheduling/engine/objective.d.ts +4 -4
- package/dist/scheduling/engine/objective.d.ts.map +1 -1
- package/dist/scheduling/engine/objective.js +12 -4
- package/dist/scheduling/engine/propagation.js +2 -1
- package/dist/scheduling/engine/search.d.ts +1 -0
- package/dist/scheduling/engine/search.d.ts.map +1 -1
- package/dist/scheduling/engine/search.js +1 -1
- package/dist/scheduling/engine/state.d.ts.map +1 -1
- package/dist/scheduling/engine/state.js +4 -0
- package/dist/scheduling/index.d.ts +1 -1
- package/dist/scheduling/index.d.ts.map +1 -1
- package/dist/scheduling/model.d.ts +1 -1
- package/dist/scheduling/model.d.ts.map +1 -1
- package/dist/scheduling/model.js +184 -42
- package/dist/scheduling/operations.d.ts +4 -0
- package/dist/scheduling/operations.d.ts.map +1 -1
- package/dist/scheduling/operations.js +36 -16
- package/dist/scheduling/provenance.d.ts +1 -1
- package/dist/scheduling/provenance.d.ts.map +1 -1
- package/dist/scheduling/provenance.js +16 -2
- package/dist/scheduling/scheduler.class.d.ts +1 -1
- package/dist/scheduling/scheduler.class.d.ts.map +1 -1
- package/dist/scheduling/scheduler.class.js +5 -3
- package/dist/scheduling/time.d.ts +2 -0
- package/dist/scheduling/time.d.ts.map +1 -1
- package/dist/scheduling/time.js +26 -1
- package/dist/scheduling/types.d.ts +78 -3
- package/dist/scheduling/types.d.ts.map +1 -1
- package/dist/types/matcher.d.ts +309 -4
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/keys.d.ts +12 -2
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +35 -2
- package/package.json +2 -1
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.prepareIngestion = void 0;
|
|
4
|
+
/** Internal, deliberately limited unit of work for learning ingestion.
|
|
5
|
+
* Reads remain sparse. Writes are simulated in Lua before any mutation so a
|
|
6
|
+
* bad counter/type cannot leave an applied marker beside partially trained data.
|
|
7
|
+
* Read dependencies are compared inside the same script; conflicts re-plan.
|
|
8
|
+
*/
|
|
9
|
+
function prepareIngestion(client, scripts) {
|
|
10
|
+
const reads = [];
|
|
11
|
+
const writes = [];
|
|
12
|
+
const keys = new Set();
|
|
13
|
+
const readCommands = { get: 'GET', hmGet: 'HMGET', sMembers: 'SMEMBERS' };
|
|
14
|
+
const writeCommands = {
|
|
15
|
+
hSet: 'HSET',
|
|
16
|
+
hIncrBy: 'HINCRBY',
|
|
17
|
+
hIncrByFloat: 'HINCRBYFLOAT',
|
|
18
|
+
incr: 'INCR',
|
|
19
|
+
sAdd: 'SADD',
|
|
20
|
+
set: 'SET',
|
|
21
|
+
del: 'DEL',
|
|
22
|
+
pExpire: 'PEXPIRE',
|
|
23
|
+
};
|
|
24
|
+
function stage(name, args) {
|
|
25
|
+
if (name === 'eval') {
|
|
26
|
+
const id = scripts.indexOf(args[0]);
|
|
27
|
+
if (id < 0)
|
|
28
|
+
throw new Error('Unsupported ingestion script');
|
|
29
|
+
args[1].keys.forEach((key) => keys.add(key));
|
|
30
|
+
writes.push({ script: id + 1, keys: args[1].keys, args: args[1].arguments });
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
const command = writeCommands[name];
|
|
34
|
+
if (!command)
|
|
35
|
+
throw new Error(`Unsupported ingestion write: ${name}`);
|
|
36
|
+
keys.add(args[0]);
|
|
37
|
+
let flat = args.flat();
|
|
38
|
+
if (name === 'set' && args[2]) {
|
|
39
|
+
flat = args.slice(0, 2);
|
|
40
|
+
if (args[2].PX !== undefined)
|
|
41
|
+
flat.push('PX', args[2].PX);
|
|
42
|
+
if (args[2].XX)
|
|
43
|
+
flat.push('XX');
|
|
44
|
+
}
|
|
45
|
+
writes.push({ command, args: flat.map(String) });
|
|
46
|
+
}
|
|
47
|
+
const batch = new Proxy({}, {
|
|
48
|
+
get: (_, name) => name === 'exec'
|
|
49
|
+
? async () => []
|
|
50
|
+
: (...args) => {
|
|
51
|
+
stage(name, args);
|
|
52
|
+
return batch;
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
const staged = new Proxy({}, {
|
|
56
|
+
get: (_, name) => {
|
|
57
|
+
if (name === 'multi')
|
|
58
|
+
return () => batch;
|
|
59
|
+
if (readCommands[name])
|
|
60
|
+
return async (...args) => {
|
|
61
|
+
keys.add(args[0]);
|
|
62
|
+
const value = await client[name](...args);
|
|
63
|
+
reads.push({
|
|
64
|
+
command: readCommands[name],
|
|
65
|
+
args: args.flat().map(String),
|
|
66
|
+
value: Array.isArray(value) ? [...value] : value,
|
|
67
|
+
});
|
|
68
|
+
return value;
|
|
69
|
+
};
|
|
70
|
+
return async (...args) => {
|
|
71
|
+
stage(name, args);
|
|
72
|
+
};
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
return {
|
|
76
|
+
client: staged,
|
|
77
|
+
async commit() {
|
|
78
|
+
const result = await client.eval(commitScript(scripts), {
|
|
79
|
+
keys: [...keys],
|
|
80
|
+
arguments: [JSON.stringify({ reads, writes })],
|
|
81
|
+
});
|
|
82
|
+
return Number(result) === 1;
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
exports.prepareIngestion = prepareIngestion;
|
|
87
|
+
function commitScript(scripts) {
|
|
88
|
+
return `
|
|
89
|
+
local plan = cjson.decode(ARGV[1])
|
|
90
|
+
local real = redis
|
|
91
|
+
local function same(a, b)
|
|
92
|
+
if b == cjson.null then return a == false end
|
|
93
|
+
if type(b) ~= 'table' then return a == b end
|
|
94
|
+
if type(a) ~= 'table' or #a ~= #b then return false end
|
|
95
|
+
for i = 1, #b do if not same(a[i], b[i]) then return false end end
|
|
96
|
+
return true
|
|
97
|
+
end
|
|
98
|
+
for _, r in ipairs(plan.reads) do
|
|
99
|
+
local actual = real.call(r.command, unpack(r.args))
|
|
100
|
+
if r.command == 'SMEMBERS' then table.sort(actual); table.sort(r.value) end
|
|
101
|
+
if not same(actual, r.value) then return 0 end
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
-- Simulate every write against a sparse overlay. No real writes happen until
|
|
105
|
+
-- all types, numeric results, TTLs and embedded decay scripts have validated.
|
|
106
|
+
local state = {}
|
|
107
|
+
local commands = {}
|
|
108
|
+
local function load(key)
|
|
109
|
+
if not state[key] then
|
|
110
|
+
state[key] = { kind = real.call('TYPE', key).ok, fields = {}, members = {} }
|
|
111
|
+
end
|
|
112
|
+
return state[key]
|
|
113
|
+
end
|
|
114
|
+
local function expect(s, kind)
|
|
115
|
+
if s.kind ~= 'none' and s.kind ~= kind then error('WRONGTYPE learning ingestion') end
|
|
116
|
+
end
|
|
117
|
+
local function number(value)
|
|
118
|
+
local n = tonumber(value)
|
|
119
|
+
if not n or n ~= n or n == math.huge or n == -math.huge then
|
|
120
|
+
error('Invalid numeric learning value')
|
|
121
|
+
end
|
|
122
|
+
return n
|
|
123
|
+
end
|
|
124
|
+
local function emit(command, args)
|
|
125
|
+
table.insert(commands, { command = command, args = args })
|
|
126
|
+
end
|
|
127
|
+
local call
|
|
128
|
+
call = function(command, ...)
|
|
129
|
+
local a = {...}
|
|
130
|
+
local key = a[1]
|
|
131
|
+
local s = load(key)
|
|
132
|
+
if command == 'HGET' then
|
|
133
|
+
expect(s, 'hash')
|
|
134
|
+
if s.fields[a[2]] == nil then s.fields[a[2]] = real.call('HGET', key, a[2]) end
|
|
135
|
+
return s.fields[a[2]]
|
|
136
|
+
elseif command == 'HSET' then
|
|
137
|
+
expect(s, 'hash'); s.kind = 'hash'
|
|
138
|
+
for i = 2, #a, 2 do s.fields[a[i]] = tostring(a[i+1]) end
|
|
139
|
+
emit(command, a); return 1
|
|
140
|
+
elseif command == 'HINCRBY' or command == 'HINCRBYFLOAT' then
|
|
141
|
+
local old = call('HGET', key, a[2]) or '0'
|
|
142
|
+
local value = number(old) + number(a[3])
|
|
143
|
+
number(value)
|
|
144
|
+
if command == 'HINCRBY' and (value % 1 ~= 0 or math.abs(value) > 9007199254740991) then
|
|
145
|
+
error('Invalid integer learning counter')
|
|
146
|
+
end
|
|
147
|
+
return call('HSET', key, a[2], string.format('%.17g', value))
|
|
148
|
+
elseif command == 'SADD' then
|
|
149
|
+
expect(s, 'set'); s.kind = 'set'; emit(command, a); return 1
|
|
150
|
+
elseif command == 'SET' then
|
|
151
|
+
local ttl = nil
|
|
152
|
+
local xx = false
|
|
153
|
+
for i = 3, #a do
|
|
154
|
+
if a[i] == 'PX' then
|
|
155
|
+
ttl = number(a[i+1])
|
|
156
|
+
if ttl <= 0 or ttl % 1 ~= 0 or ttl > 9007199254740991 then error('Invalid learning TTL') end
|
|
157
|
+
elseif a[i] == 'XX' then xx = true end
|
|
158
|
+
end
|
|
159
|
+
if xx and s.kind == 'none' then return false end
|
|
160
|
+
s.kind = 'string'; s.value = a[2]; emit(command, a); return 'OK'
|
|
161
|
+
elseif command == 'INCR' then
|
|
162
|
+
expect(s, 'string')
|
|
163
|
+
local value = number(s.value or real.call('GET', key) or '0') + 1
|
|
164
|
+
if value % 1 ~= 0 or math.abs(value) > 9007199254740991 then error('Invalid learning counter') end
|
|
165
|
+
s.value = string.format('%.17g', value); s.kind = 'string'
|
|
166
|
+
emit('SET', { key, s.value, 'KEEPTTL' }); return value
|
|
167
|
+
elseif command == 'DEL' then
|
|
168
|
+
s.kind = 'none'; s.fields = {}; s.value = nil; emit(command, a); return 1
|
|
169
|
+
elseif command == 'PEXPIRE' then
|
|
170
|
+
local ttl = number(a[2])
|
|
171
|
+
if ttl <= 0 or ttl % 1 ~= 0 or ttl > 9007199254740991 then error('Invalid learning TTL') end
|
|
172
|
+
emit(command, a); return 1
|
|
173
|
+
end
|
|
174
|
+
error('Unsupported ingestion command: ' .. command)
|
|
175
|
+
end
|
|
176
|
+
local redis = { call = call }
|
|
177
|
+
local scripts = {
|
|
178
|
+
${scripts.map((script) => `function(KEYS, ARGV)\n${script}\nend`).join(',\n')}
|
|
179
|
+
}
|
|
180
|
+
for _, w in ipairs(plan.writes) do
|
|
181
|
+
if w.script then scripts[w.script](w.keys, w.args)
|
|
182
|
+
else call(w.command, unpack(w.args)) end
|
|
183
|
+
end
|
|
184
|
+
for _, c in ipairs(commands) do real.call(c.command, unpack(c.args)) end
|
|
185
|
+
return 1
|
|
186
|
+
`;
|
|
187
|
+
}
|
|
@@ -25,8 +25,9 @@
|
|
|
25
25
|
*
|
|
26
26
|
* Pure module: no Redis access, O(number of tags) per call.
|
|
27
27
|
*/
|
|
28
|
-
import type { AutoRoutingWeightsOptions, LearningTagStat } from '../types/matcher';
|
|
29
|
-
|
|
28
|
+
import type { AutoRoutingWeightsOptions, AutoWeightExplanation, LearningTagStat } from '../types/matcher';
|
|
29
|
+
type OptionalAutoWeightsKeys = 'priorWeight' | 'maxDeltaPerSync' | 'decayHalfLifeMs' | 'rng' | 'priorVariance' | 'vetoCooldownMs' | 'totalAttempts';
|
|
30
|
+
export declare const DEFAULT_AUTO_WEIGHTS_OPTIONS: Required<Omit<AutoRoutingWeightsOptions, OptionalAutoWeightsKeys>> & {
|
|
30
31
|
priorWeight: number;
|
|
31
32
|
};
|
|
32
33
|
/**
|
|
@@ -41,4 +42,14 @@ export declare const DEFAULT_AUTO_WEIGHTS_OPTIONS: Required<Omit<AutoRoutingWeig
|
|
|
41
42
|
* tags instead of the flat `priorWeight` when provided
|
|
42
43
|
*/
|
|
43
44
|
export declare function synthesizeRoutingWeights(stats: LearningTagStat[], options?: AutoRoutingWeightsOptions, knownTags?: string[], existingWeights?: Record<string, number>): Record<string, number>;
|
|
45
|
+
/**
|
|
46
|
+
* The same synthesis, with the reasoning attached: estimate, uncertainty,
|
|
47
|
+
* evidence, last observation, decay settings and next reassessment per tag.
|
|
48
|
+
*
|
|
49
|
+
* A hard veto changes who can be given work at all, so "the model said so"
|
|
50
|
+
* is not an adequate account of it. `synthesizeRoutingWeights` is this
|
|
51
|
+
* function with the explanations dropped.
|
|
52
|
+
*/
|
|
53
|
+
export declare function explainRoutingWeights(stats: LearningTagStat[], options?: AutoRoutingWeightsOptions, knownTags?: string[], existingWeights?: Record<string, number>, now?: number): AutoWeightExplanation[];
|
|
54
|
+
export {};
|
|
44
55
|
//# sourceMappingURL=auto-weights.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auto-weights.d.ts","sourceRoot":"","sources":["../../src/learning/auto-weights.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"auto-weights.d.ts","sourceRoot":"","sources":["../../src/learning/auto-weights.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,KAAK,EACR,yBAAyB,EAEzB,qBAAqB,EACrB,eAAe,EAClB,MAAM,kBAAkB,CAAC;AAE1B,KAAK,uBAAuB,GACtB,aAAa,GACb,iBAAiB,GACjB,iBAAiB,GACjB,KAAK,GACL,eAAe,GACf,gBAAgB,GAChB,eAAe,CAAC;AAEtB,eAAO,MAAM,4BAA4B,EAAE,QAAQ,CAAC,IAAI,CAAC,yBAAyB,EAAE,uBAAuB,CAAC,CAAC,GAAG;IAC5G,WAAW,EAAE,MAAM,CAAC;CAevB,CAAC;AAsQF;;;;;;;;;;GAUG;AACH,wBAAgB,wBAAwB,CACpC,KAAK,EAAE,eAAe,EAAE,EACxB,OAAO,CAAC,EAAE,yBAAyB,EACnC,SAAS,CAAC,EAAE,MAAM,EAAE,EACpB,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACzC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAMxB;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACjC,KAAK,EAAE,eAAe,EAAE,EACxB,OAAO,CAAC,EAAE,yBAAyB,EACnC,SAAS,CAAC,EAAE,MAAM,EAAE,EACpB,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EACxC,GAAG,GAAE,MAAmB,GACzB,qBAAqB,EAAE,CA2FzB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.synthesizeRoutingWeights = exports.DEFAULT_AUTO_WEIGHTS_OPTIONS = void 0;
|
|
3
|
+
exports.explainRoutingWeights = exports.synthesizeRoutingWeights = exports.DEFAULT_AUTO_WEIGHTS_OPTIONS = void 0;
|
|
4
4
|
exports.DEFAULT_AUTO_WEIGHTS_OPTIONS = {
|
|
5
5
|
minSamples: 5,
|
|
6
6
|
vetoThreshold: -0.5,
|
|
@@ -12,6 +12,9 @@ exports.DEFAULT_AUTO_WEIGHTS_OPTIONS = {
|
|
|
12
12
|
minTotalSamples: 0,
|
|
13
13
|
minSamplesForVeto: 5,
|
|
14
14
|
terminalOnlyTagStats: false,
|
|
15
|
+
rewardModel: 'gaussian',
|
|
16
|
+
rewardRange: [-1, 1],
|
|
17
|
+
priorStrength: 2,
|
|
15
18
|
};
|
|
16
19
|
function resolveOptions(options) {
|
|
17
20
|
const maxWeight = options?.maxWeight ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.maxWeight;
|
|
@@ -28,35 +31,145 @@ function resolveOptions(options) {
|
|
|
28
31
|
priorWeight: options?.priorWeight ?? Math.round(maxWeight / 2),
|
|
29
32
|
maxDeltaPerSync: options?.maxDeltaPerSync,
|
|
30
33
|
decayHalfLifeMs: options?.decayHalfLifeMs,
|
|
34
|
+
vetoCooldownMs: options?.vetoCooldownMs,
|
|
35
|
+
totalAttempts: options?.totalAttempts,
|
|
36
|
+
rewardModel: options?.rewardModel ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.rewardModel,
|
|
37
|
+
rewardRange: options?.rewardRange ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.rewardRange,
|
|
38
|
+
priorStrength: options?.priorStrength ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.priorStrength,
|
|
39
|
+
// Variance of a uniform draw over the reward range is (range^2)/12;
|
|
40
|
+
// (range/4)^2 is the slightly wider, deliberately conservative
|
|
41
|
+
// default — a prior that is too tight is a prior that vetoes.
|
|
42
|
+
priorVariance: options?.priorVariance ??
|
|
43
|
+
Math.pow(((options?.rewardRange ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.rewardRange)[1] -
|
|
44
|
+
(options?.rewardRange ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.rewardRange)[0]) /
|
|
45
|
+
4, 2),
|
|
31
46
|
rng: options?.rng ?? Math.random,
|
|
32
47
|
};
|
|
33
48
|
}
|
|
34
49
|
function isManualTag(tag, existingWeights) {
|
|
35
50
|
return !!existingWeights && tag in existingWeights;
|
|
36
51
|
}
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
52
|
+
/**
|
|
53
|
+
* Evidence backing a tag, in independent attempts.
|
|
54
|
+
*
|
|
55
|
+
* The decayed weight sum (`count`) is NOT a sample size: scaling every weight
|
|
56
|
+
* equally leaves it looking like fewer observations than were actually seen,
|
|
57
|
+
* and after a long idle period it approaches zero without anything having
|
|
58
|
+
* been learned or forgotten in kind. Sample floors are therefore judged
|
|
59
|
+
* against, in order of preference: the never-decayed lifetime attempt count,
|
|
60
|
+
* the Kish effective sample size, and only then the raw count.
|
|
61
|
+
*/
|
|
62
|
+
function evidence(stat) {
|
|
63
|
+
if (typeof stat.attempts === 'number' && stat.attempts > 0)
|
|
64
|
+
return stat.attempts;
|
|
65
|
+
if (typeof stat.effectiveSampleSize === 'number' && stat.effectiveSampleSize > 0)
|
|
66
|
+
return stat.effectiveSampleSize;
|
|
67
|
+
return stat.count;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Prior-backed posterior over the mean reward.
|
|
71
|
+
*
|
|
72
|
+
* The pre-1.16 code took `sqrt(variance / count)` straight from the observed
|
|
73
|
+
* moments, so five identical observations produced variance 0 and therefore a
|
|
74
|
+
* confidence interval of zero width — total certainty from five samples, and
|
|
75
|
+
* the `'confidence'` policy would hard-veto on it. A prior floor is what
|
|
76
|
+
* makes "I have seen the same thing five times" different from "I know".
|
|
77
|
+
*/
|
|
78
|
+
function posterior(stat, opts) {
|
|
79
|
+
const n = Math.max(0, evidence(stat));
|
|
80
|
+
const k = Math.max(0, opts.priorStrength);
|
|
81
|
+
const [lo, hi] = opts.rewardRange;
|
|
82
|
+
if (opts.rewardModel === 'bernoulli') {
|
|
83
|
+
// Rescale rewards into [0, 1] and treat the tag as a Beta-Bernoulli
|
|
84
|
+
// arm. Only sound when the reward genuinely is a success indicator —
|
|
85
|
+
// applying Bernoulli formulas to arbitrary continuous rewards is the
|
|
86
|
+
// error this option exists to make explicit rather than implicit.
|
|
87
|
+
const span = hi - lo || 1;
|
|
88
|
+
const p = Math.max(0, Math.min(1, (stat.meanReward - lo) / span));
|
|
89
|
+
const alpha = 1 + p * n;
|
|
90
|
+
const beta = 1 + (1 - p) * n;
|
|
91
|
+
const total = alpha + beta;
|
|
92
|
+
const mean = alpha / total;
|
|
93
|
+
const variance = (alpha * beta) / (total * total * (total + 1));
|
|
94
|
+
return { mean: lo + mean * span, se: Math.sqrt(variance) * span, alpha, beta };
|
|
95
|
+
}
|
|
96
|
+
const observedVariance = stat.variance ?? opts.priorVariance;
|
|
97
|
+
// Normal-inverse-chi-square style shrinkage: the prior contributes k
|
|
98
|
+
// pseudo-observations of variance priorVariance.
|
|
99
|
+
const varPost = (n * observedVariance + k * opts.priorVariance) / (n + k);
|
|
100
|
+
const priorMean = (lo + hi) / 2;
|
|
101
|
+
const mean = (n * stat.meanReward + k * priorMean) / (n + k);
|
|
102
|
+
return { mean, se: Math.sqrt(varPost / (n + k)) };
|
|
103
|
+
}
|
|
104
|
+
/** Marsaglia-Tsang gamma sampler (shape >= 1 via boost for shape < 1). */
|
|
105
|
+
function sampleGamma(shape, rng) {
|
|
106
|
+
if (shape < 1)
|
|
107
|
+
return sampleGamma(shape + 1, rng) * Math.pow(Math.max(rng(), 1e-12), 1 / shape);
|
|
108
|
+
const d = shape - 1 / 3;
|
|
109
|
+
const c = 1 / Math.sqrt(9 * d);
|
|
110
|
+
for (let i = 0; i < 1000; i++) {
|
|
111
|
+
const z = acklamInverseNormal(rng());
|
|
112
|
+
const v = Math.pow(1 + c * z, 3);
|
|
113
|
+
if (v <= 0)
|
|
114
|
+
continue;
|
|
115
|
+
const u = Math.max(rng(), 1e-12);
|
|
116
|
+
if (Math.log(u) < 0.5 * z * z + d - d * v + d * Math.log(v))
|
|
117
|
+
return d * v;
|
|
118
|
+
}
|
|
119
|
+
return d;
|
|
120
|
+
}
|
|
121
|
+
/** Beta draw as the ratio of two gamma draws. */
|
|
122
|
+
function sampleBeta(alpha, beta, rng) {
|
|
123
|
+
const x = sampleGamma(alpha, rng);
|
|
124
|
+
const y = sampleGamma(beta, rng);
|
|
125
|
+
return x + y > 0 ? x / (x + y) : 0.5;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Whether a learned veto is admissible for a tag.
|
|
129
|
+
*
|
|
130
|
+
* `minSamplesForVeto` applies to learned and manually-weighted tags alike:
|
|
131
|
+
* the floor exists because a hard veto removes eligibility outright, and that
|
|
132
|
+
* consequence does not depend on where the previous weight came from. (It
|
|
133
|
+
* still defaults to `minSamples`, so nothing changes for callers that never
|
|
134
|
+
* set it.)
|
|
135
|
+
*/
|
|
136
|
+
function canVeto(stat, vetoScore, opts, now) {
|
|
137
|
+
if (evidence(stat) < opts.minSamplesForVeto)
|
|
138
|
+
return { veto: false, cooldown: false };
|
|
139
|
+
// A veto with no recovery path is permanent exclusion. When a cooldown is
|
|
140
|
+
// configured and the last observation predates it, the tag is released
|
|
141
|
+
// for reassessment instead of staying vetoed on stale evidence.
|
|
142
|
+
if (opts.vetoCooldownMs !== undefined && stat.lastUpdatedAt && now - stat.lastUpdatedAt > opts.vetoCooldownMs) {
|
|
143
|
+
return { veto: false, cooldown: true };
|
|
144
|
+
}
|
|
145
|
+
return { veto: vetoScore <= opts.vetoThreshold, cooldown: false };
|
|
43
146
|
}
|
|
44
147
|
function tagScore(policy, stat, totalCount, opts) {
|
|
45
|
-
const
|
|
46
|
-
const
|
|
148
|
+
const post = posterior(stat, opts);
|
|
149
|
+
const mean = post.mean;
|
|
150
|
+
const se = post.se;
|
|
47
151
|
if (policy === 'confidence') {
|
|
48
152
|
const z = opts.confidenceZ;
|
|
49
|
-
return { ucb: mean + z * se, lcb: mean - z * se, sample: mean };
|
|
153
|
+
return { ucb: mean + z * se, lcb: mean - z * se, sample: mean, post };
|
|
50
154
|
}
|
|
51
155
|
if (policy === 'thompson') {
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
156
|
+
let sample;
|
|
157
|
+
if (opts.rewardModel === 'bernoulli' && post.alpha !== undefined && post.beta !== undefined) {
|
|
158
|
+
const [lo, hi] = opts.rewardRange;
|
|
159
|
+
sample = lo + sampleBeta(post.alpha, post.beta, opts.rng) * (hi - lo);
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
// Gaussian Thompson draw: mean + Z(rng) * se, where Z is the
|
|
163
|
+
// normal inverse CDF (Acklam/Bailey approximation). The posterior
|
|
164
|
+
// se is prior-backed, so the draw is never degenerate.
|
|
165
|
+
sample = mean + acklamInverseNormal(opts.rng()) * se;
|
|
166
|
+
}
|
|
167
|
+
return { ucb: sample, lcb: sample, sample, post };
|
|
56
168
|
}
|
|
57
|
-
// 'ucb1'
|
|
58
|
-
|
|
59
|
-
|
|
169
|
+
// 'ucb1' — kept bit-compatible with the pre-1.16 formula (raw observed
|
|
170
|
+
// mean, raw count) so existing deployments' weights do not shift.
|
|
171
|
+
const ucb = stat.meanReward + opts.explorationBonus * Math.sqrt(Math.log(totalCount + 1) / Math.max(1e-9, stat.count));
|
|
172
|
+
return { ucb, lcb: stat.meanReward, sample: ucb, post };
|
|
60
173
|
}
|
|
61
174
|
function normalizedWeight(score, maxWeight) {
|
|
62
175
|
const normalized = (Math.min(Math.max(score, -1), 1) + 1) / 2;
|
|
@@ -122,47 +235,102 @@ function acklamInverseNormal(p) {
|
|
|
122
235
|
* tags instead of the flat `priorWeight` when provided
|
|
123
236
|
*/
|
|
124
237
|
function synthesizeRoutingWeights(stats, options, knownTags, existingWeights) {
|
|
238
|
+
const weights = {};
|
|
239
|
+
for (const row of explainRoutingWeights(stats, options, knownTags, existingWeights)) {
|
|
240
|
+
weights[row.tag] = row.weight;
|
|
241
|
+
}
|
|
242
|
+
return weights;
|
|
243
|
+
}
|
|
244
|
+
exports.synthesizeRoutingWeights = synthesizeRoutingWeights;
|
|
245
|
+
/**
|
|
246
|
+
* The same synthesis, with the reasoning attached: estimate, uncertainty,
|
|
247
|
+
* evidence, last observation, decay settings and next reassessment per tag.
|
|
248
|
+
*
|
|
249
|
+
* A hard veto changes who can be given work at all, so "the model said so"
|
|
250
|
+
* is not an adequate account of it. `synthesizeRoutingWeights` is this
|
|
251
|
+
* function with the explanations dropped.
|
|
252
|
+
*/
|
|
253
|
+
function explainRoutingWeights(stats, options, knownTags, existingWeights, now = Date.now()) {
|
|
125
254
|
const opts = resolveOptions(options);
|
|
126
|
-
|
|
255
|
+
// Worker-level evidence floors count independent attempts. Summing
|
|
256
|
+
// per-tag counts would let one assignment carrying five tags clear a
|
|
257
|
+
// five-sample floor on its own — correlated evidence, counted five times.
|
|
258
|
+
const totalCount = opts.totalAttempts ?? stats.reduce((sum, s) => sum + s.count, 0);
|
|
127
259
|
if (opts.minTotalSamples > 0 && totalCount < opts.minTotalSamples) {
|
|
128
|
-
return
|
|
260
|
+
return [];
|
|
129
261
|
}
|
|
130
|
-
const
|
|
262
|
+
const explorationTotal = stats.reduce((sum, s) => sum + s.count, 0);
|
|
263
|
+
const rows = [];
|
|
264
|
+
const seen = new Set();
|
|
131
265
|
for (const stat of stats) {
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
266
|
+
seen.add(stat.tag);
|
|
267
|
+
const attempts = evidence(stat);
|
|
268
|
+
const base = {
|
|
269
|
+
tag: stat.tag,
|
|
270
|
+
weight: 0,
|
|
271
|
+
decision: 'scored',
|
|
272
|
+
attempts: stat.attempts,
|
|
273
|
+
effectiveSampleSize: stat.effectiveSampleSize,
|
|
274
|
+
lastObservedAt: stat.lastUpdatedAt,
|
|
275
|
+
decayHalfLifeMs: opts.decayHalfLifeMs,
|
|
276
|
+
};
|
|
277
|
+
if (attempts < opts.minSamples) {
|
|
278
|
+
rows.push({
|
|
279
|
+
...base,
|
|
280
|
+
decision: 'insufficient-evidence',
|
|
281
|
+
weight: existingWeights?.[stat.tag] ?? opts.priorWeight,
|
|
282
|
+
});
|
|
136
283
|
continue;
|
|
137
284
|
}
|
|
138
|
-
const { ucb,
|
|
285
|
+
const { ucb, sample, post } = tagScore(opts.policy, stat, explorationTotal, opts);
|
|
139
286
|
const weightScore = opts.policy === 'thompson' ? sample : ucb;
|
|
140
287
|
// Veto decisions are deterministic and conservative: 'confidence'
|
|
141
288
|
// requires the WHOLE interval below the threshold (ucb), 'thompson'
|
|
142
289
|
// and 'ucb1' judge the raw mean — never a random draw, never an
|
|
143
290
|
// uncertainty-widened lower bound.
|
|
144
291
|
const vetoScore = opts.policy === 'confidence' ? ucb : stat.meanReward;
|
|
145
|
-
|
|
146
|
-
|
|
292
|
+
const z = opts.confidenceZ;
|
|
293
|
+
const detail = {
|
|
294
|
+
...base,
|
|
295
|
+
estimate: post.mean,
|
|
296
|
+
uncertainty: post.se,
|
|
297
|
+
lowerBound: post.mean - z * post.se,
|
|
298
|
+
upperBound: post.mean + z * post.se,
|
|
299
|
+
};
|
|
300
|
+
const { veto, cooldown } = canVeto(stat, vetoScore, opts, now);
|
|
301
|
+
if (veto) {
|
|
302
|
+
rows.push({ ...detail, decision: 'veto', weight: 0 });
|
|
147
303
|
continue;
|
|
148
304
|
}
|
|
149
|
-
|
|
150
|
-
|
|
305
|
+
if (cooldown) {
|
|
306
|
+
rows.push({
|
|
307
|
+
...detail,
|
|
308
|
+
decision: 'cooldown',
|
|
309
|
+
weight: existingWeights?.[stat.tag] ?? opts.priorWeight,
|
|
310
|
+
reassessAt: stat.lastUpdatedAt !== undefined ? stat.lastUpdatedAt + (opts.vetoCooldownMs ?? 0) : undefined,
|
|
311
|
+
});
|
|
312
|
+
continue;
|
|
313
|
+
}
|
|
314
|
+
rows.push({ ...detail, weight: normalizedWeight(weightScore, opts.maxWeight) });
|
|
151
315
|
}
|
|
152
316
|
if (knownTags) {
|
|
153
317
|
for (const tag of knownTags) {
|
|
154
|
-
if (
|
|
155
|
-
|
|
318
|
+
if (seen.has(tag))
|
|
319
|
+
continue;
|
|
320
|
+
seen.add(tag);
|
|
321
|
+
rows.push({ tag, weight: existingWeights?.[tag] ?? opts.priorWeight, decision: 'unobserved' });
|
|
156
322
|
}
|
|
157
323
|
}
|
|
158
324
|
// Tags the user already had weights for are treated as implicitly known:
|
|
159
325
|
// keep the existing value until sufficient evidence overrides it.
|
|
160
326
|
if (existingWeights) {
|
|
161
327
|
for (const [tag, existing] of Object.entries(existingWeights)) {
|
|
162
|
-
if (
|
|
163
|
-
|
|
328
|
+
if (seen.has(tag))
|
|
329
|
+
continue;
|
|
330
|
+
seen.add(tag);
|
|
331
|
+
rows.push({ tag, weight: existing, decision: 'prior' });
|
|
164
332
|
}
|
|
165
333
|
}
|
|
166
|
-
return
|
|
334
|
+
return rows;
|
|
167
335
|
}
|
|
168
|
-
exports.
|
|
336
|
+
exports.explainRoutingWeights = explainRoutingWeights;
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* assignment. All features are normalized to roughly [0, 1] so learned
|
|
6
6
|
* weights stay comparable across feature families.
|
|
7
7
|
*/
|
|
8
|
-
import type { User, LearningFeatures, LearningAssignmentContext } from '../types/matcher';
|
|
8
|
+
import type { User, LearningFeatures, LearningAssignmentContext, LearningFeatureContext } from '../types/matcher';
|
|
9
9
|
/**
|
|
10
10
|
* Cosine similarity between two numeric vectors.
|
|
11
11
|
* Returns 0 for mismatched lengths or zero-magnitude vectors.
|
|
@@ -13,7 +13,9 @@ import type { User, LearningFeatures, LearningAssignmentContext } from '../types
|
|
|
13
13
|
export declare function cosineSimilarity(a: number[], b: number[]): number;
|
|
14
14
|
/**
|
|
15
15
|
* Default feature extractor: tag matches, normalized skill weights,
|
|
16
|
-
* tag-overlap ratio, optional embedding similarity,
|
|
16
|
+
* tag-overlap ratio, optional embedding similarity, SLA urgency, and —
|
|
17
|
+
* when performance aggregates are supplied — worker-side outcome rates,
|
|
18
|
+
* workload and their interactions.
|
|
17
19
|
*/
|
|
18
|
-
export declare function extractMatchFeatures(user: User, assignment: LearningAssignmentContext, slaTightnessReferenceMs?: number): LearningFeatures;
|
|
20
|
+
export declare function extractMatchFeatures(user: User, assignment: LearningAssignmentContext, slaTightnessReferenceMs?: number, context?: LearningFeatureContext): LearningFeatures;
|
|
19
21
|
//# sourceMappingURL=features.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features.d.ts","sourceRoot":"","sources":["../../src/learning/features.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"features.d.ts","sourceRoot":"","sources":["../../src/learning/features.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EACR,IAAI,EACJ,gBAAgB,EAChB,yBAAyB,EACzB,sBAAsB,EAEzB,MAAM,kBAAkB,CAAC;AAG1B;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,CAYjE;AAqFD;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAChC,IAAI,EAAE,IAAI,EACV,UAAU,EAAE,yBAAyB,EACrC,uBAAuB,GAAE,MAAgB,EACzC,OAAO,CAAC,EAAE,sBAAsB,GACjC,gBAAgB,CAsElB"}
|