assignment-user-matcher 1.2.0 → 1.2.2

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,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,94 @@
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 } 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
+ }
34
+ export declare class LearningManager {
35
+ private redisClient;
36
+ private keys;
37
+ readonly learningRate: number;
38
+ readonly explorationRate: number;
39
+ readonly shadowMode: boolean;
40
+ readonly boostFactor: number;
41
+ readonly rewards: LearningRewards;
42
+ readonly decisionTtlMs: number;
43
+ readonly signalWeights: Record<string, number>;
44
+ readonly feedbackTtlMs: number;
45
+ constructor(redisClient: RedisClientType, keys: KeyBuilders, options?: LearningManagerOptions);
46
+ /** Load the full model weights hash from Redis */
47
+ getModel(): Promise<Record<string, string>>;
48
+ /** Predict expected reward for a feature vector against given model weights */
49
+ predict(features: LearningFeatures, weights: Record<string, string | number>): number;
50
+ /** Epsilon-greedy exploration check */
51
+ shouldExplore(): boolean;
52
+ /**
53
+ * Persist the decision context for an assignment so the eventual outcome
54
+ * can be attributed back to the features that drove the match.
55
+ */
56
+ recordDecision(userId: string, assignmentId: string, features: LearningFeatures, predictedReward: number): Promise<void>;
57
+ /** Fetch a stored decision record, or null when absent/expired */
58
+ getDecision(assignmentId: string): Promise<LearningDecisionRecord | null>;
59
+ /**
60
+ * Apply a lifecycle outcome as a reward update.
61
+ * Terminal outcomes archive the decision as an episode (with TTL) so late
62
+ * external feedback can still be attributed to the original features.
63
+ * Returns false if no decision context exists for the assignment.
64
+ */
65
+ applyOutcome(assignmentId: string, outcome: LearningOutcome): Promise<boolean>;
66
+ /**
67
+ * Apply a manually chosen reward (terminal: removes the decision record).
68
+ * Enables external reward shaping beyond the built-in lifecycle outcomes.
69
+ */
70
+ recordReward(assignmentId: string, reward: number): Promise<boolean>;
71
+ private applyReward;
72
+ /** Apply an SGD update for a single (features, reward) observation */
73
+ private updateModel;
74
+ /** Fetch an archived episode record, or null when absent/expired */
75
+ getEpisode(assignmentId: string): Promise<LearningEpisodeRecord | null>;
76
+ /**
77
+ * Apply named external feedback signals (e.g. { accuracy: 0.95 }) against
78
+ * the live decision or the archived episode of an assignment.
79
+ * Reward = sum(signalValue * signalWeight), default weight 1 per signal.
80
+ * Returns false when no learning context exists for the assignment.
81
+ */
82
+ recordFeedback(assignmentId: string, signals: LearningSignals): Promise<boolean>;
83
+ /**
84
+ * Train the model directly with raw (features, reward) samples.
85
+ * Enables offline/batch imports from external pipelines (data warehouses,
86
+ * historical logs, post-processing jobs) without a live decision context.
87
+ */
88
+ trainSamples(samples: LearningSample[]): Promise<number>;
89
+ /** Aggregate learning statistics */
90
+ getStats(): Promise<LearningStats>;
91
+ /** Reset model weights and statistics */
92
+ resetModel(): Promise<void>;
93
+ }
94
+ //# 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,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,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qB,GAAG,IAAI,CAAC;IAU7E;;;;;OAKG;IACG,cAAc,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC;IActF;;;;OAIG;IACG,YAAY,CAAC,OAAO,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC;IAS9D,oCAAoC;IAC9B,QAAQ,IAAI,OAAO,CAAC,aAAa,CAAC;IAaxC,yCAAyC;IACnC,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;CAMpC"}
@@ -0,0 +1,194 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LearningManager = exports.DEFAULT_LEARNING_REWARDS = void 0;
4
+ exports.DEFAULT_LEARNING_REWARDS = {
5
+ accept: 0.3,
6
+ complete: 1,
7
+ reject: -0.6,
8
+ expire: -0.3,
9
+ fail: -0.8,
10
+ };
11
+ /** Outcomes that end an assignment's learning episode (decision record is removed) */
12
+ const TERMINAL_OUTCOMES = new Set(['complete', 'reject', 'expire', 'fail']);
13
+ class LearningManager {
14
+ constructor(redisClient, keys, options) {
15
+ this.redisClient = redisClient;
16
+ this.keys = keys;
17
+ this.learningRate = options?.learningRate ?? 0.1;
18
+ this.explorationRate = options?.explorationRate ?? 0.05;
19
+ this.shadowMode = options?.shadowMode ?? false;
20
+ this.boostFactor = options?.boostFactor ?? 1;
21
+ this.rewards = { ...exports.DEFAULT_LEARNING_REWARDS, ...options?.rewards };
22
+ this.decisionTtlMs = options?.decisionTtlMs ?? 604800000;
23
+ this.signalWeights = options?.signalWeights ?? {};
24
+ this.feedbackTtlMs = options?.feedbackTtlMs ?? 604800000;
25
+ }
26
+ /** Load the full model weights hash from Redis */
27
+ async getModel() {
28
+ return this.redisClient.hGetAll(this.keys.learningModel());
29
+ }
30
+ /** Predict expected reward for a feature vector against given model weights */
31
+ predict(features, weights) {
32
+ let sum = 0;
33
+ for (const [feature, value] of Object.entries(features)) {
34
+ const w = Number(weights[feature]);
35
+ if (!Number.isNaN(w) && w !== 0)
36
+ sum += w * value;
37
+ }
38
+ return sum;
39
+ }
40
+ /** Epsilon-greedy exploration check */
41
+ shouldExplore() {
42
+ return this.explorationRate > 0 && Math.random() < this.explorationRate;
43
+ }
44
+ /**
45
+ * Persist the decision context for an assignment so the eventual outcome
46
+ * can be attributed back to the features that drove the match.
47
+ */
48
+ async recordDecision(userId, assignmentId, features, predictedReward) {
49
+ const record = {
50
+ userId,
51
+ assignmentId,
52
+ features,
53
+ predictedReward,
54
+ timestamp: Date.now(),
55
+ };
56
+ const multi = this.redisClient.multi();
57
+ multi.set(this.keys.learningDecision(assignmentId), JSON.stringify(record), {
58
+ PX: this.decisionTtlMs,
59
+ });
60
+ multi.hIncrBy(this.keys.learningStats(), 'decisions', 1);
61
+ await multi.exec();
62
+ }
63
+ /** Fetch a stored decision record, or null when absent/expired */
64
+ async getDecision(assignmentId) {
65
+ const json = await this.redisClient.get(this.keys.learningDecision(assignmentId));
66
+ if (!json)
67
+ return null;
68
+ try {
69
+ return JSON.parse(json);
70
+ }
71
+ catch {
72
+ return null;
73
+ }
74
+ }
75
+ /**
76
+ * Apply a lifecycle outcome as a reward update.
77
+ * Terminal outcomes archive the decision as an episode (with TTL) so late
78
+ * external feedback can still be attributed to the original features.
79
+ * Returns false if no decision context exists for the assignment.
80
+ */
81
+ async applyOutcome(assignmentId, outcome) {
82
+ return this.applyReward(assignmentId, this.rewards[outcome], TERMINAL_OUTCOMES.has(outcome), outcome);
83
+ }
84
+ /**
85
+ * Apply a manually chosen reward (terminal: removes the decision record).
86
+ * Enables external reward shaping beyond the built-in lifecycle outcomes.
87
+ */
88
+ async recordReward(assignmentId, reward) {
89
+ return this.applyReward(assignmentId, reward, true);
90
+ }
91
+ async applyReward(assignmentId, reward, terminal, outcome) {
92
+ const decision = await this.getDecision(assignmentId);
93
+ if (!decision)
94
+ return false;
95
+ await this.updateModel(decision.features, reward);
96
+ if (terminal) {
97
+ // Archive as episode so external post-processing feedback can
98
+ // still reach the model after the assignment is closed.
99
+ const episode = {
100
+ userId: decision.userId,
101
+ assignmentId,
102
+ features: decision.features,
103
+ outcome,
104
+ timestamp: Date.now(),
105
+ };
106
+ const multi = this.redisClient.multi();
107
+ multi.set(this.keys.learningEpisode(assignmentId), JSON.stringify(episode), {
108
+ PX: this.feedbackTtlMs,
109
+ });
110
+ multi.del(this.keys.learningDecision(assignmentId));
111
+ await multi.exec();
112
+ }
113
+ return true;
114
+ }
115
+ /** Apply an SGD update for a single (features, reward) observation */
116
+ async updateModel(features, reward) {
117
+ const weights = await this.getModel();
118
+ const prediction = this.predict(features, weights);
119
+ const error = reward - prediction;
120
+ const multi = this.redisClient.multi();
121
+ for (const [feature, value] of Object.entries(features)) {
122
+ if (value === 0)
123
+ continue;
124
+ multi.hIncrByFloat(this.keys.learningModel(), feature, this.learningRate * error * value);
125
+ }
126
+ multi.hIncrBy(this.keys.learningStats(), 'rewards', 1);
127
+ multi.hIncrByFloat(this.keys.learningStats(), 'totalReward', reward);
128
+ await multi.exec();
129
+ }
130
+ /** Fetch an archived episode record, or null when absent/expired */
131
+ async getEpisode(assignmentId) {
132
+ const json = await this.redisClient.get(this.keys.learningEpisode(assignmentId));
133
+ if (!json)
134
+ return null;
135
+ try {
136
+ return JSON.parse(json);
137
+ }
138
+ catch {
139
+ return null;
140
+ }
141
+ }
142
+ /**
143
+ * Apply named external feedback signals (e.g. { accuracy: 0.95 }) against
144
+ * the live decision or the archived episode of an assignment.
145
+ * Reward = sum(signalValue * signalWeight), default weight 1 per signal.
146
+ * Returns false when no learning context exists for the assignment.
147
+ */
148
+ async recordFeedback(assignmentId, signals) {
149
+ const context = (await this.getDecision(assignmentId)) ?? (await this.getEpisode(assignmentId));
150
+ if (!context)
151
+ return false;
152
+ let reward = 0;
153
+ for (const [signal, value] of Object.entries(signals)) {
154
+ const weight = this.signalWeights[signal] ?? 1;
155
+ reward += value * weight;
156
+ }
157
+ await this.updateModel(context.features, reward);
158
+ return true;
159
+ }
160
+ /**
161
+ * Train the model directly with raw (features, reward) samples.
162
+ * Enables offline/batch imports from external pipelines (data warehouses,
163
+ * historical logs, post-processing jobs) without a live decision context.
164
+ */
165
+ async trainSamples(samples) {
166
+ let applied = 0;
167
+ for (const sample of samples) {
168
+ await this.updateModel(sample.features, sample.reward);
169
+ applied++;
170
+ }
171
+ return applied;
172
+ }
173
+ /** Aggregate learning statistics */
174
+ async getStats() {
175
+ const raw = await this.redisClient.hGetAll(this.keys.learningStats());
176
+ const decisions = Number(raw.decisions) || 0;
177
+ const rewards = Number(raw.rewards) || 0;
178
+ const totalReward = Number(raw.totalReward) || 0;
179
+ return {
180
+ decisions,
181
+ rewards,
182
+ totalReward,
183
+ averageReward: rewards > 0 ? totalReward / rewards : 0,
184
+ };
185
+ }
186
+ /** Reset model weights and statistics */
187
+ async resetModel() {
188
+ const multi = this.redisClient.multi();
189
+ multi.del(this.keys.learningModel());
190
+ multi.del(this.keys.learningStats());
191
+ await multi.exec();
192
+ }
193
+ }
194
+ exports.LearningManager = LearningManager;
@@ -1,10 +1,15 @@
1
- import { RedisClientType, WorkflowDefinition, WorkflowInstance, WorkflowEvent, Assignment, WorkflowInstanceWithSnapshot } from '../types/matcher';
1
+ import { RedisClientType, WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowStep, WorkflowEvent, Assignment, WorkflowInstanceWithSnapshot } from '../types/matcher';
2
2
  import { KeyBuilders } from '../utils/keys';
3
3
  import { ReliabilityManager } from './ReliabilityManager';
4
4
  import { TelemetryManager } from './TelemetryManager';
5
5
  export interface WorkflowHost {
6
6
  addAssignment(assignment: Assignment): Promise<Assignment>;
7
7
  matchUsersAssignments(userId: string): Promise<any>;
8
+ executeMachineTask?(args: {
9
+ instance: WorkflowInstance;
10
+ step: WorkflowStep;
11
+ definition: WorkflowDefinition;
12
+ }): Promise<Record<string, any> | void>;
8
13
  }
9
14
  export declare class WorkflowManager {
10
15
  private redisClient;
@@ -22,22 +27,21 @@ export declare class WorkflowManager {
22
27
  streamConsumerGroup: string;
23
28
  streamConsumerName: string;
24
29
  reclaimIntervalMs: number;
30
+ reclaimMinIdleMs?: number;
25
31
  });
26
32
  init(): Promise<void>;
27
33
  private initStreamConsumerGroup;
28
34
  setLuaScriptSha(sha: string): void;
29
- registerWorkflow(definition: WorkflowDefinition): Promise<WorkflowDefinition>;
35
+ registerWorkflow(definition: WorkflowDefinitionInput | WorkflowDefinition): Promise<WorkflowDefinition>;
30
36
  getWorkflowDefinition(id: string): Promise<WorkflowDefinition | null>;
31
- listWorkflowDefinitions(): Promise<Array<{
32
- id: string;
33
- name: string;
34
- }>>;
37
+ listWorkflowDefinitions(): Promise<WorkflowDefinitionSummary[]>;
35
38
  startWorkflow(workflowDefinitionId: string, userId: string, initialContext?: Record<string, any>): Promise<WorkflowInstance>;
36
39
  getWorkflowInstance(instanceId: string): Promise<WorkflowInstance | null>;
37
40
  getWorkflowInstanceWithSnapshot(instanceId: string): Promise<WorkflowInstanceWithSnapshot | null>;
38
41
  getActiveWorkflowsForUser(userId: string): Promise<WorkflowInstance[]>;
39
42
  cancelWorkflow(instanceId: string): Promise<boolean>;
40
43
  private executeWorkflowStep;
44
+ private executeMachineStep;
41
45
  private setStepTimeout;
42
46
  processExpiredWorkflowSteps(): Promise<number>;
43
47
  private createWorkflowAssignment;
@@ -1 +1 @@
1
- {"version":3,"file":"WorkflowManager.d.ts","sourceRoot":"","sources":["../../src/managers/WorkflowManager.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,gBAAgB,EAAgB,aAAa,EAAqB,UAAU,EAAE,4BAA4B,EAAuB,MAAM,kBAAkB,CAAC;AACxM,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,MAAM,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;IAkBlC,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC;YASzB,gBAAgB;IAgF9B,OAAO,CAAC,kBAAkB;YAcZ,oBAAoB;YA2CpB,oBAAoB;YAgEpB,iBAAiB;YAwDjB,gBAAgB;IAQ9B,OAAO,CAAC,iBAAiB;IAqCnB,uBAAuB,IAAI,OAAO,CAAC,MAAM,CAAC;YAsDlC,YAAY;IAoBpB,wBAAwB,CAC1B,UAAU,EAAE,MAAM,EAClB,eAAe,EAAE,MAAM,EACvB,SAAS,EAAE,gBAAgB,CAAC,QAAQ,CAAC,EACrC,SAAS,EAAE,MAAM,GAAG,IAAI,EACxB,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EACnC,YAAY,CAAC,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,GAC9C,OAAO,CAAC;QAAE,EAAE,EAAE,OAAO,CAAC;QAAC,QAAQ,CAAC,EAAE,gBAAgB,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAgB3E"}
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.WorkflowManager = void 0;
4
4
  const crypto_1 = require("crypto");
5
+ const workflow_validation_1 = require("../workflow-validation");
5
6
  class WorkflowManager {
6
7
  constructor(redisClient, keys, reliability, telemetry, host, options) {
7
8
  this.redisClient = redisClient;
@@ -37,10 +38,11 @@ class WorkflowManager {
37
38
  this.luaScriptSha = sha;
38
39
  }
39
40
  async registerWorkflow(definition) {
40
- const key = this.keys.workflowDefinition(definition.id);
41
- await this.redisClient.set(key, JSON.stringify(definition));
42
- await this.redisClient.hSet(this.keys.workflowDefinitions(), definition.id, definition.name);
43
- return definition;
41
+ const normalizedDefinition = (0, workflow_validation_1.normalizeWorkflowDefinition)(definition);
42
+ const key = this.keys.workflowDefinition(normalizedDefinition.id);
43
+ await this.redisClient.set(key, JSON.stringify(normalizedDefinition));
44
+ await this.redisClient.hSet(this.keys.workflowDefinitions(), normalizedDefinition.id, normalizedDefinition.name);
45
+ return normalizedDefinition;
44
46
  }
45
47
  async getWorkflowDefinition(id) {
46
48
  const key = this.keys.workflowDefinition(id);
@@ -52,6 +54,12 @@ class WorkflowManager {
52
54
  return Object.entries(definitions).map(([id, name]) => ({ id, name }));
53
55
  }
54
56
  async startWorkflow(workflowDefinitionId, userId, initialContext) {
57
+ if (!workflowDefinitionId.trim()) {
58
+ throw new Error('Workflow definition ID is required');
59
+ }
60
+ if (!userId.trim()) {
61
+ throw new Error('Workflow user ID is required');
62
+ }
55
63
  const { span, end: endSpan } = this.telemetry.startSpan('workflow.start', {
56
64
  'workflow.definition_id': workflowDefinitionId,
57
65
  'workflow.user_id': userId,
@@ -155,33 +163,109 @@ class WorkflowManager {
155
163
  const expectedVersion = instance.version;
156
164
  if (step.parallelStepIds && step.parallelStepIds.length > 0) {
157
165
  const branches = [];
166
+ const machineParallelSteps = [];
158
167
  for (const parallelStepId of step.parallelStepIds) {
159
168
  const parallelStep = definition.steps.find((s) => s.id === parallelStepId);
160
169
  if (!parallelStep)
161
170
  continue;
162
- const assignment = await this.createWorkflowAssignment(instance, parallelStep, definition);
163
- branches.push({
164
- stepId: parallelStepId,
165
- assignmentId: assignment.id,
166
- status: 'pending',
167
- });
168
- if (parallelStep.timeoutMs) {
169
- await this.setStepTimeout(instance.id, parallelStepId, parallelStep.timeoutMs);
171
+ const taskType = parallelStep.taskType ?? 'assignment';
172
+ if (taskType === 'machine') {
173
+ if (!parallelStep.machineTask?.handler) {
174
+ throw new Error(`Machine step "${parallelStep.id}" is missing machineTask.handler`);
175
+ }
176
+ const syntheticAssignmentId = (0, crypto_1.randomUUID)();
177
+ machineParallelSteps.push({ stepId: parallelStepId, assignmentId: syntheticAssignmentId });
178
+ branches.push({
179
+ stepId: parallelStepId,
180
+ assignmentId: syntheticAssignmentId,
181
+ status: 'pending',
182
+ });
183
+ }
184
+ else {
185
+ const assignment = await this.createWorkflowAssignment(instance, parallelStep, definition);
186
+ branches.push({
187
+ stepId: parallelStepId,
188
+ assignmentId: assignment.id,
189
+ status: 'pending',
190
+ });
191
+ }
192
+ const timeoutMs = parallelStep.timeoutMs ?? definition.defaultTimeoutMs;
193
+ if (timeoutMs) {
194
+ await this.setStepTimeout(instance.id, parallelStepId, timeoutMs);
170
195
  }
171
196
  }
172
197
  instance.parallelBranches = branches;
173
198
  instance.currentStepId = null;
199
+ instance.currentAssignmentId = undefined;
200
+ await this.saveInstance(instance, expectedVersion);
201
+ for (const machineStep of machineParallelSteps) {
202
+ const parallelStep = definition.steps.find((s) => s.id === machineStep.stepId);
203
+ if (!parallelStep)
204
+ continue;
205
+ await this.executeMachineStep(instance, parallelStep, definition, machineStep.assignmentId);
206
+ }
207
+ return;
174
208
  }
175
- else {
176
- const assignment = await this.createWorkflowAssignment(instance, step, definition);
177
- instance.currentAssignmentId = assignment.id;
209
+ const taskType = step.taskType ?? 'assignment';
210
+ if (taskType === 'machine') {
211
+ if (!step.machineTask?.handler) {
212
+ throw new Error(`Machine step "${step.id}" is missing machineTask.handler`);
213
+ }
214
+ instance.currentAssignmentId = undefined;
178
215
  instance.currentStepId = stepId;
179
- if (step.timeoutMs) {
180
- await this.setStepTimeout(instance.id, stepId, step.timeoutMs);
216
+ const timeoutMs = step.timeoutMs ?? definition.defaultTimeoutMs;
217
+ if (timeoutMs) {
218
+ await this.setStepTimeout(instance.id, stepId, timeoutMs);
181
219
  }
220
+ await this.saveInstance(instance, expectedVersion);
221
+ await this.executeMachineStep(instance, step, definition);
222
+ return;
223
+ }
224
+ const assignment = await this.createWorkflowAssignment(instance, step, definition);
225
+ instance.currentAssignmentId = assignment.id;
226
+ instance.currentStepId = stepId;
227
+ const timeoutMs = step.timeoutMs ?? definition.defaultTimeoutMs;
228
+ if (timeoutMs) {
229
+ await this.setStepTimeout(instance.id, stepId, timeoutMs);
182
230
  }
183
231
  await this.saveInstance(instance, expectedVersion);
184
232
  }
233
+ async executeMachineStep(instance, step, definition, assignmentId) {
234
+ const syntheticAssignmentId = assignmentId ?? (0, crypto_1.randomUUID)();
235
+ const eventBase = {
236
+ eventId: (0, crypto_1.randomUUID)(),
237
+ type: 'COMPLETED',
238
+ userId: instance.initiatorUserId,
239
+ assignmentId: syntheticAssignmentId,
240
+ workflowInstanceId: instance.id,
241
+ stepId: step.id,
242
+ timestamp: Date.now(),
243
+ };
244
+ try {
245
+ if (!this.host.executeMachineTask) {
246
+ throw new Error(`Machine task executor not configured for step "${step.id}" (handler: ${step.machineTask?.handler ?? 'unknown'})`);
247
+ }
248
+ const result = await this.host.executeMachineTask({
249
+ instance,
250
+ step,
251
+ definition,
252
+ });
253
+ await this.processWorkflowEvent({
254
+ ...eventBase,
255
+ type: 'COMPLETED',
256
+ payload: result ? { ...result } : undefined,
257
+ });
258
+ }
259
+ catch (err) {
260
+ await this.processWorkflowEvent({
261
+ ...eventBase,
262
+ type: 'FAILED',
263
+ payload: {
264
+ error: err?.message ?? String(err),
265
+ },
266
+ });
267
+ }
268
+ }
185
269
  async setStepTimeout(instanceId, stepId, timeoutMs) {
186
270
  const expiryKey = this.keys.workflowStepExpiry(instanceId, stepId);
187
271
  const expiryTime = Date.now() + timeoutMs;
@@ -206,7 +290,8 @@ class WorkflowManager {
206
290
  if (!definition)
207
291
  continue;
208
292
  const step = definition.steps.find((s) => s.id === currentStepId);
209
- if (!step?.timeoutMs)
293
+ const timeoutMs = step?.timeoutMs ?? definition.defaultTimeoutMs;
294
+ if (!timeoutMs)
210
295
  continue;
211
296
  await this.publishWorkflowEvent({
212
297
  eventId: (0, crypto_1.randomUUID)(),
@@ -223,19 +308,23 @@ class WorkflowManager {
223
308
  return expiredCount;
224
309
  }
225
310
  async createWorkflowAssignment(instance, step, definition) {
311
+ if (!step.assignmentTemplate) {
312
+ throw new Error(`Assignment step "${step.id}" is missing assignmentTemplate`);
313
+ }
314
+ const targetUserSelector = step.targetUser ?? 'initiator';
226
315
  let targetUserId;
227
- if (step.targetUser === 'initiator') {
316
+ if (targetUserSelector === 'initiator') {
228
317
  targetUserId = instance.initiatorUserId;
229
318
  }
230
- else if (step.targetUser === 'previous') {
319
+ else if (targetUserSelector === 'previous') {
231
320
  const lastEntry = instance.history[instance.history.length - 1];
232
321
  targetUserId = lastEntry?.userId ?? instance.initiatorUserId;
233
322
  }
234
- else if (typeof step.targetUser === 'object' && 'tag' in step.targetUser) {
323
+ else if (typeof targetUserSelector === 'object' && 'tag' in targetUserSelector) {
235
324
  targetUserId = '';
236
325
  }
237
326
  else {
238
- targetUserId = step.targetUser;
327
+ targetUserId = targetUserSelector;
239
328
  }
240
329
  const assignmentId = (0, crypto_1.randomUUID)();
241
330
  const assignment = {
@@ -511,6 +600,9 @@ class WorkflowManager {
511
600
  type: 'COMPLETED',
512
601
  });
513
602
  }
603
+ else {
604
+ await this.saveInstance(instance, expectedVersion);
605
+ }
514
606
  return;
515
607
  }
516
608
  }
@@ -572,7 +664,7 @@ class WorkflowManager {
572
664
  const streamKey = this.keys.eventStream();
573
665
  let totalReclaimed = 0;
574
666
  try {
575
- const result = await this.subscriberClient.xAutoClaim(streamKey, this.options.streamConsumerGroup, this.options.streamConsumerName, this.options.reclaimIntervalMs, '0-0', { COUNT: 100 });
667
+ const result = await this.subscriberClient.xAutoClaim(streamKey, this.options.streamConsumerGroup, this.options.streamConsumerName, this.options.reclaimMinIdleMs ?? this.options.reclaimIntervalMs, '0-0', { COUNT: 100 });
576
668
  if (result && result.messages && result.messages.length > 0) {
577
669
  for (const message of result.messages) {
578
670
  if (!message)