assignment-user-matcher 1.2.3 → 1.3.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.
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Global arbitration for fair-tiebreaker bulk matching: decides which user
3
+ * tentatively wins each contested candidate assignment. Pure logic - no Redis.
4
+ * See MatcherOptions.enableFairTiebreaker / fairnessLoadPenalty /
5
+ * fairnessTieBand for the behavior each knob selects.
6
+ */
7
+ import type { FairnessMode } from '../types/matcher';
8
+ /**
9
+ * Turns a fairness preset into concrete arbitration knobs, scaled to the
10
+ * median candidate score of the current matching pass so consumers never
11
+ * have to know their own score scale. Explicitly-set expert knobs
12
+ * (fairnessLoadPenalty / fairnessTieBand > 0) always win over the preset.
13
+ */
14
+ export declare function resolveFairnessKnobs(mode: FairnessMode | undefined, pairPriorities: number[], explicit: {
15
+ loadPenalty: number;
16
+ tieBand: number;
17
+ }): {
18
+ loadPenalty: number;
19
+ tieBand: number;
20
+ };
21
+ export interface FairArbitrationOptions {
22
+ maxUserBacklogSize: number;
23
+ /**
24
+ * Per-user override of the award ceiling (compared against the same
25
+ * `backlogUsed` counter as `maxUserBacklogSize`). Used to fold in
26
+ * additional limits like the rolling-window grant cap, which can leave a
27
+ * user with less headroom than their backlog alone would allow.
28
+ */
29
+ maxByUser?: Map<string, number>;
30
+ /**
31
+ * Score subtracted per assignment already on (or won this pass into) a
32
+ * user's backlog. 0 disables load-penalized scoring.
33
+ */
34
+ loadPenalty?: number;
35
+ /**
36
+ * Width of the score bucket within which candidates count as tied; ties
37
+ * go to the less-loaded user. 0 disables tie-band arbitration.
38
+ */
39
+ tieBand?: number;
40
+ }
41
+ interface ArbitrablePair {
42
+ userId: string;
43
+ id: string;
44
+ priority: number;
45
+ }
46
+ /**
47
+ * Walks the candidate pairs in best-first order and awards each assignment to
48
+ * exactly one user, honoring per-user backlog caps. Mutates `backlogUsed`
49
+ * (one increment per awarded pair). `settled` marks assignments no longer
50
+ * available at all (already claimed, or lost to a concurrent process).
51
+ *
52
+ * Returns `winners` in award order and `deferred`: pairs skipped only because
53
+ * their user was at cap - a cap that the caller may roll back if the user
54
+ * loses a claim to a concurrent process, so these stay eligible for another
55
+ * arbitration round.
56
+ *
57
+ * With neither knob set the order is a plain stable sort by score descending,
58
+ * matching the pre-fairness-knob behavior exactly. With a knob set, ordering
59
+ * is load-aware and therefore dynamic - each award changes the winner's load,
60
+ * which can demote their remaining candidates - so a lazy max-heap re-ranks
61
+ * entries whose user's load has grown since they were pushed.
62
+ */
63
+ export declare function arbitrateFair<P extends ArbitrablePair>(pairs: P[], backlogUsed: Map<string, number>, settled: Set<string>, options: FairArbitrationOptions): {
64
+ winners: P[];
65
+ deferred: P[];
66
+ };
67
+ export {};
68
+ //# sourceMappingURL=fair-arbitration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fair-arbitration.d.ts","sourceRoot":"","sources":["../../src/scoring/fair-arbitration.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAarD;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAChC,IAAI,EAAE,YAAY,GAAG,SAAS,EAC9B,cAAc,EAAE,MAAM,EAAE,EACxB,QAAQ,EAAE;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GACnD;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAU1C;AAED,MAAM,WAAW,sBAAsB;IACnC,kBAAkB,EAAE,MAAM,CAAC;IAC3B;;;;;OAKG;IACH,SAAS,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,UAAU,cAAc;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,aAAa,CAAC,CAAC,SAAS,cAAc,EAClD,KAAK,EAAE,CAAC,EAAE,EACV,WAAW,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,EAChC,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,EACpB,OAAO,EAAE,sBAAsB,GAChC;IAAE,OAAO,EAAE,CAAC,EAAE,CAAC;IAAC,QAAQ,EAAE,CAAC,EAAE,CAAA;CAAE,CA6FjC"}
@@ -0,0 +1,151 @@
1
+ "use strict";
2
+ /**
3
+ * Global arbitration for fair-tiebreaker bulk matching: decides which user
4
+ * tentatively wins each contested candidate assignment. Pure logic - no Redis.
5
+ * See MatcherOptions.enableFairTiebreaker / fairnessLoadPenalty /
6
+ * fairnessTieBand for the behavior each knob selects.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.arbitrateFair = exports.resolveFairnessKnobs = void 0;
10
+ /**
11
+ * Per-assignment load discount each fairness preset applies, as a ratio of
12
+ * the median candidate score of the matching pass. A discount of X is itself
13
+ * a smooth tie-band: a user loses a contested assignment to a rival carrying
14
+ * one assignment less exactly when the score gap is under X.
15
+ */
16
+ const PRESET_LOAD_PENALTY_RATIO = {
17
+ balanced: 0.05,
18
+ 'spread-work': 0.5,
19
+ };
20
+ /**
21
+ * Turns a fairness preset into concrete arbitration knobs, scaled to the
22
+ * median candidate score of the current matching pass so consumers never
23
+ * have to know their own score scale. Explicitly-set expert knobs
24
+ * (fairnessLoadPenalty / fairnessTieBand > 0) always win over the preset.
25
+ */
26
+ function resolveFairnessKnobs(mode, pairPriorities, explicit) {
27
+ let { loadPenalty, tieBand } = explicit;
28
+ const ratio = mode ? PRESET_LOAD_PENALTY_RATIO[mode] : undefined;
29
+ if (ratio && loadPenalty <= 0 && pairPriorities.length > 0) {
30
+ const sorted = [...pairPriorities].sort((a, b) => a - b);
31
+ const mid = sorted.length >> 1;
32
+ const median = sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
33
+ if (median > 0)
34
+ loadPenalty = median * ratio;
35
+ }
36
+ return { loadPenalty, tieBand };
37
+ }
38
+ exports.resolveFairnessKnobs = resolveFairnessKnobs;
39
+ /**
40
+ * Walks the candidate pairs in best-first order and awards each assignment to
41
+ * exactly one user, honoring per-user backlog caps. Mutates `backlogUsed`
42
+ * (one increment per awarded pair). `settled` marks assignments no longer
43
+ * available at all (already claimed, or lost to a concurrent process).
44
+ *
45
+ * Returns `winners` in award order and `deferred`: pairs skipped only because
46
+ * their user was at cap - a cap that the caller may roll back if the user
47
+ * loses a claim to a concurrent process, so these stay eligible for another
48
+ * arbitration round.
49
+ *
50
+ * With neither knob set the order is a plain stable sort by score descending,
51
+ * matching the pre-fairness-knob behavior exactly. With a knob set, ordering
52
+ * is load-aware and therefore dynamic - each award changes the winner's load,
53
+ * which can demote their remaining candidates - so a lazy max-heap re-ranks
54
+ * entries whose user's load has grown since they were pushed.
55
+ */
56
+ function arbitrateFair(pairs, backlogUsed, settled, options) {
57
+ const loadPenalty = options.loadPenalty ?? 0;
58
+ const tieBand = options.tieBand ?? 0;
59
+ const winners = [];
60
+ const deferred = [];
61
+ const taken = new Set();
62
+ const load = (userId) => backlogUsed.get(userId) ?? 0;
63
+ const capOf = (userId) => options.maxByUser?.get(userId) ?? options.maxUserBacklogSize;
64
+ const award = (pair) => {
65
+ // Assignments already taken this pass are settled either way by the
66
+ // caller (a failed claim means a concurrent process owns it), so
67
+ // lower-ranked pairs for them never need re-arbitration.
68
+ if (settled.has(pair.id) || taken.has(pair.id))
69
+ return;
70
+ const used = load(pair.userId);
71
+ if (used >= capOf(pair.userId)) {
72
+ deferred.push(pair);
73
+ return;
74
+ }
75
+ taken.add(pair.id);
76
+ backlogUsed.set(pair.userId, used + 1);
77
+ winners.push(pair);
78
+ };
79
+ if (loadPenalty <= 0 && tieBand <= 0) {
80
+ for (const pair of [...pairs].sort((a, b) => b.priority - a.priority)) {
81
+ award(pair);
82
+ }
83
+ return { winners, deferred };
84
+ }
85
+ const effective = (pair) => pair.priority - loadPenalty * load(pair.userId);
86
+ const rank = (pair) => (tieBand > 0 ? Math.floor(effective(pair) / tieBand) : effective(pair));
87
+ // True when a orders strictly before b: higher rank bucket, then lower
88
+ // load, then higher raw score, then ids for full determinism.
89
+ const before = (a, b) => {
90
+ if (a.rank !== b.rank)
91
+ return a.rank > b.rank;
92
+ if (a.loadAtEval !== b.loadAtEval)
93
+ return a.loadAtEval < b.loadAtEval;
94
+ if (a.pair.priority !== b.pair.priority)
95
+ return a.pair.priority > b.pair.priority;
96
+ if (a.pair.id !== b.pair.id)
97
+ return a.pair.id < b.pair.id;
98
+ return a.pair.userId < b.pair.userId;
99
+ };
100
+ const heap = [];
101
+ const push = (pair) => {
102
+ heap.push({ pair, rank: rank(pair), loadAtEval: load(pair.userId) });
103
+ let i = heap.length - 1;
104
+ while (i > 0) {
105
+ const parent = (i - 1) >> 1;
106
+ if (!before(heap[i], heap[parent]))
107
+ break;
108
+ [heap[i], heap[parent]] = [heap[parent], heap[i]];
109
+ i = parent;
110
+ }
111
+ };
112
+ const pop = () => {
113
+ const top = heap[0];
114
+ const last = heap.pop();
115
+ if (heap.length > 0) {
116
+ heap[0] = last;
117
+ let i = 0;
118
+ for (;;) {
119
+ const left = i * 2 + 1;
120
+ const right = left + 1;
121
+ let best = i;
122
+ if (left < heap.length && before(heap[left], heap[best]))
123
+ best = left;
124
+ if (right < heap.length && before(heap[right], heap[best]))
125
+ best = right;
126
+ if (best === i)
127
+ break;
128
+ [heap[i], heap[best]] = [heap[best], heap[i]];
129
+ i = best;
130
+ }
131
+ }
132
+ return top;
133
+ };
134
+ for (const pair of pairs)
135
+ push(pair);
136
+ while (heap.length > 0) {
137
+ const entry = pop();
138
+ if (settled.has(entry.pair.id) || taken.has(entry.pair.id))
139
+ continue;
140
+ // Lazy re-rank: a user's load only grows during this pass (one per
141
+ // award), which can only demote their remaining entries. Terminates
142
+ // because load is capped at maxUserBacklogSize.
143
+ if (load(entry.pair.userId) !== entry.loadAtEval) {
144
+ push(entry.pair);
145
+ continue;
146
+ }
147
+ award(entry.pair);
148
+ }
149
+ return { winners, deferred };
150
+ }
151
+ exports.arbitrateFair = arbitrateFair;
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Scoring and matching utilities
3
3
  */
4
- import type { User } from '../matcher.class';
4
+ import type { User, MatchTraceReason } from '../types/matcher';
5
5
  /**
6
6
  * Check if a pattern matches a tag (supports wildcard patterns ending with *)
7
7
  */
@@ -21,6 +21,22 @@ export declare function meetsSkillThresholds(routingWeights: Record<string, numb
21
21
  * Returns [score, combinedPriority]
22
22
  */
23
23
  export declare function calculateMatchScore(user: User, assignmentTags: string, assignmentPriority: string | number, enableDefaultMatching: boolean, skillThresholds?: Record<string, number>): [number, number];
24
+ /** Result of `explainMatchScore`: the `calculateMatchScore` pair plus the reasons behind it. */
25
+ export interface MatchScoreExplanation {
26
+ score: number;
27
+ combinedPriority: number;
28
+ reasons: MatchTraceReason[];
29
+ }
30
+ /**
31
+ * Explaining twin of `calculateMatchScore`: same inputs, same score and
32
+ * combined priority (asserted by the parity test in
33
+ * tests/matcher_decision_traces.test.ts), plus the structured reasons behind
34
+ * the number — matched weights, vetoes, threshold failures, tag overlap.
35
+ * Kept separate from `calculateMatchScore` so the hot scoring path never pays
36
+ * for reason allocation; any change to one function must be mirrored in the
37
+ * other.
38
+ */
39
+ export declare function explainMatchScore(user: User, assignmentTags: string, assignmentPriority: string | number, enableDefaultMatching: boolean, skillThresholds?: Record<string, number>): MatchScoreExplanation;
24
40
  /**
25
41
  * Calculate default priority based on creation time
26
42
  * Note: Returns 0 if createdAt is undefined to match original behavior
@@ -1 +1 @@
1
- {"version":3,"file":"match-score.d.ts","sourceRoot":"","sources":["../../src/scoring/match-score.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAE7C;;GAEG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAOpE;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAY9F;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAChC,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,EAClD,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,GACpD,OAAO,CAeT;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAC/B,IAAI,EAAE,IAAI,EACV,cAAc,EAAE,MAAM,EACtB,kBAAkB,EAAE,MAAM,GAAG,MAAM,EACnC,qBAAqB,EAAE,OAAO,EAC9B,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACzC,CAAC,MAAM,EAAE,MAAM,CAAC,CAoElB;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,CAGnE"}
1
+ {"version":3,"file":"match-score.d.ts","sourceRoot":"","sources":["../../src/scoring/match-score.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,IAAI,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAE/D;;GAEG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAOpE;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAY9F;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAChC,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,EAClD,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,GACpD,OAAO,CAeT;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAC/B,IAAI,EAAE,IAAI,EACV,cAAc,EAAE,MAAM,EACtB,kBAAkB,EAAE,MAAM,GAAG,MAAM,EACnC,qBAAqB,EAAE,OAAO,EAC9B,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACzC,CAAC,MAAM,EAAE,MAAM,CAAC,CAoElB;AAED,gGAAgG;AAChG,MAAM,WAAW,qBAAqB;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,EAAE,MAAM,CAAC;IACzB,OAAO,EAAE,gBAAgB,EAAE,CAAC;CAC/B;AAED;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAC7B,IAAI,EAAE,IAAI,EACV,cAAc,EAAE,MAAM,EACtB,kBAAkB,EAAE,MAAM,GAAG,MAAM,EACnC,qBAAqB,EAAE,OAAO,EAC9B,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACzC,qBAAqB,CAyEvB;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,CAGnE"}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.calculateDefaultPriority = exports.calculateMatchScore = exports.meetsSkillThresholds = exports.getEffectiveWeight = exports.matchesPattern = void 0;
3
+ exports.calculateDefaultPriority = exports.explainMatchScore = exports.calculateMatchScore = exports.meetsSkillThresholds = exports.getEffectiveWeight = exports.matchesPattern = void 0;
4
4
  /**
5
5
  * Check if a pattern matches a tag (supports wildcard patterns ending with *)
6
6
  */
@@ -119,6 +119,86 @@ function calculateMatchScore(user, assignmentTags, assignmentPriority, enableDef
119
119
  return [score || 0, base + (score || 0)];
120
120
  }
121
121
  exports.calculateMatchScore = calculateMatchScore;
122
+ /**
123
+ * Explaining twin of `calculateMatchScore`: same inputs, same score and
124
+ * combined priority (asserted by the parity test in
125
+ * tests/matcher_decision_traces.test.ts), plus the structured reasons behind
126
+ * the number — matched weights, vetoes, threshold failures, tag overlap.
127
+ * Kept separate from `calculateMatchScore` so the hot scoring path never pays
128
+ * for reason allocation; any change to one function must be mirrored in the
129
+ * other.
130
+ */
131
+ function explainMatchScore(user, assignmentTags, assignmentPriority, enableDefaultMatching, skillThresholds) {
132
+ const aTags = assignmentTags ? assignmentTags.split(',') : [];
133
+ const base = Number(assignmentPriority) || 0;
134
+ const reasons = [];
135
+ if (user.routingWeights && Object.keys(user.routingWeights).length > 0) {
136
+ if (!meetsSkillThresholds(user.routingWeights, skillThresholds)) {
137
+ for (const [skill, required] of Object.entries(skillThresholds ?? {})) {
138
+ const actual = getEffectiveWeight(user.routingWeights, skill);
139
+ if (actual < required)
140
+ reasons.push({ kind: 'skillThreshold', skill, required, actual });
141
+ }
142
+ return { score: 0, combinedPriority: base, reasons };
143
+ }
144
+ // calculateMatchScore short-circuits on the first veto; collecting all
145
+ // of them here changes nothing about the outcome (score 0 either way)
146
+ // and gives the trace every rule that fired.
147
+ let vetoed = false;
148
+ for (const [pattern, weight] of Object.entries(user.routingWeights)) {
149
+ if (weight === 0) {
150
+ for (const t of aTags) {
151
+ if (matchesPattern(pattern, t)) {
152
+ reasons.push({ kind: 'veto', tag: t, pattern });
153
+ vetoed = true;
154
+ }
155
+ }
156
+ }
157
+ }
158
+ if (vetoed)
159
+ return { score: 0, combinedPriority: base, reasons };
160
+ let weightSum = 0;
161
+ for (const t of aTags) {
162
+ let matchedByRouting = false;
163
+ for (const [pattern, weight] of Object.entries(user.routingWeights)) {
164
+ if (typeof weight === 'number' && weight > 0 && matchesPattern(pattern, t)) {
165
+ weightSum += weight;
166
+ matchedByRouting = true;
167
+ reasons.push(pattern === t
168
+ ? { kind: 'tagWeight', tag: t, weight }
169
+ : { kind: 'tagWeight', tag: t, weight, pattern });
170
+ }
171
+ }
172
+ if (enableDefaultMatching && t === 'default' && !matchedByRouting) {
173
+ weightSum += 1;
174
+ reasons.push({ kind: 'defaultTag', weight: 1 });
175
+ }
176
+ }
177
+ return { score: weightSum, combinedPriority: base + weightSum, reasons };
178
+ }
179
+ if (skillThresholds && Object.keys(skillThresholds).length > 0) {
180
+ for (const [skill, required] of Object.entries(skillThresholds)) {
181
+ reasons.push({ kind: 'skillThreshold', skill, required, actual: 0 });
182
+ }
183
+ return { score: 0, combinedPriority: base, reasons };
184
+ }
185
+ const userTagSet = new Set(user.tags);
186
+ const assignmentTagSet = new Set(aTags);
187
+ const matchedTags = [];
188
+ for (const userTag of userTagSet) {
189
+ for (const assignmentTag of assignmentTagSet) {
190
+ if (matchesPattern(userTag, assignmentTag)) {
191
+ matchedTags.push(userTag);
192
+ break;
193
+ }
194
+ }
195
+ }
196
+ const score = userTagSet.size > 0 ? matchedTags.length / userTagSet.size : 0;
197
+ if (score > 0)
198
+ reasons.push({ kind: 'tagOverlap', matchedTags, overlapRatio: score });
199
+ return { score: score || 0, combinedPriority: base + (score || 0), reasons };
200
+ }
201
+ exports.explainMatchScore = explainMatchScore;
122
202
  /**
123
203
  * Calculate default priority based on creation time
124
204
  * Note: Returns 0 if createdAt is undefined to match original behavior
@@ -0,0 +1,48 @@
1
+ import type { MatchCandidateTrace, MatchDecisionMode, MatchDecisionTrace, MatchTraceReason, User } from '../types/matcher';
2
+ /** One user's evaluation of one assignment, captured during a matching pass. */
3
+ export interface TraceEvaluation {
4
+ userId: string;
5
+ eligible: boolean;
6
+ score: number;
7
+ effectivePriority: number;
8
+ reasons: MatchTraceReason[];
9
+ }
10
+ /** Per-pass accumulator of candidate evaluations, keyed by assignment. */
11
+ export declare class TraceCollector {
12
+ readonly byAssignment: Map<string, {
13
+ tags: string;
14
+ evaluations: TraceEvaluation[];
15
+ }>;
16
+ record(assignmentId: string, tags: string, evaluation: TraceEvaluation): void;
17
+ }
18
+ /** A pass participant plus the Redis-side exclusion sets used for enrichment. */
19
+ export interface TraceUserContext {
20
+ user: User;
21
+ /** Assignment ids this user previously rejected */
22
+ rejected: Set<string>;
23
+ /** Assignment ids this user is hard-vetoed from (assignment.vetoedUsers) */
24
+ vetoed: Set<string>;
25
+ /** Whether the user was paused during the pass (excluded from all matching) */
26
+ paused?: boolean;
27
+ }
28
+ /** Chosen candidate first, then eligible before ineligible, then by effective priority. */
29
+ export declare function sortCandidates(candidates: MatchCandidateTrace[]): MatchCandidateTrace[];
30
+ /**
31
+ * Pivot a pass's evaluations into one decision trace per won assignment.
32
+ * `winners` maps assignmentId -> the user whose claim succeeded.
33
+ */
34
+ export declare function buildDecisionTraces(params: {
35
+ collector: TraceCollector;
36
+ winners: Map<string, string>;
37
+ mode: MatchDecisionMode;
38
+ users: TraceUserContext[];
39
+ maxCandidates: number;
40
+ matchedAt: number;
41
+ }): MatchDecisionTrace[];
42
+ /** Traces for deterministic workflow-targeted handoffs (no arbitration to show). */
43
+ export declare function buildWorkflowTraces(grants: Array<{
44
+ assignmentId: string;
45
+ userId: string;
46
+ priority: number;
47
+ }>, matchedAt: number): MatchDecisionTrace[];
48
+ //# sourceMappingURL=decision-trace.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decision-trace.d.ts","sourceRoot":"","sources":["../../src/tracing/decision-trace.ts"],"names":[],"mappings":"AAoBA,OAAO,KAAK,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAE3H,gFAAgF;AAChF,MAAM,WAAW,eAAe;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,OAAO,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,iBAAiB,EAAE,MAAM,CAAC;IAC1B,OAAO,EAAE,gBAAgB,EAAE,CAAC;CAC/B;AAED,0EAA0E;AAC1E,qBAAa,cAAc;IACvB,QAAQ,CAAC,YAAY;cAA2B,MAAM;qBAAe,eAAe,EAAE;OAAM;IAE5F,MAAM,CAAC,YAAY,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,eAAe,GAAG,IAAI;CAQhF;AAED,iFAAiF;AACjF,MAAM,WAAW,gBAAgB;IAC7B,IAAI,EAAE,IAAI,CAAC;IACX,mDAAmD;IACnD,QAAQ,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACtB,4EAA4E;IAC5E,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACpB,+EAA+E;IAC/E,MAAM,CAAC,EAAE,OAAO,CAAC;CACpB;AAED,2FAA2F;AAC3F,wBAAgB,cAAc,CAAC,UAAU,EAAE,mBAAmB,EAAE,GAAG,mBAAmB,EAAE,CAMvF;AA0BD;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE;IACxC,SAAS,EAAE,cAAc,CAAC;IAC1B,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,IAAI,EAAE,iBAAiB,CAAC;IACxB,KAAK,EAAE,gBAAgB,EAAE,CAAC;IAC1B,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,MAAM,CAAC;CACrB,GAAG,kBAAkB,EAAE,CAgDvB;AAED,oFAAoF;AACpF,wBAAgB,mBAAmB,CAC/B,MAAM,EAAE,KAAK,CAAC;IAAE,YAAY,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC,EACzE,SAAS,EAAE,MAAM,GAClB,kBAAkB,EAAE,CAkBtB"}
@@ -0,0 +1,152 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildWorkflowTraces = exports.buildDecisionTraces = exports.sortCandidates = exports.TraceCollector = void 0;
4
+ /**
5
+ * Pure decision-trace assembly.
6
+ *
7
+ * A matching pass evaluates users -> assignments; a decision trace is the
8
+ * inverse view: one matched assignment -> every candidate considered for it.
9
+ * The collector accumulates per-(assignment, user) evaluations as they happen
10
+ * inside candidate scoring, and buildDecisionTraces() pivots them into
11
+ * per-assignment records once the pass's winners are known.
12
+ *
13
+ * Candidate discovery is Redis-first: users excluded by the per-tag zset diff
14
+ * (zero-weight vetoes, prior rejections, assignment-level user vetoes) never
15
+ * reach scoring, so they produce no evaluations. Because those are exactly the
16
+ * exclusions an auditor asks about, buildDecisionTraces() re-derives them
17
+ * in memory from the pass's user contexts and adds them as struck-out
18
+ * candidates. Users absent for any other reason (no positive tag overlap, or
19
+ * the assignment was claimed before their snapshot read) were never candidates
20
+ * and are not synthesized.
21
+ */
22
+ const crypto_1 = require("crypto");
23
+ const match_score_1 = require("../scoring/match-score");
24
+ /** Per-pass accumulator of candidate evaluations, keyed by assignment. */
25
+ class TraceCollector {
26
+ constructor() {
27
+ this.byAssignment = new Map();
28
+ }
29
+ record(assignmentId, tags, evaluation) {
30
+ let entry = this.byAssignment.get(assignmentId);
31
+ if (!entry) {
32
+ entry = { tags, evaluations: [] };
33
+ this.byAssignment.set(assignmentId, entry);
34
+ }
35
+ entry.evaluations.push(evaluation);
36
+ }
37
+ }
38
+ exports.TraceCollector = TraceCollector;
39
+ /** Chosen candidate first, then eligible before ineligible, then by effective priority. */
40
+ function sortCandidates(candidates) {
41
+ return candidates.sort((a, b) => {
42
+ if (a.chosen !== b.chosen)
43
+ return a.chosen ? -1 : 1;
44
+ if (a.eligible !== b.eligible)
45
+ return a.eligible ? -1 : 1;
46
+ return b.effectivePriority - a.effectivePriority;
47
+ });
48
+ }
49
+ exports.sortCandidates = sortCandidates;
50
+ /**
51
+ * Hard-rule exclusion reasons for a user the Redis prefilter kept out of
52
+ * scoring entirely. Returns null when no exclusion rule applies (the user
53
+ * simply was not a candidate).
54
+ */
55
+ function excludedCandidate(ctx, assignmentId, tags) {
56
+ const reasons = [];
57
+ if (ctx.paused)
58
+ reasons.push({ kind: 'paused' });
59
+ if (ctx.vetoed.has(assignmentId))
60
+ reasons.push({ kind: 'assignmentVeto' });
61
+ if (ctx.rejected.has(assignmentId))
62
+ reasons.push({ kind: 'rejectedPreviously' });
63
+ const weights = ctx.user.routingWeights;
64
+ if (weights) {
65
+ for (const [pattern, weight] of Object.entries(weights)) {
66
+ if (weight === 0) {
67
+ for (const tag of tags) {
68
+ if ((0, match_score_1.matchesPattern)(pattern, tag))
69
+ reasons.push({ kind: 'veto', tag, pattern });
70
+ }
71
+ }
72
+ }
73
+ }
74
+ if (reasons.length === 0)
75
+ return null;
76
+ return { userId: ctx.user.id, eligible: false, chosen: false, score: 0, effectivePriority: 0, reasons };
77
+ }
78
+ /**
79
+ * Pivot a pass's evaluations into one decision trace per won assignment.
80
+ * `winners` maps assignmentId -> the user whose claim succeeded.
81
+ */
82
+ function buildDecisionTraces(params) {
83
+ const traces = [];
84
+ for (const [assignmentId, chosenUserId] of params.winners) {
85
+ const entry = params.collector.byAssignment.get(assignmentId);
86
+ const tags = entry ? entry.tags.split(',').filter(Boolean) : [];
87
+ const evaluated = new Set();
88
+ const candidates = [];
89
+ for (const e of entry?.evaluations ?? []) {
90
+ evaluated.add(e.userId);
91
+ candidates.push({
92
+ userId: e.userId,
93
+ eligible: e.eligible,
94
+ chosen: e.userId === chosenUserId,
95
+ score: e.score,
96
+ effectivePriority: e.effectivePriority,
97
+ reasons: e.reasons,
98
+ });
99
+ }
100
+ for (const ctx of params.users) {
101
+ if (evaluated.has(ctx.user.id))
102
+ continue;
103
+ const excluded = excludedCandidate(ctx, assignmentId, tags);
104
+ if (excluded)
105
+ candidates.push(excluded);
106
+ }
107
+ // The winner always evaluated the assignment; keep the trace coherent
108
+ // even if capture and claiming ever disagree.
109
+ if (!candidates.some((c) => c.userId === chosenUserId)) {
110
+ candidates.push({
111
+ userId: chosenUserId,
112
+ eligible: true,
113
+ chosen: true,
114
+ score: 0,
115
+ effectivePriority: 0,
116
+ reasons: [],
117
+ });
118
+ }
119
+ sortCandidates(candidates);
120
+ traces.push({
121
+ id: (0, crypto_1.randomUUID)(),
122
+ assignmentId,
123
+ chosenUserId,
124
+ matchedAt: params.matchedAt,
125
+ mode: params.mode,
126
+ candidates: candidates.slice(0, Math.max(1, params.maxCandidates)),
127
+ });
128
+ }
129
+ return traces;
130
+ }
131
+ exports.buildDecisionTraces = buildDecisionTraces;
132
+ /** Traces for deterministic workflow-targeted handoffs (no arbitration to show). */
133
+ function buildWorkflowTraces(grants, matchedAt) {
134
+ return grants.map((grant) => ({
135
+ id: (0, crypto_1.randomUUID)(),
136
+ assignmentId: grant.assignmentId,
137
+ chosenUserId: grant.userId,
138
+ matchedAt,
139
+ mode: 'workflow',
140
+ candidates: [
141
+ {
142
+ userId: grant.userId,
143
+ eligible: true,
144
+ chosen: true,
145
+ score: 0,
146
+ effectivePriority: grant.priority,
147
+ reasons: [{ kind: 'workflowTargeted' }],
148
+ },
149
+ ],
150
+ }));
151
+ }
152
+ exports.buildWorkflowTraces = buildWorkflowTraces;