File size: 10,699 Bytes
9646e24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import { nanoid } from "nanoid";
import {
  StrategyAssignment,
  StrategyGenome,
  StrategyPortfolio,
  RoleType,
  AssignmentReason,
  StrategyClass,
  StrategyContextCondition,
} from "@/types";
import { loadStrategyAssignments, saveStrategyAssignments, loadStrategies } from "@/lib/config";
import { ensureStrategiesSeeded, listStrategiesByRole } from "@/lib/strategy/library";

const now = () => new Date().toISOString();

const MAX_PROVEN = 3;
const MAX_PERSONALIZED = 2;
const MAX_EXPERIMENTAL = 1;
const TARGET_EXPLORE_RATIO = 0.3;

// ─── Context Matching ──────────────────────────────────────────────

export interface EmployeeContext {
  employeeId: string;
  role: RoleType;
  territoryType?: string;
  workloadLevel?: "low" | "medium" | "high";
  stakeholderSegment?: string;
  productPortfolio?: string[];
}

function contextMatches(
  conditions: StrategyContextCondition[],
  ctx: EmployeeContext
): boolean {
  if (conditions.length === 0) return true;
  return conditions.every((c) => {
    let actualValue: unknown;
    switch (c.field) {
      case "role":
        actualValue = ctx.role;
        break;
      case "territory_type":
        actualValue = ctx.territoryType || "geographic";
        break;
      case "workload_level":
        actualValue = ctx.workloadLevel || "medium";
        break;
      case "stakeholder_segment":
        actualValue = ctx.stakeholderSegment || "mixed";
        break;
      case "product_portfolio":
        actualValue = ctx.productPortfolio || [];
        break;
      default:
        return true;
    }

    switch (c.operator) {
      case "equals":
        return actualValue === c.value;
      case "contains":
        if (typeof actualValue === "string" && typeof c.value === "string") {
          return actualValue.includes(c.value);
        }
        if (Array.isArray(actualValue) && typeof c.value === "string") {
          return actualValue.includes(c.value);
        }
        return false;
      case "in_range":
        if (Array.isArray(c.value) && typeof actualValue === "string") {
          return c.value.includes(actualValue);
        }
        return false;
      case "greater_than":
        return typeof actualValue === "number" && typeof c.value === "number" && actualValue > c.value;
      case "less_than":
        return typeof actualValue === "number" && typeof c.value === "number" && actualValue < c.value;
      default:
        return true;
    }
  });
}

// ─── Assignment Store ──────────────────────────────────────────────

export function listAssignments(): StrategyAssignment[] {
  return loadStrategyAssignments();
}

export function getAssignmentsForEmployee(employeeId: string): StrategyAssignment[] {
  return loadStrategyAssignments().filter((a) => a.employeeId === employeeId && a.active);
}

export function getAssignmentById(id: string): StrategyAssignment | undefined {
  return loadStrategyAssignments().find((a) => a.id === id);
}

export function upsertAssignment(assignment: StrategyAssignment): void {
  const all = loadStrategyAssignments();
  const idx = all.findIndex((a) => a.id === assignment.id);
  if (idx >= 0) {
    all[idx] = assignment;
  } else {
    all.push(assignment);
  }
  saveStrategyAssignments(all);
}

export function deactivateAssignment(id: string): void {
  const all = loadStrategyAssignments();
  const idx = all.findIndex((a) => a.id === id);
  if (idx >= 0) {
    all[idx].active = false;
    all[idx].deactivatedAt = now();
    saveStrategyAssignments(all);
  }
}

// ─── Explore-vs-Exploit Engine ─────────────────────────────────────

export function computeExploreRatio(assignments: StrategyAssignment[]): number {
  if (assignments.length === 0) return 0;
  const exploreCount = assignments.filter(
    (a) => a.assignmentReason === "explore" || a.strategyClass === "experimental"
  ).length;
  return exploreCount / assignments.length;
}

export function shouldExplore(
  currentAssignments: StrategyAssignment[],
  candidateClass: StrategyClass
): boolean {
  const exploreRatio = computeExploreRatio(currentAssignments);
  if (exploreRatio >= TARGET_EXPLORE_RATIO) return false;
  return candidateClass === "experimental" || candidateClass === "personalized";
}

// ─── Assignment Engine ─────────────────────────────────────────────

export function assignStrategies(ctx: EmployeeContext): StrategyAssignment[] {
  ensureStrategiesSeeded();

  const existing = getAssignmentsForEmployee(ctx.employeeId);
  const newAssignments: StrategyAssignment[] = [];

  const candidates = listStrategiesByRole(ctx.role).filter(
    (s) => !existing.some((a) => a.strategyId === s.id)
  );

  const contextMatched = candidates.filter((s) => contextMatches(s.applicableContext, ctx));
  const pool = contextMatched.length > 0 ? contextMatched : candidates;

  const byClass: Record<StrategyClass, StrategyGenome[]> = {
    proven: pool.filter((s) => s.strategyClass === "proven"),
    personalized: pool.filter((s) => s.strategyClass === "personalized"),
    experimental: pool.filter((s) => s.strategyClass === "experimental"),
  };

  // Assign proven strategies (exploit)
  const provenToAssign = Math.min(
    MAX_PROVEN - existing.filter((a) => a.strategyClass === "proven").length,
    byClass.proven.length
  );
  for (let i = 0; i < Math.max(0, provenToAssign); i++) {
    const strategy = byClass.proven[i];
    const assignment = createAssignment(strategy, ctx, "exploit", existing.length + newAssignments.length + 1);
    newAssignments.push(assignment);
    upsertAssignment(assignment);
  }

  // Assign personalized strategies
  const personalizedToAssign = Math.min(
    MAX_PERSONALIZED - existing.filter((a) => a.strategyClass === "personalized").length,
    byClass.personalized.length
  );
  for (let i = 0; i < Math.max(0, personalizedToAssign); i++) {
    const strategy = byClass.personalized[i];
    const reason: AssignmentReason = shouldExplore([...existing, ...newAssignments], "personalized")
      ? "personalized_fit"
      : "exploit";
    const assignment = createAssignment(strategy, ctx, reason, existing.length + newAssignments.length + 1);
    newAssignments.push(assignment);
    upsertAssignment(assignment);
  }

  // Assign experimental strategies (explore)
  const updatedAll = [...existing, ...newAssignments];
  if (shouldExplore(updatedAll, "experimental")) {
    const experimentalToAssign = Math.min(
      MAX_EXPERIMENTAL - existing.filter((a) => a.strategyClass === "experimental").length,
      byClass.experimental.length
    );
    for (let i = 0; i < Math.max(0, experimentalToAssign); i++) {
      const strategy = byClass.experimental[i];
      const assignment = createAssignment(strategy, ctx, "explore", existing.length + newAssignments.length + 1);
      newAssignments.push(assignment);
      upsertAssignment(assignment);
    }
  }

  return newAssignments;
}

function createAssignment(
  strategy: StrategyGenome,
  ctx: EmployeeContext,
  reason: AssignmentReason,
  trialNumber: number
): StrategyAssignment {
  return {
    id: nanoid(12),
    strategyId: strategy.id,
    employeeId: ctx.employeeId,
    employeeRole: ctx.role,
    strategyClass: strategy.strategyClass,
    assignmentReason: reason,
    assignedAt: now(),
    active: true,
    employeeAccepted: false,
    employeeModified: false,
    expectedOutcomeMetrics: strategy.expectedOutcomes.map((m) => ({ ...m })),
    contextSnapshot: {
      territoryType: ctx.territoryType,
      workloadLevel: ctx.workloadLevel,
      stakeholderSegment: ctx.stakeholderSegment,
      productPortfolio: ctx.productPortfolio,
    },
    trialNumber,
    confidenceAtAssignment: strategy.evidenceLevel === "experimentally_supported"
      ? 0.85
      : strategy.evidenceLevel === "probable_contribution"
        ? 0.65
        : strategy.evidenceLevel === "observed_association"
          ? 0.45
          : 0.25,
  };
}

// ─── Portfolio Generation ──────────────────────────────────────────

export function computeDiversityScore(assignments: StrategyAssignment[], strategies: StrategyGenome[]): number {
  if (assignments.length === 0) return 0;
  const domains = new Set<string>();
  for (const a of assignments) {
    const s = strategies.find((s) => s.id === a.strategyId);
    if (s) domains.add(s.domain);
  }
  return Math.round((domains.size / 8) * 100) / 100;
}

export function getPortfolio(employeeId: string, role: RoleType): StrategyPortfolio {
  ensureStrategiesSeeded();
  const allStrategies = loadStrategies();
  const active = getAssignmentsForEmployee(employeeId);

  const proven = active.filter((a) => a.strategyClass === "proven");
  const personalized = active.filter((a) => a.strategyClass === "personalized");
  const experimental = active.filter((a) => a.strategyClass === "experimental");

  const exploreRatio = computeExploreRatio(active);
  const exploitRatio = 1 - exploreRatio;
  const diversity = computeDiversityScore(active, allStrategies);

  return {
    employeeId,
    employeeRole: role,
    activeAssignments: active,
    provenStrategies: proven,
    personalizedStrategies: personalized,
    experimentalStrategies: experimental,
    portfolioDiversityScore: diversity,
    exploreRatio,
    exploitRatio,
    lastRebalancedAt: now(),
  };
}

// ─── Employee Acceptance ───────────────────────────────────────────

export function acceptAssignment(id: string): StrategyAssignment | undefined {
  const all = loadStrategyAssignments();
  const idx = all.findIndex((a) => a.id === id);
  if (idx < 0) return undefined;
  all[idx].employeeAccepted = true;
  saveStrategyAssignments(all);
  return all[idx];
}

export function modifyAssignment(id: string, notes: string): StrategyAssignment | undefined {
  const all = loadStrategyAssignments();
  const idx = all.findIndex((a) => a.id === id);
  if (idx < 0) return undefined;
  all[idx].employeeModified = true;
  all[idx].modificationNotes = notes;
  saveStrategyAssignments(all);
  return all[idx];
}

export function rejectAssignment(id: string): StrategyAssignment | undefined {
  deactivateAssignment(id);
  const all = loadStrategyAssignments();
  return all.find((a) => a.id === id);
}