assignment-user-matcher 1.2.1 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +609 -5
  2. package/dist/index.d.ts +7 -3
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +13 -1
  5. package/dist/learning/auto-weights.d.ts +31 -0
  6. package/dist/learning/auto-weights.d.ts.map +1 -0
  7. package/dist/learning/auto-weights.js +65 -0
  8. package/dist/learning/features.d.ts +19 -0
  9. package/dist/learning/features.d.ts.map +1 -0
  10. package/dist/learning/features.js +55 -0
  11. package/dist/lua/workflow-transition.lua +29 -0
  12. package/dist/managers/LearningManager.d.ts +129 -0
  13. package/dist/managers/LearningManager.d.ts.map +1 -0
  14. package/dist/managers/LearningManager.js +269 -0
  15. package/dist/managers/ReliabilityManager.d.ts +60 -2
  16. package/dist/managers/ReliabilityManager.d.ts.map +1 -1
  17. package/dist/managers/ReliabilityManager.js +190 -9
  18. package/dist/managers/TelemetryManager.d.ts.map +1 -1
  19. package/dist/managers/WorkflowManager.d.ts +80 -6
  20. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  21. package/dist/managers/WorkflowManager.js +464 -81
  22. package/dist/matcher.class.d.ts +180 -13
  23. package/dist/matcher.class.d.ts.map +1 -1
  24. package/dist/matcher.class.js +632 -46
  25. package/dist/queries/pagination.d.ts.map +1 -1
  26. package/dist/queries/pagination.js +9 -6
  27. package/dist/scoring/match-score.d.ts.map +1 -1
  28. package/dist/scoring/match-score.js +1 -1
  29. package/dist/types/matcher.d.ts +258 -9
  30. package/dist/types/matcher.d.ts.map +1 -1
  31. package/dist/utils/geo.d.ts +26 -0
  32. package/dist/utils/geo.d.ts.map +1 -0
  33. package/dist/utils/geo.js +62 -0
  34. package/dist/utils/keys.d.ts +15 -0
  35. package/dist/utils/keys.d.ts.map +1 -1
  36. package/dist/utils/keys.js +17 -0
  37. package/dist/workflow-builder.d.ts +2 -4
  38. package/dist/workflow-builder.d.ts.map +1 -1
  39. package/dist/workflow-builder.js +4 -46
  40. package/dist/workflow-validation.d.ts +4 -0
  41. package/dist/workflow-validation.d.ts.map +1 -0
  42. package/dist/workflow-validation.js +85 -0
  43. package/package.json +4 -2
package/dist/index.js CHANGED
@@ -17,9 +17,17 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
17
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.AssignmentMatcher = exports.createKeyBuilders = exports.approvalWorkflow = exports.linearWorkflow = exports.workflow = exports.WorkflowStepBuilder = exports.WorkflowBuilder = void 0;
20
+ exports.AssignmentMatcher = exports.createKeyBuilders = exports.validateWorkflowDefinition = exports.normalizeWorkflowDefinition = exports.approvalWorkflow = exports.linearWorkflow = exports.workflow = exports.WorkflowStepBuilder = exports.WorkflowBuilder = exports.DEFAULT_AUTO_WEIGHTS_OPTIONS = exports.synthesizeRoutingWeights = exports.cosineSimilarity = exports.extractMatchFeatures = void 0;
21
21
  const matcher_class_1 = __importDefault(require("./matcher.class"));
22
22
  exports.AssignmentMatcher = matcher_class_1.default;
23
+ // Learning feature helpers (for custom feature extractors)
24
+ var features_1 = require("./learning/features");
25
+ Object.defineProperty(exports, "extractMatchFeatures", { enumerable: true, get: function () { return features_1.extractMatchFeatures; } });
26
+ Object.defineProperty(exports, "cosineSimilarity", { enumerable: true, get: function () { return features_1.cosineSimilarity; } });
27
+ // Automatic routing-weight synthesis (UCB1 policy over learned tag stats)
28
+ var auto_weights_1 = require("./learning/auto-weights");
29
+ Object.defineProperty(exports, "synthesizeRoutingWeights", { enumerable: true, get: function () { return auto_weights_1.synthesizeRoutingWeights; } });
30
+ Object.defineProperty(exports, "DEFAULT_AUTO_WEIGHTS_OPTIONS", { enumerable: true, get: function () { return auto_weights_1.DEFAULT_AUTO_WEIGHTS_OPTIONS; } });
23
31
  // Workflow builder DSL
24
32
  var workflow_builder_1 = require("./workflow-builder");
25
33
  Object.defineProperty(exports, "WorkflowBuilder", { enumerable: true, get: function () { return workflow_builder_1.WorkflowBuilder; } });
@@ -27,8 +35,12 @@ Object.defineProperty(exports, "WorkflowStepBuilder", { enumerable: true, get: f
27
35
  Object.defineProperty(exports, "workflow", { enumerable: true, get: function () { return workflow_builder_1.workflow; } });
28
36
  Object.defineProperty(exports, "linearWorkflow", { enumerable: true, get: function () { return workflow_builder_1.linearWorkflow; } });
29
37
  Object.defineProperty(exports, "approvalWorkflow", { enumerable: true, get: function () { return workflow_builder_1.approvalWorkflow; } });
38
+ var workflow_validation_1 = require("./workflow-validation");
39
+ Object.defineProperty(exports, "normalizeWorkflowDefinition", { enumerable: true, get: function () { return workflow_validation_1.normalizeWorkflowDefinition; } });
40
+ Object.defineProperty(exports, "validateWorkflowDefinition", { enumerable: true, get: function () { return workflow_validation_1.validateWorkflowDefinition; } });
30
41
  // Utility exports for advanced usage
31
42
  __exportStar(require("./utils/cidr"), exports);
43
+ __exportStar(require("./utils/geo"), exports);
32
44
  var keys_1 = require("./utils/keys");
33
45
  Object.defineProperty(exports, "createKeyBuilders", { enumerable: true, get: function () { return keys_1.createKeyBuilders; } });
34
46
  exports.default = matcher_class_1.default;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Automatic routing-weight synthesis from per-user tag reward statistics.
3
+ *
4
+ * Implements a UCB1-style bandit policy over tags: each tag's score is its
5
+ * mean observed reward plus an exploration bonus that shrinks as the tag is
6
+ * sampled more. Scores map onto the conventional 0-100 routing-weight scale:
7
+ *
8
+ * - tags with enough samples and a mean reward at/below `vetoThreshold` get
9
+ * weight 0 (the matcher's hard-veto semantics),
10
+ * - under-sampled or unobserved known tags get an optimistic `priorWeight`
11
+ * so the matcher keeps exploring them,
12
+ * - all other tags get a weight proportional to their UCB score, clamped to
13
+ * [1, maxWeight] so eligible tags never collapse to an accidental veto.
14
+ *
15
+ * Pure module: no Redis access, O(number of tags) per call.
16
+ */
17
+ import type { AutoRoutingWeightsOptions, LearningTagStat } from '../types/matcher';
18
+ export declare const DEFAULT_AUTO_WEIGHTS_OPTIONS: Required<Omit<AutoRoutingWeightsOptions, 'priorWeight'>>;
19
+ /**
20
+ * Synthesize a routingWeights map from per-tag reward statistics.
21
+ *
22
+ * @param stats per-user tag reward statistics (from learned outcomes)
23
+ * @param options UCB policy tuning (merged with defaults)
24
+ * @param knownTags optional tags to include even without observations;
25
+ * unobserved known tags receive the optimistic prior weight
26
+ * @param existingWeights optional current routingWeights of the user;
27
+ * used as the per-tag prior for under-sampled or unobserved
28
+ * tags instead of the flat `priorWeight` when provided
29
+ */
30
+ export declare function synthesizeRoutingWeights(stats: LearningTagStat[], options?: AutoRoutingWeightsOptions, knownTags?: string[], existingWeights?: Record<string, number>): Record<string, number>;
31
+ //# sourceMappingURL=auto-weights.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auto-weights.d.ts","sourceRoot":"","sources":["../../src/learning/auto-weights.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,KAAK,EAAE,yBAAyB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAEnF,eAAO,MAAM,4BAA4B,EAAE,QAAQ,CAAC,IAAI,CAAC,yBAAyB,EAAE,aAAa,CAAC,CAKjG,CAAC;AAEF;;;;;;;;;;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,CA8CxB"}
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.synthesizeRoutingWeights = exports.DEFAULT_AUTO_WEIGHTS_OPTIONS = void 0;
4
+ exports.DEFAULT_AUTO_WEIGHTS_OPTIONS = {
5
+ minSamples: 5,
6
+ vetoThreshold: -0.5,
7
+ maxWeight: 100,
8
+ explorationBonus: 0.5,
9
+ };
10
+ /**
11
+ * Synthesize a routingWeights map from per-tag reward statistics.
12
+ *
13
+ * @param stats per-user tag reward statistics (from learned outcomes)
14
+ * @param options UCB policy tuning (merged with defaults)
15
+ * @param knownTags optional tags to include even without observations;
16
+ * unobserved known tags receive the optimistic prior weight
17
+ * @param existingWeights optional current routingWeights of the user;
18
+ * used as the per-tag prior for under-sampled or unobserved
19
+ * tags instead of the flat `priorWeight` when provided
20
+ */
21
+ function synthesizeRoutingWeights(stats, options, knownTags, existingWeights) {
22
+ const minSamples = options?.minSamples ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.minSamples;
23
+ const vetoThreshold = options?.vetoThreshold ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.vetoThreshold;
24
+ const maxWeight = options?.maxWeight ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.maxWeight;
25
+ const explorationBonus = options?.explorationBonus ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.explorationBonus;
26
+ const priorWeight = options?.priorWeight ?? Math.round(maxWeight / 2);
27
+ const weights = {};
28
+ const totalCount = stats.reduce((sum, s) => sum + s.count, 0);
29
+ for (const stat of stats) {
30
+ if (stat.count < minSamples) {
31
+ // Not enough evidence yet: use the existing weight as a warm
32
+ // prior if available, otherwise fall back to the flat prior.
33
+ weights[stat.tag] = existingWeights?.[stat.tag] ?? priorWeight;
34
+ continue;
35
+ }
36
+ // UCB1 score: mean reward + exploration bonus for under-sampled tags.
37
+ const ucb = stat.meanReward + explorationBonus * Math.sqrt(Math.log(totalCount + 1) / stat.count);
38
+ if (stat.meanReward <= vetoThreshold) {
39
+ // Consistently bad on the evidence: hard veto (matcher treats
40
+ // weight 0 as exclusion). The veto uses the raw mean so the
41
+ // exploration bonus cannot keep a provably bad tag alive.
42
+ weights[stat.tag] = 0;
43
+ continue;
44
+ }
45
+ // Map score (clamped to [-1, 1]) onto [1, maxWeight].
46
+ const normalized = (Math.min(Math.max(ucb, -1), 1) + 1) / 2;
47
+ weights[stat.tag] = Math.max(1, Math.round(normalized * maxWeight));
48
+ }
49
+ if (knownTags) {
50
+ for (const tag of knownTags) {
51
+ if (!(tag in weights))
52
+ weights[tag] = existingWeights?.[tag] ?? priorWeight;
53
+ }
54
+ }
55
+ // Tags the user already had weights for are treated as implicitly known:
56
+ // keep the existing value until sufficient evidence overrides it.
57
+ if (existingWeights) {
58
+ for (const [tag, existing] of Object.entries(existingWeights)) {
59
+ if (!(tag in weights))
60
+ weights[tag] = existing;
61
+ }
62
+ }
63
+ return weights;
64
+ }
65
+ exports.synthesizeRoutingWeights = synthesizeRoutingWeights;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Default feature extraction for the learning (contextual bandit) layer.
3
+ *
4
+ * Produces a sparse feature vector describing how well a user matches an
5
+ * assignment. All features are normalized to roughly [0, 1] so learned
6
+ * weights stay comparable across feature families.
7
+ */
8
+ import type { User, LearningFeatures, LearningAssignmentContext } from '../types/matcher';
9
+ /**
10
+ * Cosine similarity between two numeric vectors.
11
+ * Returns 0 for mismatched lengths or zero-magnitude vectors.
12
+ */
13
+ export declare function cosineSimilarity(a: number[], b: number[]): number;
14
+ /**
15
+ * Default feature extractor: tag matches, normalized skill weights,
16
+ * tag-overlap ratio, and optional embedding similarity.
17
+ */
18
+ export declare function extractMatchFeatures(user: User, assignment: LearningAssignmentContext): LearningFeatures;
19
+ //# sourceMappingURL=features.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"features.d.ts","sourceRoot":"","sources":["../../src/learning/features.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,IAAI,EAAE,gBAAgB,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AAG1F;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,CAYjE;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,IAAI,EAAE,UAAU,EAAE,yBAAyB,GAAG,gBAAgB,CA6BxG"}
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.extractMatchFeatures = exports.cosineSimilarity = void 0;
4
+ const match_score_1 = require("../scoring/match-score");
5
+ /**
6
+ * Cosine similarity between two numeric vectors.
7
+ * Returns 0 for mismatched lengths or zero-magnitude vectors.
8
+ */
9
+ function cosineSimilarity(a, b) {
10
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length === 0 || a.length !== b.length)
11
+ return 0;
12
+ let dot = 0;
13
+ let normA = 0;
14
+ let normB = 0;
15
+ for (let i = 0; i < a.length; i++) {
16
+ dot += a[i] * b[i];
17
+ normA += a[i] * a[i];
18
+ normB += b[i] * b[i];
19
+ }
20
+ if (normA === 0 || normB === 0)
21
+ return 0;
22
+ return dot / (Math.sqrt(normA) * Math.sqrt(normB));
23
+ }
24
+ exports.cosineSimilarity = cosineSimilarity;
25
+ /**
26
+ * Default feature extractor: tag matches, normalized skill weights,
27
+ * tag-overlap ratio, and optional embedding similarity.
28
+ */
29
+ function extractMatchFeatures(user, assignment) {
30
+ const features = { bias: 1 };
31
+ const userTags = new Set(user.tags || []);
32
+ const assignmentTags = assignment.tags || [];
33
+ let overlapCount = 0;
34
+ for (const tag of assignmentTags) {
35
+ if (userTags.has(tag)) {
36
+ features[`tag:${tag}`] = 1;
37
+ overlapCount++;
38
+ }
39
+ if (user.routingWeights && Object.keys(user.routingWeights).length > 0) {
40
+ const weight = (0, match_score_1.getEffectiveWeight)(user.routingWeights, tag);
41
+ if (weight > 0) {
42
+ // Normalize assuming the conventional 0-100 weight scale, capped at 1.
43
+ features[`skill:${tag}`] = Math.min(weight / 100, 1);
44
+ }
45
+ }
46
+ }
47
+ if (assignmentTags.length > 0) {
48
+ features.overlap = overlapCount / assignmentTags.length;
49
+ }
50
+ if (Array.isArray(user.embedding) && Array.isArray(assignment.embedding)) {
51
+ features['emb:sim'] = cosineSimilarity(user.embedding, assignment.embedding);
52
+ }
53
+ return features;
54
+ }
55
+ exports.extractMatchFeatures = extractMatchFeatures;
@@ -0,0 +1,29 @@
1
+ -- workflow-transition.lua
2
+ -- Atomic workflow state transition with optimistic locking (CAS)
3
+ --
4
+ -- KEYS[1] = workflow instance key
5
+ -- ARGV[1] = expected version
6
+ -- ARGV[2] = new data (JSON string)
7
+ --
8
+ -- Returns:
9
+ -- {ok = true} on success
10
+ -- {err = 'NOT_FOUND'} if instance doesn't exist
11
+ -- {err = 'VERSION_MISMATCH', current_version = N} if version doesn't match
12
+
13
+ local key = KEYS[1]
14
+ local expected_version = tonumber(ARGV[1])
15
+ local new_data = ARGV[2]
16
+
17
+ local current = redis.call('HGET', key, 'data')
18
+ if not current then
19
+ return cjson.encode({err = 'NOT_FOUND'})
20
+ end
21
+
22
+ local parsed = cjson.decode(current)
23
+ if parsed.version ~= expected_version then
24
+ return cjson.encode({err = 'VERSION_MISMATCH', current_version = parsed.version})
25
+ end
26
+
27
+ redis.call('HSET', key, 'data', new_data)
28
+ return cjson.encode({ok = true})
29
+
@@ -0,0 +1,129 @@
1
+ /**
2
+ * LearningManager - Redis-backed contextual bandit for adaptive matchmaking.
3
+ *
4
+ * Maintains an online linear reward model: each feature has a learned weight
5
+ * stored in a Redis hash. Predictions are dot products of the feature vector
6
+ * with the learned weights; updates use stochastic gradient descent on the
7
+ * observed reward for each assignment outcome.
8
+ *
9
+ * The model only re-ranks candidates that already passed the hard matching
10
+ * rules (tags/weights, CIDR, skill thresholds) - it never makes an ineligible
11
+ * assignment eligible.
12
+ */
13
+ import type { RedisClientType, LearningFeatures, LearningOutcome, LearningRewards, LearningDecisionRecord, LearningEpisodeRecord, LearningSignals, LearningSample, LearningStats, LearningTagStat, AutoRoutingWeightsOptions } from '../types/matcher';
14
+ import type { KeyBuilders } from '../utils/keys';
15
+ export declare const DEFAULT_LEARNING_REWARDS: LearningRewards;
16
+ export interface LearningManagerOptions {
17
+ /** SGD learning rate (default: 0.1) */
18
+ learningRate?: number;
19
+ /** Epsilon-greedy exploration rate (default: 0.05) */
20
+ explorationRate?: number;
21
+ /** Shadow mode: learn and record but never alter ranking (default: false) */
22
+ shadowMode?: boolean;
23
+ /** Multiplier applied to predicted reward when re-ranking (default: 1) */
24
+ boostFactor?: number;
25
+ /** Reward overrides merged with defaults */
26
+ rewards?: Partial<LearningRewards>;
27
+ /** TTL for stored decision contexts in ms (default: 7 days) */
28
+ decisionTtlMs?: number;
29
+ /** Weights applied to named external feedback signals (default weight: 1) */
30
+ signalWeights?: Record<string, number>;
31
+ /** TTL for archived episodes awaiting external feedback in ms (default: 7 days) */
32
+ feedbackTtlMs?: number;
33
+ /** Track per-user, per-tag reward stats for automatic routing weights (default: false) */
34
+ trackTagStats?: boolean;
35
+ /** Tuning for automatic routing-weight synthesis */
36
+ autoWeights?: AutoRoutingWeightsOptions;
37
+ }
38
+ export declare class LearningManager {
39
+ private redisClient;
40
+ private keys;
41
+ readonly learningRate: number;
42
+ readonly explorationRate: number;
43
+ private _shadowMode;
44
+ readonly boostFactor: number;
45
+ readonly rewards: LearningRewards;
46
+ readonly decisionTtlMs: number;
47
+ readonly signalWeights: Record<string, number>;
48
+ readonly feedbackTtlMs: number;
49
+ readonly trackTagStats: boolean;
50
+ readonly autoWeights: AutoRoutingWeightsOptions;
51
+ constructor(redisClient: RedisClientType, keys: KeyBuilders, options?: LearningManagerOptions);
52
+ /** Load the full model weights hash from Redis */
53
+ getModel(): Promise<Record<string, string>>;
54
+ /** Predict expected reward for a feature vector against given model weights */
55
+ predict(features: LearningFeatures, weights: Record<string, string | number>): number;
56
+ /** Epsilon-greedy exploration check */
57
+ shouldExplore(): boolean;
58
+ /** Current shadow mode state (true: learn-only, false: affects ranking) */
59
+ get shadowMode(): boolean;
60
+ /**
61
+ * Toggle shadow mode at runtime without resetting model/state.
62
+ *
63
+ * When enabled, the matcher still records decisions and learns rewards,
64
+ * but predicted rewards do not influence ranking.
65
+ */
66
+ setShadowMode(enabled: boolean): void;
67
+ /**
68
+ * Persist the decision context for an assignment so the eventual outcome
69
+ * can be attributed back to the features that drove the match.
70
+ */
71
+ recordDecision(userId: string, assignmentId: string, features: LearningFeatures, predictedReward: number, tags?: string[]): Promise<void>;
72
+ /** Fetch a stored decision record, or null when absent/expired */
73
+ getDecision(assignmentId: string): Promise<LearningDecisionRecord | null>;
74
+ /**
75
+ * Apply a lifecycle outcome as a reward update.
76
+ * Terminal outcomes archive the decision as an episode (with TTL) so late
77
+ * external feedback can still be attributed to the original features.
78
+ * Returns false if no decision context exists for the assignment.
79
+ */
80
+ applyOutcome(assignmentId: string, outcome: LearningOutcome): Promise<boolean>;
81
+ /**
82
+ * Apply a manually chosen reward (terminal: removes the decision record).
83
+ * Enables external reward shaping beyond the built-in lifecycle outcomes.
84
+ */
85
+ recordReward(assignmentId: string, reward: number): Promise<boolean>;
86
+ private applyReward;
87
+ /** Apply an SGD update for a single (features, reward) observation */
88
+ private updateModel;
89
+ /** Fetch an archived episode record, or null when absent/expired */
90
+ getEpisode(assignmentId: string): Promise<LearningEpisodeRecord | null>;
91
+ /**
92
+ * Apply named external feedback signals (e.g. { accuracy: 0.95 }) against
93
+ * the live decision or the archived episode of an assignment.
94
+ * Reward = sum(signalValue * signalWeight), default weight 1 per signal.
95
+ * Returns false when no learning context exists for the assignment.
96
+ */
97
+ recordFeedback(assignmentId: string, signals: LearningSignals): Promise<boolean>;
98
+ /**
99
+ * Train the model directly with raw (features, reward) samples.
100
+ * Enables offline/batch imports from external pipelines (data warehouses,
101
+ * historical logs, post-processing jobs) without a live decision context.
102
+ */
103
+ trainSamples(samples: LearningSample[]): Promise<number>;
104
+ /**
105
+ * Update per-user, per-tag reward aggregates (count + reward sum).
106
+ * Uses atomic hash increments only - O(tags) with no read-modify-write -
107
+ * so high-throughput outcome streams scale without contention.
108
+ */
109
+ private updateTagStats;
110
+ /** Per-user, per-tag reward statistics aggregated from observed outcomes */
111
+ getUserTagStats(userId: string): Promise<LearningTagStat[]>;
112
+ /** Users that have accumulated tag reward statistics */
113
+ listTrackedUsers(): Promise<string[]>;
114
+ /**
115
+ * Synthesize a routingWeights map for a user from learned tag statistics
116
+ * (UCB1 policy: mean reward + exploration bonus, hard veto for bad tags).
117
+ * Pure read + O(tags) computation; does not persist anything.
118
+ *
119
+ * @param existingWeights current routingWeights of the user; values are
120
+ * used as warm per-tag priors for under-sampled or unobserved tags
121
+ * instead of the flat `priorWeight`.
122
+ */
123
+ getLearnedRoutingWeights(userId: string, knownTags?: string[], existingWeights?: Record<string, number>): Promise<Record<string, number>>;
124
+ /** Aggregate learning statistics */
125
+ getStats(): Promise<LearningStats>;
126
+ /** Reset model weights, statistics, and per-user tag statistics */
127
+ resetModel(): Promise<void>;
128
+ }
129
+ //# sourceMappingURL=LearningManager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"LearningManager.d.ts","sourceRoot":"","sources":["../../src/managers/LearningManager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,KAAK,EACR,eAAe,EACf,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,sBAAsB,EACtB,qBAAqB,EACrB,eAAe,EACf,cAAc,EACd,aAAa,EACb,eAAe,EACf,yBAAyB,EAC5B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAGjD,eAAO,MAAM,wBAAwB,EAAE,eAMtC,CAAC;AAKF,MAAM,WAAW,sBAAsB;IACnC,uCAAuC;IACvC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,sDAAsD;IACtD,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,6EAA6E;IAC7E,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,0EAA0E;IAC1E,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,4CAA4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Ae,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACzC,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAMlC,oCAAoC;IAC9B,QAAQ,IAAI,OAAO,CAAC,aAAa,CAAC;IAaxC,mEAAmE;IAC7D,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;CAYpC"}
@@ -0,0 +1,269 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LearningManager = exports.DEFAULT_LEARNING_REWARDS = void 0;
4
+ const auto_weights_1 = require("../learning/auto-weights");
5
+ exports.DEFAULT_LEARNING_REWARDS = {
6
+ accept: 0.3,
7
+ complete: 1,
8
+ reject: -0.6,
9
+ expire: -0.3,
10
+ fail: -0.8,
11
+ };
12
+ /** Outcomes that end an assignment's learning episode (decision record is removed) */
13
+ const TERMINAL_OUTCOMES = new Set(['complete', 'reject', 'expire', 'fail']);
14
+ class LearningManager {
15
+ constructor(redisClient, keys, options) {
16
+ this.redisClient = redisClient;
17
+ this.keys = keys;
18
+ this.learningRate = options?.learningRate ?? 0.1;
19
+ this.explorationRate = options?.explorationRate ?? 0.05;
20
+ this._shadowMode = options?.shadowMode ?? false;
21
+ this.boostFactor = options?.boostFactor ?? 1;
22
+ this.rewards = { ...exports.DEFAULT_LEARNING_REWARDS, ...options?.rewards };
23
+ this.decisionTtlMs = options?.decisionTtlMs ?? 604800000;
24
+ this.signalWeights = options?.signalWeights ?? {};
25
+ this.feedbackTtlMs = options?.feedbackTtlMs ?? 604800000;
26
+ this.trackTagStats = options?.trackTagStats ?? false;
27
+ this.autoWeights = options?.autoWeights ?? {};
28
+ }
29
+ /** Load the full model weights hash from Redis */
30
+ async getModel() {
31
+ return this.redisClient.hGetAll(this.keys.learningModel());
32
+ }
33
+ /** Predict expected reward for a feature vector against given model weights */
34
+ predict(features, weights) {
35
+ let sum = 0;
36
+ for (const [feature, value] of Object.entries(features)) {
37
+ const w = Number(weights[feature]);
38
+ if (!Number.isNaN(w) && w !== 0)
39
+ sum += w * value;
40
+ }
41
+ return sum;
42
+ }
43
+ /** Epsilon-greedy exploration check */
44
+ shouldExplore() {
45
+ return this.explorationRate > 0 && Math.random() < this.explorationRate;
46
+ }
47
+ /** Current shadow mode state (true: learn-only, false: affects ranking) */
48
+ get shadowMode() {
49
+ return this._shadowMode;
50
+ }
51
+ /**
52
+ * Toggle shadow mode at runtime without resetting model/state.
53
+ *
54
+ * When enabled, the matcher still records decisions and learns rewards,
55
+ * but predicted rewards do not influence ranking.
56
+ */
57
+ setShadowMode(enabled) {
58
+ this._shadowMode = enabled;
59
+ }
60
+ /**
61
+ * Persist the decision context for an assignment so the eventual outcome
62
+ * can be attributed back to the features that drove the match.
63
+ */
64
+ async recordDecision(userId, assignmentId, features, predictedReward, tags) {
65
+ const record = {
66
+ userId,
67
+ assignmentId,
68
+ features,
69
+ predictedReward,
70
+ tags,
71
+ timestamp: Date.now(),
72
+ };
73
+ const multi = this.redisClient.multi();
74
+ multi.set(this.keys.learningDecision(assignmentId), JSON.stringify(record), {
75
+ PX: this.decisionTtlMs,
76
+ });
77
+ multi.hIncrBy(this.keys.learningStats(), 'decisions', 1);
78
+ await multi.exec();
79
+ }
80
+ /** Fetch a stored decision record, or null when absent/expired */
81
+ async getDecision(assignmentId) {
82
+ const json = await this.redisClient.get(this.keys.learningDecision(assignmentId));
83
+ if (!json)
84
+ return null;
85
+ try {
86
+ return JSON.parse(json);
87
+ }
88
+ catch {
89
+ return null;
90
+ }
91
+ }
92
+ /**
93
+ * Apply a lifecycle outcome as a reward update.
94
+ * Terminal outcomes archive the decision as an episode (with TTL) so late
95
+ * external feedback can still be attributed to the original features.
96
+ * Returns false if no decision context exists for the assignment.
97
+ */
98
+ async applyOutcome(assignmentId, outcome) {
99
+ return this.applyReward(assignmentId, this.rewards[outcome], TERMINAL_OUTCOMES.has(outcome), outcome);
100
+ }
101
+ /**
102
+ * Apply a manually chosen reward (terminal: removes the decision record).
103
+ * Enables external reward shaping beyond the built-in lifecycle outcomes.
104
+ */
105
+ async recordReward(assignmentId, reward) {
106
+ return this.applyReward(assignmentId, reward, true);
107
+ }
108
+ async applyReward(assignmentId, reward, terminal, outcome) {
109
+ const decision = await this.getDecision(assignmentId);
110
+ if (!decision)
111
+ return false;
112
+ await this.updateModel(decision.features, reward);
113
+ await this.updateTagStats(decision.userId, decision.tags, reward);
114
+ if (terminal) {
115
+ // Archive as episode so external post-processing feedback can
116
+ // still reach the model after the assignment is closed.
117
+ const episode = {
118
+ userId: decision.userId,
119
+ assignmentId,
120
+ features: decision.features,
121
+ outcome,
122
+ tags: decision.tags,
123
+ timestamp: Date.now(),
124
+ };
125
+ const multi = this.redisClient.multi();
126
+ multi.set(this.keys.learningEpisode(assignmentId), JSON.stringify(episode), {
127
+ PX: this.feedbackTtlMs,
128
+ });
129
+ multi.del(this.keys.learningDecision(assignmentId));
130
+ await multi.exec();
131
+ }
132
+ return true;
133
+ }
134
+ /** Apply an SGD update for a single (features, reward) observation */
135
+ async updateModel(features, reward) {
136
+ const weights = await this.getModel();
137
+ const prediction = this.predict(features, weights);
138
+ const error = reward - prediction;
139
+ const multi = this.redisClient.multi();
140
+ for (const [feature, value] of Object.entries(features)) {
141
+ if (value === 0)
142
+ continue;
143
+ multi.hIncrByFloat(this.keys.learningModel(), feature, this.learningRate * error * value);
144
+ }
145
+ multi.hIncrBy(this.keys.learningStats(), 'rewards', 1);
146
+ multi.hIncrByFloat(this.keys.learningStats(), 'totalReward', reward);
147
+ await multi.exec();
148
+ }
149
+ /** Fetch an archived episode record, or null when absent/expired */
150
+ async getEpisode(assignmentId) {
151
+ const json = await this.redisClient.get(this.keys.learningEpisode(assignmentId));
152
+ if (!json)
153
+ return null;
154
+ try {
155
+ return JSON.parse(json);
156
+ }
157
+ catch {
158
+ return null;
159
+ }
160
+ }
161
+ /**
162
+ * Apply named external feedback signals (e.g. { accuracy: 0.95 }) against
163
+ * the live decision or the archived episode of an assignment.
164
+ * Reward = sum(signalValue * signalWeight), default weight 1 per signal.
165
+ * Returns false when no learning context exists for the assignment.
166
+ */
167
+ async recordFeedback(assignmentId, signals) {
168
+ const context = (await this.getDecision(assignmentId)) ?? (await this.getEpisode(assignmentId));
169
+ if (!context)
170
+ return false;
171
+ let reward = 0;
172
+ for (const [signal, value] of Object.entries(signals)) {
173
+ const weight = this.signalWeights[signal] ?? 1;
174
+ reward += value * weight;
175
+ }
176
+ await this.updateModel(context.features, reward);
177
+ await this.updateTagStats(context.userId, context.tags, reward);
178
+ return true;
179
+ }
180
+ /**
181
+ * Train the model directly with raw (features, reward) samples.
182
+ * Enables offline/batch imports from external pipelines (data warehouses,
183
+ * historical logs, post-processing jobs) without a live decision context.
184
+ */
185
+ async trainSamples(samples) {
186
+ let applied = 0;
187
+ for (const sample of samples) {
188
+ await this.updateModel(sample.features, sample.reward);
189
+ applied++;
190
+ }
191
+ return applied;
192
+ }
193
+ /**
194
+ * Update per-user, per-tag reward aggregates (count + reward sum).
195
+ * Uses atomic hash increments only - O(tags) with no read-modify-write -
196
+ * so high-throughput outcome streams scale without contention.
197
+ */
198
+ async updateTagStats(userId, tags, reward) {
199
+ if (!this.trackTagStats || !tags || tags.length === 0)
200
+ return;
201
+ const multi = this.redisClient.multi();
202
+ for (const tag of tags) {
203
+ if (!tag)
204
+ continue;
205
+ multi.hIncrBy(this.keys.learningUserTagCounts(userId), tag, 1);
206
+ multi.hIncrByFloat(this.keys.learningUserTagRewards(userId), tag, reward);
207
+ }
208
+ multi.sAdd(this.keys.learningUsers(), userId);
209
+ await multi.exec();
210
+ }
211
+ /** Per-user, per-tag reward statistics aggregated from observed outcomes */
212
+ async getUserTagStats(userId) {
213
+ const [counts, rewards] = await Promise.all([
214
+ this.redisClient.hGetAll(this.keys.learningUserTagCounts(userId)),
215
+ this.redisClient.hGetAll(this.keys.learningUserTagRewards(userId)),
216
+ ]);
217
+ return Object.entries(counts).map(([tag, rawCount]) => {
218
+ const count = Number(rawCount) || 0;
219
+ const rewardSum = Number(rewards[tag]) || 0;
220
+ return { tag, count, rewardSum, meanReward: count > 0 ? rewardSum / count : 0 };
221
+ });
222
+ }
223
+ /** Users that have accumulated tag reward statistics */
224
+ async listTrackedUsers() {
225
+ return this.redisClient.sMembers(this.keys.learningUsers());
226
+ }
227
+ /**
228
+ * Synthesize a routingWeights map for a user from learned tag statistics
229
+ * (UCB1 policy: mean reward + exploration bonus, hard veto for bad tags).
230
+ * Pure read + O(tags) computation; does not persist anything.
231
+ *
232
+ * @param existingWeights current routingWeights of the user; values are
233
+ * used as warm per-tag priors for under-sampled or unobserved tags
234
+ * instead of the flat `priorWeight`.
235
+ */
236
+ async getLearnedRoutingWeights(userId, knownTags, existingWeights) {
237
+ const stats = await this.getUserTagStats(userId);
238
+ if (stats.length === 0 && (!knownTags || knownTags.length === 0))
239
+ return {};
240
+ return (0, auto_weights_1.synthesizeRoutingWeights)(stats, this.autoWeights, knownTags, existingWeights);
241
+ }
242
+ /** Aggregate learning statistics */
243
+ async getStats() {
244
+ const raw = await this.redisClient.hGetAll(this.keys.learningStats());
245
+ const decisions = Number(raw.decisions) || 0;
246
+ const rewards = Number(raw.rewards) || 0;
247
+ const totalReward = Number(raw.totalReward) || 0;
248
+ return {
249
+ decisions,
250
+ rewards,
251
+ totalReward,
252
+ averageReward: rewards > 0 ? totalReward / rewards : 0,
253
+ };
254
+ }
255
+ /** Reset model weights, statistics, and per-user tag statistics */
256
+ async resetModel() {
257
+ const trackedUsers = await this.listTrackedUsers();
258
+ const multi = this.redisClient.multi();
259
+ multi.del(this.keys.learningModel());
260
+ multi.del(this.keys.learningStats());
261
+ for (const userId of trackedUsers) {
262
+ multi.del(this.keys.learningUserTagCounts(userId));
263
+ multi.del(this.keys.learningUserTagRewards(userId));
264
+ }
265
+ multi.del(this.keys.learningUsers());
266
+ await multi.exec();
267
+ }
268
+ }
269
+ exports.LearningManager = LearningManager;