assignment-user-matcher 1.2.2 → 1.2.5

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 (38) hide show
  1. package/README.md +243 -91
  2. package/dist/index.d.ts +5 -3
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +6 -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/lua/workflow-transition.lua +29 -0
  9. package/dist/managers/LearningManager.d.ts +39 -4
  10. package/dist/managers/LearningManager.d.ts.map +1 -1
  11. package/dist/managers/LearningManager.js +78 -3
  12. package/dist/managers/ReliabilityManager.d.ts +60 -2
  13. package/dist/managers/ReliabilityManager.d.ts.map +1 -1
  14. package/dist/managers/ReliabilityManager.js +190 -9
  15. package/dist/managers/TelemetryManager.d.ts.map +1 -1
  16. package/dist/managers/WorkflowManager.d.ts +78 -1
  17. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  18. package/dist/managers/WorkflowManager.js +449 -77
  19. package/dist/matcher.class.d.ts +195 -8
  20. package/dist/matcher.class.d.ts.map +1 -1
  21. package/dist/matcher.class.js +619 -36
  22. package/dist/queries/pagination.d.ts.map +1 -1
  23. package/dist/queries/pagination.js +9 -6
  24. package/dist/scoring/fair-arbitration.d.ts +68 -0
  25. package/dist/scoring/fair-arbitration.d.ts.map +1 -0
  26. package/dist/scoring/fair-arbitration.js +151 -0
  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 -0
  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 +13 -0
  35. package/dist/utils/keys.d.ts.map +1 -1
  36. package/dist/utils/keys.js +14 -0
  37. package/dist/workflow-validation.d.ts.map +1 -1
  38. package/package.json +58 -57
@@ -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,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
+
@@ -10,7 +10,7 @@
10
10
  * rules (tags/weights, CIDR, skill thresholds) - it never makes an ineligible
11
11
  * assignment eligible.
12
12
  */
13
- import type { RedisClientType, LearningFeatures, LearningOutcome, LearningRewards, LearningDecisionRecord, LearningEpisodeRecord, LearningSignals, LearningSample, LearningStats } from '../types/matcher';
13
+ import type { RedisClientType, LearningFeatures, LearningOutcome, LearningRewards, LearningDecisionRecord, LearningEpisodeRecord, LearningSignals, LearningSample, LearningStats, LearningTagStat, AutoRoutingWeightsOptions } from '../types/matcher';
14
14
  import type { KeyBuilders } from '../utils/keys';
15
15
  export declare const DEFAULT_LEARNING_REWARDS: LearningRewards;
16
16
  export interface LearningManagerOptions {
@@ -30,18 +30,24 @@ export interface LearningManagerOptions {
30
30
  signalWeights?: Record<string, number>;
31
31
  /** TTL for archived episodes awaiting external feedback in ms (default: 7 days) */
32
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;
33
37
  }
34
38
  export declare class LearningManager {
35
39
  private redisClient;
36
40
  private keys;
37
41
  readonly learningRate: number;
38
42
  readonly explorationRate: number;
39
- readonly shadowMode: boolean;
43
+ private _shadowMode;
40
44
  readonly boostFactor: number;
41
45
  readonly rewards: LearningRewards;
42
46
  readonly decisionTtlMs: number;
43
47
  readonly signalWeights: Record<string, number>;
44
48
  readonly feedbackTtlMs: number;
49
+ readonly trackTagStats: boolean;
50
+ readonly autoWeights: AutoRoutingWeightsOptions;
45
51
  constructor(redisClient: RedisClientType, keys: KeyBuilders, options?: LearningManagerOptions);
46
52
  /** Load the full model weights hash from Redis */
47
53
  getModel(): Promise<Record<string, string>>;
@@ -49,11 +55,20 @@ export declare class LearningManager {
49
55
  predict(features: LearningFeatures, weights: Record<string, string | number>): number;
50
56
  /** Epsilon-greedy exploration check */
51
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;
52
67
  /**
53
68
  * Persist the decision context for an assignment so the eventual outcome
54
69
  * can be attributed back to the features that drove the match.
55
70
  */
56
- recordDecision(userId: string, assignmentId: string, features: LearningFeatures, predictedReward: number): Promise<void>;
71
+ recordDecision(userId: string, assignmentId: string, features: LearningFeatures, predictedReward: number, tags?: string[]): Promise<void>;
57
72
  /** Fetch a stored decision record, or null when absent/expired */
58
73
  getDecision(assignmentId: string): Promise<LearningDecisionRecord | null>;
59
74
  /**
@@ -86,9 +101,29 @@ export declare class LearningManager {
86
101
  * historical logs, post-processing jobs) without a live decision context.
87
102
  */
88
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>>;
89
124
  /** Aggregate learning statistics */
90
125
  getStats(): Promise<LearningStats>;
91
- /** Reset model weights and statistics */
126
+ /** Reset model weights, statistics, and per-user tag statistics */
92
127
  resetModel(): Promise<void>;
93
128
  }
94
129
  //# sourceMappingURL=LearningManager.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"LearningManager.d.ts","sourceRoot":"","sources":["../../src/managers/LearningManager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,eAAe,EAAE,eAAe,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,eAAe,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAC3M,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAEjD,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,4CAA4C;IAC5C,OAAO,CAAC,EAAE,OAAO,CAAC,eAAe,CAAC,CAAC;IACnC,+DAA+D;IAC/D,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,6EAA6E;IAC7E,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACvC,mFAAmF;IACnF,aAAa,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,qBAAa,eAAe;IAWpB,OAAO,CAAC,WAAW;IACnB,OAAO,CAAC,IAAI;IAXhB,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC;IAC7B,QAAQ,CAAC,WAAW,EAA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REWARDS = void 0;
4
+ const auto_weights_1 = require("../learning/auto-weights");
4
5
  exports.DEFAULT_LEARNING_REWARDS = {
5
6
  accept: 0.3,
6
7
  complete: 1,
@@ -16,12 +17,14 @@ class LearningManager {
16
17
  this.keys = keys;
17
18
  this.learningRate = options?.learningRate ?? 0.1;
18
19
  this.explorationRate = options?.explorationRate ?? 0.05;
19
- this.shadowMode = options?.shadowMode ?? false;
20
+ this._shadowMode = options?.shadowMode ?? false;
20
21
  this.boostFactor = options?.boostFactor ?? 1;
21
22
  this.rewards = { ...exports.DEFAULT_LEARNING_REWARDS, ...options?.rewards };
22
23
  this.decisionTtlMs = options?.decisionTtlMs ?? 604800000;
23
24
  this.signalWeights = options?.signalWeights ?? {};
24
25
  this.feedbackTtlMs = options?.feedbackTtlMs ?? 604800000;
26
+ this.trackTagStats = options?.trackTagStats ?? false;
27
+ this.autoWeights = options?.autoWeights ?? {};
25
28
  }
26
29
  /** Load the full model weights hash from Redis */
27
30
  async getModel() {
@@ -41,16 +44,30 @@ class LearningManager {
41
44
  shouldExplore() {
42
45
  return this.explorationRate > 0 && Math.random() < this.explorationRate;
43
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
+ }
44
60
  /**
45
61
  * Persist the decision context for an assignment so the eventual outcome
46
62
  * can be attributed back to the features that drove the match.
47
63
  */
48
- async recordDecision(userId, assignmentId, features, predictedReward) {
64
+ async recordDecision(userId, assignmentId, features, predictedReward, tags) {
49
65
  const record = {
50
66
  userId,
51
67
  assignmentId,
52
68
  features,
53
69
  predictedReward,
70
+ tags,
54
71
  timestamp: Date.now(),
55
72
  };
56
73
  const multi = this.redisClient.multi();
@@ -93,6 +110,7 @@ class LearningManager {
93
110
  if (!decision)
94
111
  return false;
95
112
  await this.updateModel(decision.features, reward);
113
+ await this.updateTagStats(decision.userId, decision.tags, reward);
96
114
  if (terminal) {
97
115
  // Archive as episode so external post-processing feedback can
98
116
  // still reach the model after the assignment is closed.
@@ -101,6 +119,7 @@ class LearningManager {
101
119
  assignmentId,
102
120
  features: decision.features,
103
121
  outcome,
122
+ tags: decision.tags,
104
123
  timestamp: Date.now(),
105
124
  };
106
125
  const multi = this.redisClient.multi();
@@ -155,6 +174,7 @@ class LearningManager {
155
174
  reward += value * weight;
156
175
  }
157
176
  await this.updateModel(context.features, reward);
177
+ await this.updateTagStats(context.userId, context.tags, reward);
158
178
  return true;
159
179
  }
160
180
  /**
@@ -170,6 +190,55 @@ class LearningManager {
170
190
  }
171
191
  return applied;
172
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
+ }
173
242
  /** Aggregate learning statistics */
174
243
  async getStats() {
175
244
  const raw = await this.redisClient.hGetAll(this.keys.learningStats());
@@ -183,11 +252,17 @@ class LearningManager {
183
252
  averageReward: rewards > 0 ? totalReward / rewards : 0,
184
253
  };
185
254
  }
186
- /** Reset model weights and statistics */
255
+ /** Reset model weights, statistics, and per-user tag statistics */
187
256
  async resetModel() {
257
+ const trackedUsers = await this.listTrackedUsers();
188
258
  const multi = this.redisClient.multi();
189
259
  multi.del(this.keys.learningModel());
190
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());
191
266
  await multi.exec();
192
267
  }
193
268
  }
@@ -1,6 +1,6 @@
1
1
  import { RedisClientType } from '../types/matcher';
2
2
  import { KeyBuilders } from '../utils/keys';
3
- import { WorkflowEvent, DeadLetterEntry, AuditEntry, CircuitBreakerState } from '../types/matcher';
3
+ import { WorkflowEvent, DeadLetterEntry, AuditEntry, CircuitBreakerState, ReliabilityMetrics } from '../types/matcher';
4
4
  export declare class ReliabilityManager {
5
5
  private redisClient;
6
6
  private keys;
@@ -12,8 +12,19 @@ export declare class ReliabilityManager {
12
12
  workflowAuditEnabled: boolean;
13
13
  workflowSnapshotDefinitions?: boolean;
14
14
  streamConsumerName: string;
15
+ circuitBreakerPersistState?: boolean;
16
+ circuitBreakerShared?: boolean;
17
+ enableReliabilityMetrics?: boolean;
18
+ deadLetterQueueAlertThreshold?: number;
15
19
  };
16
20
  private circuitBreaker;
21
+ private metrics;
22
+ private persistState;
23
+ private reconnectCount;
24
+ private lastError?;
25
+ private redisHealthy;
26
+ private lastConnectedAt;
27
+ private lastHealthCheckAt?;
17
28
  constructor(redisClient: RedisClientType, keys: KeyBuilders, options: {
18
29
  workflowMaxRetries: number;
19
30
  workflowIdempotencyTtlMs: number;
@@ -22,7 +33,43 @@ export declare class ReliabilityManager {
22
33
  workflowAuditEnabled: boolean;
23
34
  workflowSnapshotDefinitions?: boolean;
24
35
  streamConsumerName: string;
36
+ circuitBreakerPersistState?: boolean;
37
+ circuitBreakerShared?: boolean;
38
+ enableReliabilityMetrics?: boolean;
39
+ deadLetterQueueAlertThreshold?: number;
25
40
  });
41
+ /**
42
+ * Initialize the reliability manager by loading persisted state if enabled
43
+ */
44
+ init(): Promise<void>;
45
+ /**
46
+ * Load circuit breaker state from Redis for distributed awareness
47
+ */
48
+ private loadCircuitBreakerState;
49
+ /**
50
+ * Save circuit breaker state to Redis for distributed awareness
51
+ */
52
+ private saveCircuitBreakerState;
53
+ /**
54
+ * Update reliability metrics
55
+ */
56
+ private updateMetrics;
57
+ /**
58
+ * Get current reliability metrics
59
+ */
60
+ getMetrics(): Promise<ReliabilityMetrics>;
61
+ /**
62
+ * Update Redis health status (called by health check mechanism)
63
+ */
64
+ updateRedisHealth(isHealthy: boolean, error?: string): void;
65
+ /**
66
+ * Update reconnection count (called by connection handler)
67
+ */
68
+ updateReconnectCount(count: number): void;
69
+ /**
70
+ * Update last health check timestamp
71
+ */
72
+ updateHealthCheckTimestamp(): void;
26
73
  /**
27
74
  * Move a failed event to the Dead Letter Queue.
28
75
  */
@@ -34,9 +81,20 @@ export declare class ReliabilityManager {
34
81
  markEventProcessed(eventId: string): Promise<void>;
35
82
  shouldProcessCircuitBreaker(): boolean;
36
83
  recordCircuitBreakerSuccess(): void;
37
- recordCircuitBreakerFailure(): void;
84
+ recordCircuitBreakerFailure(): Promise<void>;
38
85
  emitAuditEvent(action: string, resourceId: string, details?: Record<string, any>, resourceType?: string): Promise<void>;
39
86
  getAuditEvents(count?: number): Promise<AuditEntry[]>;
40
87
  getCircuitBreakerState(): CircuitBreakerState;
88
+ /**
89
+ * Check if Dead Letter Queue size exceeds alert threshold
90
+ */
91
+ checkDeadLetterQueueAlert(): Promise<boolean>;
92
+ /**
93
+ * Perform exponential backoff delay
94
+ * @param attempt Current retry attempt
95
+ * @param initialDelay Initial delay in ms (default: 100)
96
+ * @param maxDelay Maximum delay in ms (default: 5000)
97
+ */
98
+ static backoff(attempt: number, initialDelay?: number, maxDelay?: number): Promise<void>;
41
99
  }
42
100
  //# sourceMappingURL=ReliabilityManager.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ReliabilityManager.d.ts","sourceRoot":"","sources":["../../src/managers/ReliabilityManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EACH,aAAa,EACb,eAAe,EACf,UAAU,EACV,mBAAmB,EACtB,MAAM,kBAAkB,CAAC;AAE1B,qBAAa,kBAAkB;IAIvB,OAAO,CAAC,WAAW;IACnB,OAAO,CAAC,IAAI;IACL,OAAO,EAAE;QACZ,kBAAkB,EAAE,MAAM,CAAC;QAC3B,wBAAwB,EAAE,MAAM,CAAC;QACjC,+BAA+B,EAAE,MAAM,CAAC;QACxC,6BAA6B,EAAE,MAAM,CAAC;QACtC,oBAAoB,EAAE,OAAO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