@spekra.in/agent-os 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/Booker/README.md +41 -0
  2. package/Booker/package.json +11 -0
  3. package/Booker/src/agent.js +15 -0
  4. package/Booker/src/calendar-adapter.js +75 -0
  5. package/Booker/src/index.js +4 -0
  6. package/Booker/src/intake-parser.js +96 -0
  7. package/Booker/src/validation.js +34 -0
  8. package/Booker/test/booker.test.js +35 -0
  9. package/CashHound/README.md +181 -0
  10. package/CashHound/package.json +21 -0
  11. package/CashHound/src/agent.js +621 -0
  12. package/CashHound/src/bank-reconciler.js +66 -0
  13. package/CashHound/src/dunning.js +380 -0
  14. package/CashHound/src/index.js +32 -0
  15. package/CashHound/src/invoice.js +371 -0
  16. package/CashHound/src/mobile.js +35 -0
  17. package/CashHound/src/npv-optimizer.js +259 -0
  18. package/CashHound/test/advanced.test.js +44 -0
  19. package/CashHound/test/cashhound.test.js +530 -0
  20. package/CashHound/test/mobile.test.js +25 -0
  21. package/CashHound/test/security.test.js +35 -0
  22. package/Clerk/README.md +30 -0
  23. package/Clerk/package.json +11 -0
  24. package/Clerk/src/agent.js +18 -0
  25. package/Clerk/src/index.js +2 -0
  26. package/Clerk/src/reconciliation.js +52 -0
  27. package/Clerk/test/clerk.test.js +39 -0
  28. package/LocalRoar/README.md +37 -0
  29. package/LocalRoar/package.json +13 -0
  30. package/LocalRoar/src/agent.js +70 -0
  31. package/LocalRoar/src/booking-router.js +74 -0
  32. package/LocalRoar/src/feedback-interceptor.js +47 -0
  33. package/LocalRoar/src/index.js +7 -0
  34. package/LocalRoar/src/lead-engine.js +52 -0
  35. package/LocalRoar/src/mobile.js +23 -0
  36. package/LocalRoar/src/review-booster.js +24 -0
  37. package/LocalRoar/src/route-density.js +46 -0
  38. package/LocalRoar/test/advanced.test.js +41 -0
  39. package/LocalRoar/test/localroar.test.js +59 -0
  40. package/LocalRoar/test/mobile.test.js +12 -0
  41. package/OmniLife/README.md +39 -0
  42. package/OmniLife/package.json +13 -0
  43. package/OmniLife/src/agent.js +47 -0
  44. package/OmniLife/src/bill-negotiator.js +43 -0
  45. package/OmniLife/src/browser-cancel.js +28 -0
  46. package/OmniLife/src/conflict-engine.js +49 -0
  47. package/OmniLife/src/index.js +6 -0
  48. package/OmniLife/src/mobile.js +18 -0
  49. package/OmniLife/src/subscription-manager.js +66 -0
  50. package/OmniLife/test/advanced.test.js +29 -0
  51. package/OmniLife/test/mobile.test.js +12 -0
  52. package/OmniLife/test/omnilife.test.js +71 -0
  53. package/PulseMD/README.md +42 -0
  54. package/PulseMD/package.json +13 -0
  55. package/PulseMD/src/agent.js +67 -0
  56. package/PulseMD/src/ambient-scribe.js +46 -0
  57. package/PulseMD/src/auth.js +63 -0
  58. package/PulseMD/src/charting.js +54 -0
  59. package/PulseMD/src/index.js +7 -0
  60. package/PulseMD/src/mobile.js +18 -0
  61. package/PulseMD/src/prior-auth.js +39 -0
  62. package/PulseMD/src/safety-guard.js +88 -0
  63. package/PulseMD/test/advanced.test.js +50 -0
  64. package/PulseMD/test/mobile.test.js +12 -0
  65. package/PulseMD/test/pulsemd.test.js +71 -0
  66. package/README.md +208 -2
  67. package/ResolveX/README.md +274 -0
  68. package/ResolveX/package.json +20 -0
  69. package/ResolveX/src/agent.js +679 -0
  70. package/ResolveX/src/carrier-listener.js +405 -0
  71. package/ResolveX/src/diagnosis.js +315 -0
  72. package/ResolveX/src/index.js +36 -0
  73. package/ResolveX/src/mobile.js +31 -0
  74. package/ResolveX/src/policy.js +325 -0
  75. package/ResolveX/src/vision.js +384 -0
  76. package/ResolveX/test/advanced.test.js +445 -0
  77. package/ResolveX/test/mobile.test.js +15 -0
  78. package/ResolveX/test/resolvex.test.js +428 -0
  79. package/SentinelMesh/README.md +51 -0
  80. package/SentinelMesh/package.json +13 -0
  81. package/SentinelMesh/src/governor.js +61 -0
  82. package/SentinelMesh/src/index.js +4 -0
  83. package/SentinelMesh/src/mobile.js +19 -0
  84. package/SentinelMesh/src/policy.js +63 -0
  85. package/SentinelMesh/src/sandbox.js +152 -0
  86. package/SentinelMesh/test/mobile.test.js +12 -0
  87. package/SentinelMesh/test/sentinel.test.js +135 -0
  88. package/Sidekick/README.md +43 -0
  89. package/Sidekick/package.json +11 -0
  90. package/Sidekick/src/agent.js +15 -0
  91. package/Sidekick/src/evidence.js +45 -0
  92. package/Sidekick/src/index.js +3 -0
  93. package/Sidekick/src/validation.js +15 -0
  94. package/Sidekick/test/sidekick.test.js +33 -0
  95. package/agent-os-mobile/README.md +26 -0
  96. package/agent-os-mobile/src/api.js +97 -0
  97. package/agent-os-mobile/src/biometric.js +41 -0
  98. package/agent-os-mobile/src/components/ApprovalStack.js +207 -0
  99. package/agent-os-mobile/src/components/OutcomeCard.js +98 -0
  100. package/agent-os-mobile/src/memory-graph.js +114 -0
  101. package/agent-os-mobile/src/screens/CashHoundMobileScreen.js +111 -0
  102. package/agent-os-mobile/src/screens/LocalRoarMobileScreen.js +183 -0
  103. package/agent-os-mobile/src/screens/OmniLifeMobileScreen.js +111 -0
  104. package/agent-os-mobile/src/screens/PulseMDMobileScreen.js +55 -0
  105. package/agent-os-mobile/src/screens/ResolveXMobileScreen.js +96 -0
  106. package/agent-os-mobile/src/screens/SentinelMeshMobileScreen.js +199 -0
  107. package/agent-os-mobile/src/self-healer.js +104 -0
  108. package/agent-os-mobile/src/speculative-verifier.js +69 -0
  109. package/agent-os-mobile/src/spekra-bridge.js +216 -0
  110. package/agent-os-mobile/src/swarm.js +72 -0
  111. package/agent-os-mobile/src/voice.js +51 -0
  112. package/bin/agentos.js +338 -0
  113. package/package.json +52 -4
  114. package/src/index.js +95 -0
  115. package/src/llm-gateway.js +226 -0
@@ -0,0 +1,315 @@
1
+ /**
2
+ * ResolveX Incident Diagnosis Engine
3
+ * Classifies root causes, extracts facts, inspects telemetry/transactions,
4
+ * and assesses resolution eligibility.
5
+ */
6
+
7
+ export const IncidentType = Object.freeze({
8
+ SHIPPING_DELAY: 'SHIPPING_DELAY',
9
+ PRODUCT_DEFECT: 'PRODUCT_DEFECT',
10
+ DOUBLE_BILLING: 'DOUBLE_BILLING',
11
+ SERVICE_OUTAGE: 'SERVICE_OUTAGE',
12
+ INCORRECT_ITEM: 'INCORRECT_ITEM',
13
+ UNKNOWN: 'UNKNOWN',
14
+ });
15
+
16
+ export const DiagnosisSeverity = Object.freeze({
17
+ LOW: 'LOW',
18
+ MEDIUM: 'MEDIUM',
19
+ HIGH: 'HIGH',
20
+ CRITICAL: 'CRITICAL',
21
+ });
22
+
23
+ const PATTERNS = {
24
+ [IncidentType.DOUBLE_BILLING]: [
25
+ /charged twice/i,
26
+ /double bill(ing|ed)?/i,
27
+ /duplicate charge/i,
28
+ /billed (two|2) times/i,
29
+ /charged (two|2) times/i,
30
+ /two charges/i,
31
+ /multiple charges/i,
32
+ ],
33
+ [IncidentType.SHIPPING_DELAY]: [
34
+ /late/i,
35
+ /delay(ed)?/i,
36
+ /tracking.*stuck/i,
37
+ /where is my order/i,
38
+ /not arrived/i,
39
+ /hasn't arrived/i,
40
+ /past.*delivery/i,
41
+ /carrier.*lost/i,
42
+ /stuck in transit/i,
43
+ ],
44
+ [IncidentType.PRODUCT_DEFECT]: [
45
+ /broken/i,
46
+ /defect(ive)?/i,
47
+ /damaged/i,
48
+ /won'?t turn on/i,
49
+ /not working/i,
50
+ /hardware failure/i,
51
+ /dead on arrival/i,
52
+ /malfunction/i,
53
+ /faulty/i,
54
+ /cracked/i,
55
+ ],
56
+ [IncidentType.SERVICE_OUTAGE]: [
57
+ /outage/i,
58
+ /service (is )?down/i,
59
+ /downtime/i,
60
+ /can'?t access/i,
61
+ /server error/i,
62
+ /system.*unavailable/i,
63
+ /503/i,
64
+ /api error/i,
65
+ /service disruption/i,
66
+ ],
67
+ [IncidentType.INCORRECT_ITEM]: [
68
+ /wrong item/i,
69
+ /wrong (product|color|size)/i,
70
+ /missing item/i,
71
+ /received incorrect/i,
72
+ /different item/i,
73
+ ],
74
+ };
75
+
76
+ export class DiagnosisEngine {
77
+ /**
78
+ * Classify text intent and return best match with confidence.
79
+ */
80
+ classifyText(text = '') {
81
+ if (!text || typeof text !== 'string') {
82
+ return { type: IncidentType.UNKNOWN, confidence: 0 };
83
+ }
84
+
85
+ const matches = [];
86
+
87
+ for (const [type, patterns] of Object.entries(PATTERNS)) {
88
+ let hits = 0;
89
+ for (const pattern of patterns) {
90
+ if (pattern.test(text)) {
91
+ hits++;
92
+ }
93
+ }
94
+ if (hits > 0) {
95
+ // Normalize confidence between 0.6 and 0.95
96
+ const confidence = Math.min(0.95, 0.6 + hits * 0.15);
97
+ matches.push({ type, confidence, hits });
98
+ }
99
+ }
100
+
101
+ if (matches.length === 0) {
102
+ return { type: IncidentType.UNKNOWN, confidence: 0.2 };
103
+ }
104
+
105
+ matches.sort((a, b) => b.hits - a.hits || b.confidence - a.confidence);
106
+ return matches[0];
107
+ }
108
+
109
+ /**
110
+ * Deep diagnosis combining telemetry, transactions, tracking, and text description.
111
+ */
112
+ diagnose(issue = {}, context = {}) {
113
+ const textClassification = this.classifyText(issue.description || issue.subject || '');
114
+ const statedType = issue.type && IncidentType[issue.type] ? issue.type : null;
115
+
116
+ let rootCause = statedType || textClassification.type;
117
+ let confidence = statedType ? 0.9 : textClassification.confidence;
118
+ const verifiedFacts = [];
119
+ const evidence = {};
120
+
121
+ // 1. Double Billing Verification
122
+ if (rootCause === IncidentType.DOUBLE_BILLING || (!statedType && context.transactions?.length > 1)) {
123
+ const duplicateAnalysis = this._verifyDoubleBilling(context.transactions, issue.amount);
124
+ if (duplicateAnalysis.isDuplicate) {
125
+ rootCause = IncidentType.DOUBLE_BILLING;
126
+ confidence = Math.max(confidence, 0.98);
127
+ verifiedFacts.push(`Detected duplicate charge of $${duplicateAnalysis.duplicateAmount} on ${duplicateAnalysis.date}`);
128
+ evidence.duplicateTransaction = duplicateAnalysis;
129
+ }
130
+ }
131
+
132
+ // 2. Shipping Delay Verification
133
+ if (rootCause === IncidentType.SHIPPING_DELAY || (!statedType && context.shipment)) {
134
+ const shippingAnalysis = this._verifyShippingDelay(context.shipment, context.currentDate);
135
+ if (shippingAnalysis.isDelayed) {
136
+ rootCause = IncidentType.SHIPPING_DELAY;
137
+ confidence = Math.max(confidence, 0.95);
138
+ verifiedFacts.push(`Shipment delayed by ${shippingAnalysis.daysLate} day(s); status: ${shippingAnalysis.carrierStatus}`);
139
+ evidence.shipping = shippingAnalysis;
140
+ }
141
+ }
142
+
143
+ // 3. Service Outage Verification
144
+ if (rootCause === IncidentType.SERVICE_OUTAGE || (!statedType && context.systemOutages?.length > 0)) {
145
+ const outageAnalysis = this._verifyServiceOutage(context.systemOutages, issue.timestamp);
146
+ if (outageAnalysis.isImpacted) {
147
+ rootCause = IncidentType.SERVICE_OUTAGE;
148
+ confidence = Math.max(confidence, 0.96);
149
+ verifiedFacts.push(`Confirmed service outage on ${outageAnalysis.service} during user timeframe (duration: ${outageAnalysis.durationHours}h)`);
150
+ evidence.outage = outageAnalysis;
151
+ }
152
+ }
153
+
154
+ // 4. Product Defect Verification
155
+ if (rootCause === IncidentType.PRODUCT_DEFECT) {
156
+ const defectAnalysis = this._verifyProductDefect(issue, context.deviceTelemetry);
157
+ confidence = Math.max(confidence, defectAnalysis.confirmed ? 0.92 : 0.75);
158
+ if (defectAnalysis.confirmed) {
159
+ verifiedFacts.push(`Hardware telemetry confirms defect: ${defectAnalysis.errorCode}`);
160
+ } else {
161
+ verifiedFacts.push('Customer reported defect without conflicting telemetry');
162
+ }
163
+ evidence.defect = defectAnalysis;
164
+ }
165
+
166
+ // Determine Severity
167
+ const severity = this._determineSeverity(rootCause, issue, evidence);
168
+
169
+ // Resolution Eligibility Assessment
170
+ const eligibility = this._determineEligibility(rootCause, severity, evidence);
171
+
172
+ return {
173
+ rootCause,
174
+ confidence: Number(confidence.toFixed(2)),
175
+ severity,
176
+ verifiedFacts,
177
+ evidence,
178
+ eligibility,
179
+ summary: this._generateSummary(rootCause, severity, verifiedFacts),
180
+ };
181
+ }
182
+
183
+ _verifyDoubleBilling(transactions = [], requestedAmount = null) {
184
+ if (!transactions || transactions.length < 2) {
185
+ return { isDuplicate: false };
186
+ }
187
+
188
+ // Find pairs with identical amount and same currency within 48h
189
+ for (let i = 0; i < transactions.length; i++) {
190
+ for (let j = i + 1; j < transactions.length; j++) {
191
+ const t1 = transactions[i];
192
+ const t2 = transactions[j];
193
+ const sameAmount = Math.abs(t1.amount - t2.amount) < 0.01;
194
+ const matchesRequested = requestedAmount ? Math.abs(t1.amount - requestedAmount) < 0.01 : true;
195
+
196
+ if (sameAmount && matchesRequested) {
197
+ const d1 = new Date(t1.timestamp || t1.date);
198
+ const d2 = new Date(t2.timestamp || t2.date);
199
+ const diffHours = Math.abs(d1.getTime() - d2.getTime()) / (1000 * 60 * 60);
200
+
201
+ if (diffHours <= 72) {
202
+ return {
203
+ isDuplicate: true,
204
+ originalTxId: t1.id,
205
+ duplicateTxId: t2.id,
206
+ duplicateAmount: t2.amount,
207
+ date: t2.date || t2.timestamp,
208
+ hoursApart: Number(diffHours.toFixed(1)),
209
+ };
210
+ }
211
+ }
212
+ }
213
+ }
214
+
215
+ return { isDuplicate: false };
216
+ }
217
+
218
+ _verifyShippingDelay(shipment, refDate = new Date()) {
219
+ if (!shipment) return { isDelayed: false };
220
+
221
+ const edd = shipment.estimatedDeliveryDate ? new Date(shipment.estimatedDeliveryDate) : null;
222
+ const now = new Date(refDate);
223
+
224
+ let isDelayed = false;
225
+ let daysLate = 0;
226
+
227
+ if (edd && now > edd && shipment.status !== 'DELIVERED') {
228
+ isDelayed = true;
229
+ daysLate = Math.floor((now.getTime() - edd.getTime()) / (1000 * 60 * 60 * 24));
230
+ } else if (shipment.status === 'DELAYED' || shipment.status === 'EXCEPTION' || shipment.status === 'STUCK') {
231
+ isDelayed = true;
232
+ daysLate = shipment.daysLate || 2;
233
+ }
234
+
235
+ return {
236
+ isDelayed,
237
+ daysLate,
238
+ carrierStatus: shipment.status || 'UNKNOWN',
239
+ carrier: shipment.carrier || 'Standard Carrier',
240
+ trackingNumber: shipment.trackingNumber,
241
+ estimatedDeliveryDate: shipment.estimatedDeliveryDate,
242
+ };
243
+ }
244
+
245
+ _verifyServiceOutage(outages = [], issueTimestamp = null) {
246
+ if (!outages || outages.length === 0) return { isImpacted: false };
247
+
248
+ const targetTime = issueTimestamp ? new Date(issueTimestamp).getTime() : Date.now();
249
+
250
+ for (const outage of outages) {
251
+ const start = new Date(outage.startTime).getTime();
252
+ const end = outage.endTime ? new Date(outage.endTime).getTime() : Date.now();
253
+
254
+ if (targetTime >= start && targetTime <= end + 3600000) {
255
+ return {
256
+ isImpacted: true,
257
+ incidentId: outage.id,
258
+ service: outage.service,
259
+ durationHours: outage.durationHours || Number(((end - start) / 3600000).toFixed(1)),
260
+ description: outage.description,
261
+ };
262
+ }
263
+ }
264
+
265
+ return { isImpacted: false };
266
+ }
267
+
268
+ _verifyProductDefect(issue, telemetry) {
269
+ if (telemetry && telemetry.diagnosticFailed) {
270
+ return {
271
+ confirmed: true,
272
+ errorCode: telemetry.errorCode || 'HW_FAULT_DETECTED',
273
+ component: telemetry.faultyComponent || 'Mainboard',
274
+ };
275
+ }
276
+ return {
277
+ confirmed: false,
278
+ reportedDescription: issue.description,
279
+ };
280
+ }
281
+
282
+ _determineSeverity(rootCause, issue, evidence) {
283
+ if (issue.severity && DiagnosisSeverity[issue.severity]) {
284
+ return issue.severity;
285
+ }
286
+
287
+ switch (rootCause) {
288
+ case IncidentType.DOUBLE_BILLING:
289
+ return evidence.duplicateTransaction?.duplicateAmount > 200 ? DiagnosisSeverity.HIGH : DiagnosisSeverity.MEDIUM;
290
+ case IncidentType.SERVICE_OUTAGE:
291
+ return DiagnosisSeverity.HIGH;
292
+ case IncidentType.SHIPPING_DELAY:
293
+ return (evidence.shipping?.daysLate || 0) >= 5 ? DiagnosisSeverity.HIGH : DiagnosisSeverity.MEDIUM;
294
+ case IncidentType.PRODUCT_DEFECT:
295
+ return DiagnosisSeverity.HIGH;
296
+ default:
297
+ return DiagnosisSeverity.LOW;
298
+ }
299
+ }
300
+
301
+ _determineEligibility(rootCause, severity, evidence) {
302
+ return {
303
+ canRefund: rootCause === IncidentType.DOUBLE_BILLING || rootCause === IncidentType.PRODUCT_DEFECT,
304
+ canReplace: rootCause === IncidentType.PRODUCT_DEFECT || rootCause === IncidentType.INCORRECT_ITEM,
305
+ canCredit: true, // Apology credit can be applied across incidents
306
+ canDispatchTech: rootCause === IncidentType.PRODUCT_DEFECT && severity === DiagnosisSeverity.HIGH,
307
+ requiresCarrierInquiry: rootCause === IncidentType.SHIPPING_DELAY,
308
+ };
309
+ }
310
+
311
+ _generateSummary(rootCause, severity, facts) {
312
+ const factText = facts.length > 0 ? ` Verified signals: ${facts.join('; ')}.` : '';
313
+ return `Diagnosed incident as [${rootCause}] with severity [${severity}].${factText}`;
314
+ }
315
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * ResolveX - Autonomous Customer Resolution Agent
3
+ * Entry Point & Exports
4
+ */
5
+
6
+ export {
7
+ PolicyEngine,
8
+ CustomerTier,
9
+ IssueSeverity,
10
+ DEFAULT_POLICY_CONFIG,
11
+ } from './policy.js';
12
+
13
+ export {
14
+ DiagnosisEngine,
15
+ IncidentType,
16
+ DiagnosisSeverity,
17
+ } from './diagnosis.js';
18
+
19
+ export {
20
+ ResolveXAgent,
21
+ ResolutionStatus,
22
+ ActionType,
23
+ } from './agent.js';
24
+
25
+ export { ResolveXMobileAdapter } from './mobile.js';
26
+
27
+ export {
28
+ DamageVerifier,
29
+ DamageType,
30
+ DamageVerificationStatus,
31
+ } from './vision.js';
32
+
33
+ export {
34
+ CarrierWebhookListener,
35
+ CarrierExceptionType,
36
+ } from './carrier-listener.js';
@@ -0,0 +1,31 @@
1
+ /**
2
+ * ResolveX Mobile Adapter: Provides mobile outcome cards & supervisor ticket queues.
3
+ */
4
+
5
+ export class ResolveXMobileAdapter {
6
+ constructor(agent) {
7
+ this.agent = agent;
8
+ }
9
+
10
+ getMobileOutcomeCard() {
11
+ const closed = this.agent.auditLog.filter(l => l.action === 'RESOLUTION_EXECUTED').length;
12
+ const tickets = this.agent.getPendingApprovals();
13
+
14
+ return {
15
+ title: 'ResolveX Autonomous Care',
16
+ outcomeMetric: `${closed} Resolved`,
17
+ pendingSupervisorTickets: tickets.length,
18
+ statusBadge: 'ONLINE_24_7'
19
+ };
20
+ }
21
+
22
+ getMobileTicketQueue() {
23
+ return this.agent.getPendingApprovals().map(t => ({
24
+ id: t.id,
25
+ customerName: t.customer?.name || 'Customer',
26
+ issueType: t.diagnosis?.type || 'Inquiry',
27
+ amountFormatted: t.proposedResolution?.refundAmount ? `$${t.proposedResolution.refundAmount.toFixed(2)}` : null,
28
+ reason: t.escalationReason || 'Supervisor approval threshold reached'
29
+ }));
30
+ }
31
+ }
@@ -0,0 +1,325 @@
1
+ /**
2
+ * ResolveX Resolution Policy Engine
3
+ * Governs thresholds, warranty validation, replacement criteria,
4
+ * voucher/credit multipliers, risk evaluation, and human-in-the-loop triggers.
5
+ */
6
+
7
+ export const CustomerTier = Object.freeze({
8
+ STANDARD: 'STANDARD',
9
+ BRONZE: 'BRONZE',
10
+ SILVER: 'SILVER',
11
+ GOLD: 'GOLD',
12
+ PLATINUM: 'PLATINUM',
13
+ });
14
+
15
+ export const IssueSeverity = Object.freeze({
16
+ LOW: 'LOW',
17
+ MEDIUM: 'MEDIUM',
18
+ HIGH: 'HIGH',
19
+ CRITICAL: 'CRITICAL',
20
+ });
21
+
22
+ export const DEFAULT_POLICY_CONFIG = Object.freeze({
23
+ autonomousRefundLimit: 100.0,
24
+ maxRefundLimit: 1500.0,
25
+ standardReturnWindowDays: 30,
26
+ standardWarrantyDays: 365,
27
+ maxAutonomousReplacementsPerYear: 2,
28
+ maxAutonomousRiskScore: 0.35,
29
+ tierVoucherMultipliers: {
30
+ [CustomerTier.STANDARD]: 1.0,
31
+ [CustomerTier.BRONZE]: 1.1,
32
+ [CustomerTier.SILVER]: 1.25,
33
+ [CustomerTier.GOLD]: 1.5,
34
+ [CustomerTier.PLATINUM]: 2.0,
35
+ },
36
+ severityBaseCredits: {
37
+ [IssueSeverity.LOW]: 10.0,
38
+ [IssueSeverity.MEDIUM]: 25.0,
39
+ [IssueSeverity.HIGH]: 50.0,
40
+ [IssueSeverity.CRITICAL]: 100.0,
41
+ },
42
+ });
43
+
44
+ export class PolicyEngine {
45
+ constructor(customConfig = {}) {
46
+ this.config = {
47
+ ...DEFAULT_POLICY_CONFIG,
48
+ ...customConfig,
49
+ tierVoucherMultipliers: {
50
+ ...DEFAULT_POLICY_CONFIG.tierVoucherMultipliers,
51
+ ...(customConfig.tierVoucherMultipliers || {}),
52
+ },
53
+ severityBaseCredits: {
54
+ ...DEFAULT_POLICY_CONFIG.severityBaseCredits,
55
+ ...(customConfig.severityBaseCredits || {}),
56
+ },
57
+ };
58
+ }
59
+
60
+ /**
61
+ * Validate warranty or return window against reference date.
62
+ */
63
+ validateWarranty({ purchaseDate, warrantyDays = this.config.standardWarrantyDays, referenceDate = new Date() }) {
64
+ if (!purchaseDate) {
65
+ return {
66
+ valid: false,
67
+ daysSincePurchase: null,
68
+ remainingDays: 0,
69
+ isExpired: true,
70
+ reason: 'Missing purchase date',
71
+ };
72
+ }
73
+
74
+ const pDate = new Date(purchaseDate);
75
+ const refDate = new Date(referenceDate);
76
+ const msDiff = refDate.getTime() - pDate.getTime();
77
+ const daysSincePurchase = Math.floor(msDiff / (1000 * 60 * 60 * 24));
78
+
79
+ if (daysSincePurchase < 0) {
80
+ return {
81
+ valid: false,
82
+ daysSincePurchase,
83
+ remainingDays: 0,
84
+ isExpired: false,
85
+ reason: 'Purchase date is in the future',
86
+ };
87
+ }
88
+
89
+ const remainingDays = warrantyDays - daysSincePurchase;
90
+ const isExpired = remainingDays < 0;
91
+
92
+ return {
93
+ valid: !isExpired,
94
+ daysSincePurchase,
95
+ remainingDays: Math.max(0, remainingDays),
96
+ isExpired,
97
+ reason: isExpired
98
+ ? `Warranty expired ${Math.abs(remainingDays)} day(s) ago (Window: ${warrantyDays} days)`
99
+ : `Within warranty period (${remainingDays} days remaining)`,
100
+ };
101
+ }
102
+
103
+ /**
104
+ * Evaluate customer risk and fraud indicators.
105
+ */
106
+ evaluateRisk({ customerProfile = {}, incidentHistory = [] }) {
107
+ const flags = [];
108
+ let riskScore = 0.05; // Baseline trust
109
+
110
+ const accountAgeDays = customerProfile.accountAgeDays ?? 180;
111
+ if (accountAgeDays < 14) {
112
+ riskScore += 0.25;
113
+ flags.push('New account (<14 days)');
114
+ } else if (accountAgeDays < 30) {
115
+ riskScore += 0.1;
116
+ flags.push('Young account (<30 days)');
117
+ }
118
+
119
+ const pastClaims = incidentHistory.filter((i) => i.resolvedWith === 'REFUND' || i.resolvedWith === 'REPLACEMENT');
120
+ if (pastClaims.length >= 4) {
121
+ riskScore += 0.35;
122
+ flags.push(`High claim frequency (${pastClaims.length} prior claims)`);
123
+ } else if (pastClaims.length >= 2) {
124
+ riskScore += 0.15;
125
+ flags.push(`Multiple past claims (${pastClaims.length})`);
126
+ }
127
+
128
+ if (customerProfile.flaggedForAbuse) {
129
+ riskScore += 0.5;
130
+ flags.push('Account previously flagged for abuse review');
131
+ }
132
+
133
+ if (customerProfile.chargebackCount && customerProfile.chargebackCount > 0) {
134
+ riskScore += 0.4;
135
+ flags.push(`Chargeback history detected (${customerProfile.chargebackCount})`);
136
+ }
137
+
138
+ riskScore = Math.min(1.0, Math.max(0.0, Number(riskScore.toFixed(2))));
139
+
140
+ let riskLevel = 'LOW';
141
+ if (riskScore >= 0.6) {
142
+ riskLevel = 'HIGH';
143
+ } else if (riskScore >= 0.3) {
144
+ riskLevel = 'MEDIUM';
145
+ }
146
+
147
+ const allowsAutonomousAction = riskScore <= this.config.maxAutonomousRiskScore;
148
+
149
+ return {
150
+ riskScore,
151
+ riskLevel,
152
+ flagExceptions: flags,
153
+ allowsAutonomousAction,
154
+ };
155
+ }
156
+
157
+ /**
158
+ * Validate refund eligibility and whether it can proceed autonomously.
159
+ */
160
+ validateRefund({
161
+ amount,
162
+ orderTotal = null,
163
+ customerProfile = {},
164
+ incidentHistory = [],
165
+ isSpecialException = false,
166
+ }) {
167
+ if (typeof amount !== 'number' || isNaN(amount) || amount <= 0) {
168
+ return {
169
+ allowed: false,
170
+ allowedAutonomous: false,
171
+ requiresApproval: false,
172
+ reason: 'Refund amount must be a positive number',
173
+ };
174
+ }
175
+
176
+ if (orderTotal !== null && amount > orderTotal + 0.001) {
177
+ return {
178
+ allowed: false,
179
+ allowedAutonomous: false,
180
+ requiresApproval: true,
181
+ reason: `Refund amount ($${amount}) exceeds total order value ($${orderTotal})`,
182
+ };
183
+ }
184
+
185
+ if (amount > this.config.maxRefundLimit) {
186
+ return {
187
+ allowed: false,
188
+ allowedAutonomous: false,
189
+ requiresApproval: true,
190
+ reason: `Refund amount ($${amount}) exceeds maximum allowable system limit ($${this.config.maxRefundLimit})`,
191
+ };
192
+ }
193
+
194
+ const risk = this.evaluateRisk({ customerProfile, incidentHistory });
195
+
196
+ if (!risk.allowsAutonomousAction) {
197
+ return {
198
+ allowed: true,
199
+ allowedAutonomous: false,
200
+ requiresApproval: true,
201
+ reason: `Customer risk level (${risk.riskLevel}, score ${risk.riskScore}) requires human approval: ${risk.flagExceptions.join(', ')}`,
202
+ risk,
203
+ };
204
+ }
205
+
206
+ if (isSpecialException) {
207
+ return {
208
+ allowed: true,
209
+ allowedAutonomous: false,
210
+ requiresApproval: true,
211
+ reason: 'Special policy exception flagged for supervisor review',
212
+ risk,
213
+ };
214
+ }
215
+
216
+ if (amount <= this.config.autonomousRefundLimit) {
217
+ return {
218
+ allowed: true,
219
+ allowedAutonomous: true,
220
+ requiresApproval: false,
221
+ reason: `Amount ($${amount}) within autonomous threshold ($${this.config.autonomousRefundLimit})`,
222
+ risk,
223
+ };
224
+ }
225
+
226
+ return {
227
+ allowed: true,
228
+ allowedAutonomous: false,
229
+ requiresApproval: true,
230
+ reason: `Amount ($${amount}) exceeds autonomous refund threshold ($${this.config.autonomousRefundLimit}); requires agent approval`,
231
+ risk,
232
+ };
233
+ }
234
+
235
+ /**
236
+ * Validate product replacement request.
237
+ */
238
+ validateReplacement({
239
+ product = {},
240
+ purchaseDate,
241
+ stockAvailable = true,
242
+ customerProfile = {},
243
+ incidentHistory = [],
244
+ }) {
245
+ if (!stockAvailable) {
246
+ return {
247
+ eligible: false,
248
+ allowedAutonomous: false,
249
+ requiresApproval: true,
250
+ reason: 'Item is out of stock; alternate resolution or backorder review required',
251
+ };
252
+ }
253
+
254
+ const warranty = this.validateWarranty({
255
+ purchaseDate,
256
+ warrantyDays: product.warrantyDays || this.config.standardWarrantyDays,
257
+ });
258
+
259
+ if (!warranty.valid) {
260
+ return {
261
+ eligible: false,
262
+ allowedAutonomous: false,
263
+ requiresApproval: true,
264
+ reason: `Product is outside warranty period: ${warranty.reason}`,
265
+ warranty,
266
+ };
267
+ }
268
+
269
+ const risk = this.evaluateRisk({ customerProfile, incidentHistory });
270
+ const pastReplacements = incidentHistory.filter((i) => i.resolvedWith === 'REPLACEMENT');
271
+
272
+ if (pastReplacements.length >= this.config.maxAutonomousReplacementsPerYear) {
273
+ return {
274
+ eligible: true,
275
+ allowedAutonomous: false,
276
+ requiresApproval: true,
277
+ reason: `Customer exceeded autonomous replacement frequency limit (${pastReplacements.length}/${this.config.maxAutonomousReplacementsPerYear})`,
278
+ risk,
279
+ warranty,
280
+ };
281
+ }
282
+
283
+ if (!risk.allowsAutonomousAction) {
284
+ return {
285
+ eligible: true,
286
+ allowedAutonomous: false,
287
+ requiresApproval: true,
288
+ reason: `Customer risk profile requires human approval for replacement: ${risk.flagExceptions.join(', ')}`,
289
+ risk,
290
+ warranty,
291
+ };
292
+ }
293
+
294
+ return {
295
+ eligible: true,
296
+ allowedAutonomous: true,
297
+ requiresApproval: false,
298
+ reason: 'Valid warranty, item in stock, and risk criteria satisfied for autonomous replacement',
299
+ risk,
300
+ warranty,
301
+ };
302
+ }
303
+
304
+ /**
305
+ * Calculate apology voucher or credit based on severity and loyalty tier.
306
+ */
307
+ calculateApologyCredit({ severity = IssueSeverity.MEDIUM, customerTier = CustomerTier.STANDARD, customBase = null }) {
308
+ const tier = customerTier.toUpperCase();
309
+ const multiplier = this.config.tierVoucherMultipliers[tier] ?? 1.0;
310
+ const base = customBase !== null
311
+ ? customBase
312
+ : (this.config.severityBaseCredits[severity] ?? this.config.severityBaseCredits[IssueSeverity.MEDIUM]);
313
+
314
+ const finalAmount = Number((base * multiplier).toFixed(2));
315
+
316
+ return {
317
+ amount: finalAmount,
318
+ currency: 'USD',
319
+ customerTier: tier,
320
+ multiplier,
321
+ severity,
322
+ breakdown: `Base $${base} x ${multiplier} (${tier} tier) = $${finalAmount}`,
323
+ };
324
+ }
325
+ }