@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,679 @@
1
+ /**
2
+ * ResolveX Agent - Autonomous Customer Resolution Decision Engine
3
+ * Orchestrates diagnosis, policy guardrails, autonomous low-risk execution,
4
+ * and human-in-the-loop (HITL) escalation workflows.
5
+ */
6
+
7
+ import crypto from 'node:crypto';
8
+ import { PolicyEngine, CustomerTier, IssueSeverity } from './policy.js';
9
+ import { DiagnosisEngine, IncidentType } from './diagnosis.js';
10
+
11
+ export const ResolutionStatus = Object.freeze({
12
+ RESOLVED_AUTONOMOUSLY: 'RESOLVED_AUTONOMOUSLY',
13
+ REQUIRES_APPROVAL: 'REQUIRES_APPROVAL',
14
+ RESOLVED_BY_APPROVAL: 'RESOLVED_BY_APPROVAL',
15
+ REJECTED_BY_REVIEWER: 'REJECTED_BY_REVIEWER',
16
+ FAILED: 'FAILED',
17
+ });
18
+
19
+ export const ActionType = Object.freeze({
20
+ REFUND: 'REFUND',
21
+ REPLACEMENT: 'REPLACEMENT',
22
+ APOLOGY_CREDIT: 'APOLOGY_CREDIT',
23
+ CARRIER_INQUIRY: 'CARRIER_INQUIRY',
24
+ DISPATCH_TECHNICIAN: 'DISPATCH_TECHNICIAN',
25
+ });
26
+
27
+ let idCounter = 1;
28
+ function generateId(prefix = 'RES') {
29
+ return `${prefix}-${Date.now().toString(36).toUpperCase()}-${(idCounter++).toString().padStart(4, '0')}`;
30
+ }
31
+
32
+ export class ResolveXAgent {
33
+ constructor(options = {}) {
34
+ this.policyEngine = options.policyEngine || new PolicyEngine(options.policyConfig);
35
+ this.diagnosisEngine = options.diagnosisEngine || new DiagnosisEngine();
36
+ this.auditLog = [];
37
+ this.pendingApprovals = new Map();
38
+ this.cases = new Map();
39
+ this.executedIdempotencyKeys = new Map();
40
+ this.refundedTransactions = new Set();
41
+ this.executionAdapter = options.executionAdapter || this._defaultExecutionAdapter();
42
+ }
43
+
44
+ /**
45
+ * Primary entry point to resolve an inbound customer issue.
46
+ */
47
+ async resolveIssue({ customer, order = {}, issue, context = {} }) {
48
+ const caseId = issue.caseId || generateId('CASE');
49
+ const startedAt = new Date().toISOString();
50
+
51
+ this._recordAudit({
52
+ caseId,
53
+ stage: 'INGESTION',
54
+ actor: 'SYSTEM',
55
+ action: 'ISSUE_INGESTED',
56
+ details: {
57
+ customerId: customer.id,
58
+ issueType: issue.type,
59
+ issueText: issue.description || issue.subject,
60
+ },
61
+ });
62
+
63
+ // 1. Context validation & customer authentication check
64
+ if (!customer || !customer.id) {
65
+ const error = 'Unauthenticated customer context';
66
+ this._recordAudit({ caseId, stage: 'AUTHENTICATION', actor: 'SYSTEM', action: 'FAILED', details: { error } });
67
+ return { caseId, status: ResolutionStatus.FAILED, error };
68
+ }
69
+
70
+ // Combine transaction/shipment context from order if present
71
+ const enrichedContext = {
72
+ ...context,
73
+ transactions: context.transactions || order.transactions || [],
74
+ shipment: context.shipment || order.shipment || null,
75
+ deviceTelemetry: context.deviceTelemetry || null,
76
+ currentDate: context.currentDate || new Date(),
77
+ };
78
+
79
+ // 2. Incident Diagnosis
80
+ const diagnosis = this.diagnosisEngine.diagnose(issue, enrichedContext);
81
+
82
+ this._recordAudit({
83
+ caseId,
84
+ stage: 'DIAGNOSIS',
85
+ actor: 'AGENT',
86
+ action: 'DIAGNOSIS_COMPLETED',
87
+ details: {
88
+ rootCause: diagnosis.rootCause,
89
+ confidence: diagnosis.confidence,
90
+ severity: diagnosis.severity,
91
+ verifiedFacts: diagnosis.verifiedFacts,
92
+ },
93
+ });
94
+
95
+ // 3. Propose Resolution Plan based on Diagnosis & Customer Intent
96
+ const proposedPlan = this._formulatePlan({ customer, order, issue, diagnosis, context: enrichedContext });
97
+
98
+ this._recordAudit({
99
+ caseId,
100
+ stage: 'POLICY_EVALUATION',
101
+ actor: 'POLICY_ENGINE',
102
+ action: 'PLAN_PROPOSED',
103
+ details: {
104
+ actionsCount: proposedPlan.actions.length,
105
+ requiresApproval: proposedPlan.requiresApproval,
106
+ reasons: proposedPlan.approvalReasons,
107
+ },
108
+ });
109
+
110
+ // 4. Progressive Autonomy Execution Branch
111
+ if (proposedPlan.requiresApproval) {
112
+ const ticketId = generateId('TICK');
113
+ const ticket = {
114
+ ticketId,
115
+ caseId,
116
+ createdAt: new Date().toISOString(),
117
+ customer: { id: customer.id, name: customer.name, tier: customer.tier || CustomerTier.STANDARD },
118
+ diagnosis,
119
+ proposedPlan,
120
+ status: 'PENDING_APPROVAL',
121
+ escalationReason: proposedPlan.approvalReasons.join('; '),
122
+ };
123
+
124
+ this.pendingApprovals.set(ticketId, ticket);
125
+ this.cases.set(caseId, { caseId, ticketId, customer, order, issue, diagnosis, plan: proposedPlan, status: ResolutionStatus.REQUIRES_APPROVAL });
126
+
127
+ this._recordAudit({
128
+ caseId,
129
+ stage: 'ESCALATION',
130
+ actor: 'AGENT',
131
+ action: 'HUMAN_APPROVAL_REQUESTED',
132
+ details: {
133
+ ticketId,
134
+ escalationReason: ticket.escalationReason,
135
+ pendingActions: proposedPlan.actions.map((a) => a.type),
136
+ },
137
+ });
138
+
139
+ return {
140
+ caseId,
141
+ ticketId,
142
+ status: ResolutionStatus.REQUIRES_APPROVAL,
143
+ diagnosis,
144
+ proposedPlan,
145
+ message: `Action requires human agent approval: ${ticket.escalationReason}`,
146
+ };
147
+ }
148
+
149
+ // 5. Execute Autonomous Safe Actions
150
+ const executionResults = await this._executeActions(proposedPlan.actions, { customer, order, caseId });
151
+
152
+ this.cases.set(caseId, {
153
+ caseId,
154
+ customer,
155
+ order,
156
+ issue,
157
+ diagnosis,
158
+ plan: proposedPlan,
159
+ status: ResolutionStatus.RESOLVED_AUTONOMOUSLY,
160
+ executionResults,
161
+ resolvedAt: new Date().toISOString(),
162
+ });
163
+
164
+ this._recordAudit({
165
+ caseId,
166
+ stage: 'EXECUTION',
167
+ actor: 'AGENT',
168
+ action: 'AUTONOMOUS_RESOLUTION_EXECUTED',
169
+ details: {
170
+ executedActions: executionResults,
171
+ },
172
+ });
173
+
174
+ return {
175
+ caseId,
176
+ status: ResolutionStatus.RESOLVED_AUTONOMOUSLY,
177
+ diagnosis,
178
+ actionsTaken: executionResults,
179
+ summary: this._generateResolutionSummary(executionResults, diagnosis),
180
+ completedAt: new Date().toISOString(),
181
+ };
182
+ }
183
+
184
+ /**
185
+ * Reviewer approval for pending ticket.
186
+ */
187
+ async approveTicket(ticketId, { reviewerId = 'HUMAN_SUPERVISOR', notes = '' } = {}) {
188
+ const ticket = this.pendingApprovals.get(ticketId);
189
+ if (!ticket) {
190
+ throw new Error(`Ticket ${ticketId} not found`);
191
+ }
192
+
193
+ if (ticket.status !== 'PENDING_APPROVAL') {
194
+ throw new Error(`Ticket ${ticketId} is already in ${ticket.status} state`);
195
+ }
196
+
197
+ const { caseId, proposedPlan, customer, order } = ticket;
198
+
199
+ // Execute approved actions
200
+ const executionResults = await this._executeActions(proposedPlan.actions, { customer, order, caseId });
201
+
202
+ ticket.status = 'APPROVED';
203
+ ticket.reviewedBy = reviewerId;
204
+ ticket.reviewedAt = new Date().toISOString();
205
+ ticket.reviewNotes = notes;
206
+ ticket.executionResults = executionResults;
207
+
208
+ const caseRecord = this.cases.get(caseId);
209
+ if (caseRecord) {
210
+ caseRecord.status = ResolutionStatus.RESOLVED_BY_APPROVAL;
211
+ caseRecord.executionResults = executionResults;
212
+ caseRecord.reviewedBy = reviewerId;
213
+ caseRecord.resolvedAt = ticket.reviewedAt;
214
+ }
215
+
216
+ this._recordAudit({
217
+ caseId,
218
+ stage: 'HUMAN_IN_THE_LOOP',
219
+ actor: reviewerId,
220
+ action: 'TICKET_APPROVED_AND_EXECUTED',
221
+ details: {
222
+ ticketId,
223
+ notes,
224
+ executedActions: executionResults,
225
+ },
226
+ });
227
+
228
+ return {
229
+ caseId,
230
+ ticketId,
231
+ status: ResolutionStatus.RESOLVED_BY_APPROVAL,
232
+ reviewerId,
233
+ executedActions: executionResults,
234
+ summary: `Approved by ${reviewerId}. Actions successfully executed.`,
235
+ resolvedAt: ticket.reviewedAt,
236
+ };
237
+ }
238
+
239
+ /**
240
+ * Reviewer rejection for pending ticket with optional alternative action.
241
+ */
242
+ async rejectTicket(ticketId, { reviewerId = 'HUMAN_SUPERVISOR', reason = 'Request declined per review', alternativeAction = null } = {}) {
243
+ const ticket = this.pendingApprovals.get(ticketId);
244
+ if (!ticket) {
245
+ throw new Error(`Ticket ${ticketId} not found`);
246
+ }
247
+
248
+ if (ticket.status !== 'PENDING_APPROVAL') {
249
+ throw new Error(`Ticket ${ticketId} is already in ${ticket.status} state`);
250
+ }
251
+
252
+ const { caseId, customer, order } = ticket;
253
+ let alternativeResult = null;
254
+
255
+ if (alternativeAction) {
256
+ alternativeResult = await this._executeActions([alternativeAction], { customer, order, caseId });
257
+ }
258
+
259
+ ticket.status = 'REJECTED';
260
+ ticket.reviewedBy = reviewerId;
261
+ ticket.reviewedAt = new Date().toISOString();
262
+ ticket.rejectionReason = reason;
263
+ ticket.alternativeResult = alternativeResult;
264
+
265
+ const caseRecord = this.cases.get(caseId);
266
+ if (caseRecord) {
267
+ caseRecord.status = ResolutionStatus.REJECTED_BY_REVIEWER;
268
+ caseRecord.rejectionReason = reason;
269
+ caseRecord.alternativeResult = alternativeResult;
270
+ caseRecord.reviewedBy = reviewerId;
271
+ caseRecord.resolvedAt = ticket.reviewedAt;
272
+ }
273
+
274
+ this._recordAudit({
275
+ caseId,
276
+ stage: 'HUMAN_IN_THE_LOOP',
277
+ actor: reviewerId,
278
+ action: 'TICKET_REJECTED',
279
+ details: {
280
+ ticketId,
281
+ reason,
282
+ alternativeResult,
283
+ },
284
+ });
285
+
286
+ return {
287
+ caseId,
288
+ ticketId,
289
+ status: ResolutionStatus.REJECTED_BY_REVIEWER,
290
+ reviewerId,
291
+ reason,
292
+ alternativeResult,
293
+ resolvedAt: ticket.reviewedAt,
294
+ };
295
+ }
296
+
297
+ /**
298
+ * Formulate candidate plan and check policy boundaries.
299
+ */
300
+ _formulatePlan({ customer, order, issue, diagnosis, context }) {
301
+ const actions = [];
302
+ const approvalReasons = [];
303
+ let requiresApproval = false;
304
+
305
+ const customerTier = customer.tier || CustomerTier.STANDARD;
306
+
307
+ switch (diagnosis.rootCause) {
308
+ case IncidentType.DOUBLE_BILLING: {
309
+ const refundAmount = diagnosis.evidence.duplicateTransaction?.duplicateAmount || issue.amount || 0;
310
+ const refundCheck = this.policyEngine.validateRefund({
311
+ amount: refundAmount,
312
+ orderTotal: order.total || refundAmount,
313
+ customerProfile: customer,
314
+ incidentHistory: customer.incidentHistory || [],
315
+ });
316
+
317
+ actions.push({
318
+ type: ActionType.REFUND,
319
+ amount: refundAmount,
320
+ currency: 'USD',
321
+ targetTxId: diagnosis.evidence.duplicateTransaction?.duplicateTxId || 'TX_DUP',
322
+ autonomousAllowed: refundCheck.allowedAutonomous,
323
+ checkResult: refundCheck,
324
+ });
325
+
326
+ if (refundCheck.requiresApproval) {
327
+ requiresApproval = true;
328
+ approvalReasons.push(refundCheck.reason);
329
+ }
330
+
331
+ // Add apology credit for inconvenience
332
+ const credit = this.policyEngine.calculateApologyCredit({
333
+ severity: diagnosis.severity,
334
+ customerTier,
335
+ });
336
+ actions.push({
337
+ type: ActionType.APOLOGY_CREDIT,
338
+ amount: credit.amount,
339
+ currency: credit.currency,
340
+ breakdown: credit.breakdown,
341
+ autonomousAllowed: true,
342
+ });
343
+ break;
344
+ }
345
+
346
+ case IncidentType.PRODUCT_DEFECT: {
347
+ const replacementCheck = this.policyEngine.validateReplacement({
348
+ product: order.product || { name: 'Item', warrantyDays: 365 },
349
+ purchaseDate: order.purchaseDate || order.orderDate,
350
+ stockAvailable: order.stockAvailable ?? true,
351
+ customerProfile: customer,
352
+ incidentHistory: customer.incidentHistory || [],
353
+ });
354
+
355
+ if (issue.requestedAction === ActionType.REFUND) {
356
+ const refundAmount = issue.amount || order.total || 0;
357
+ const refundCheck = this.policyEngine.validateRefund({
358
+ amount: refundAmount,
359
+ orderTotal: order.total,
360
+ customerProfile: customer,
361
+ incidentHistory: customer.incidentHistory || [],
362
+ });
363
+ actions.push({
364
+ type: ActionType.REFUND,
365
+ amount: refundAmount,
366
+ currency: 'USD',
367
+ autonomousAllowed: refundCheck.allowedAutonomous,
368
+ checkResult: refundCheck,
369
+ });
370
+ if (refundCheck.requiresApproval) {
371
+ requiresApproval = true;
372
+ approvalReasons.push(refundCheck.reason);
373
+ }
374
+ } else {
375
+ actions.push({
376
+ type: ActionType.REPLACEMENT,
377
+ sku: order.product?.sku || 'SKU-REPLACE-DEFAULT',
378
+ productName: order.product?.name || 'Replacement Unit',
379
+ autonomousAllowed: replacementCheck.allowedAutonomous,
380
+ checkResult: replacementCheck,
381
+ });
382
+ if (replacementCheck.requiresApproval) {
383
+ requiresApproval = true;
384
+ approvalReasons.push(replacementCheck.reason);
385
+ }
386
+ }
387
+
388
+ const credit = this.policyEngine.calculateApologyCredit({
389
+ severity: diagnosis.severity,
390
+ customerTier,
391
+ });
392
+ actions.push({
393
+ type: ActionType.APOLOGY_CREDIT,
394
+ amount: credit.amount,
395
+ currency: credit.currency,
396
+ breakdown: credit.breakdown,
397
+ autonomousAllowed: true,
398
+ });
399
+ break;
400
+ }
401
+
402
+ case IncidentType.SHIPPING_DELAY: {
403
+ actions.push({
404
+ type: ActionType.CARRIER_INQUIRY,
405
+ trackingNumber: diagnosis.evidence.shipping?.trackingNumber || order.trackingNumber,
406
+ carrier: diagnosis.evidence.shipping?.carrier || order.carrier,
407
+ autonomousAllowed: true,
408
+ });
409
+
410
+ const credit = this.policyEngine.calculateApologyCredit({
411
+ severity: diagnosis.severity,
412
+ customerTier,
413
+ });
414
+ actions.push({
415
+ type: ActionType.APOLOGY_CREDIT,
416
+ amount: credit.amount,
417
+ currency: credit.currency,
418
+ breakdown: credit.breakdown,
419
+ autonomousAllowed: true,
420
+ });
421
+
422
+ // If delayed >= 10 days, customer can be offered refund if requested
423
+ if (issue.requestedAction === ActionType.REFUND || (diagnosis.evidence.shipping?.daysLate || 0) >= 10) {
424
+ const refundAmount = issue.amount || order.total || 50;
425
+ const refundCheck = this.policyEngine.validateRefund({
426
+ amount: refundAmount,
427
+ orderTotal: order.total,
428
+ customerProfile: customer,
429
+ incidentHistory: customer.incidentHistory || [],
430
+ });
431
+ actions.push({
432
+ type: ActionType.REFUND,
433
+ amount: refundAmount,
434
+ currency: 'USD',
435
+ autonomousAllowed: refundCheck.allowedAutonomous,
436
+ checkResult: refundCheck,
437
+ });
438
+ if (refundCheck.requiresApproval) {
439
+ requiresApproval = true;
440
+ approvalReasons.push(refundCheck.reason);
441
+ }
442
+ }
443
+ break;
444
+ }
445
+
446
+ case IncidentType.SERVICE_OUTAGE: {
447
+ const credit = this.policyEngine.calculateApologyCredit({
448
+ severity: IssueSeverity.HIGH,
449
+ customerTier,
450
+ });
451
+ actions.push({
452
+ type: ActionType.APOLOGY_CREDIT,
453
+ amount: credit.amount,
454
+ currency: credit.currency,
455
+ breakdown: credit.breakdown,
456
+ reason: 'Service Outage SLA Credit',
457
+ autonomousAllowed: true,
458
+ });
459
+ break;
460
+ }
461
+
462
+ default: {
463
+ // Fallback for custom or direct refund request
464
+ if (issue.requestedAction === ActionType.REFUND || issue.amount) {
465
+ const refundAmount = issue.amount || 0;
466
+ const refundCheck = this.policyEngine.validateRefund({
467
+ amount: refundAmount,
468
+ orderTotal: order.total,
469
+ customerProfile: customer,
470
+ incidentHistory: customer.incidentHistory || [],
471
+ });
472
+ actions.push({
473
+ type: ActionType.REFUND,
474
+ amount: refundAmount,
475
+ currency: 'USD',
476
+ autonomousAllowed: refundCheck.allowedAutonomous,
477
+ checkResult: refundCheck,
478
+ });
479
+ if (refundCheck.requiresApproval) {
480
+ requiresApproval = true;
481
+ approvalReasons.push(refundCheck.reason);
482
+ }
483
+ } else {
484
+ // Default inquiry & basic credit
485
+ const credit = this.policyEngine.calculateApologyCredit({
486
+ severity: IssueSeverity.LOW,
487
+ customerTier,
488
+ });
489
+ actions.push({
490
+ type: ActionType.APOLOGY_CREDIT,
491
+ amount: credit.amount,
492
+ currency: credit.currency,
493
+ breakdown: credit.breakdown,
494
+ autonomousAllowed: true,
495
+ });
496
+ }
497
+ break;
498
+ }
499
+ }
500
+
501
+ return {
502
+ actions,
503
+ requiresApproval,
504
+ approvalReasons,
505
+ };
506
+ }
507
+
508
+ /**
509
+ * Execute approved or autonomous actions via adapter.
510
+ */
511
+ async _executeActions(actions, { customer, order, caseId }) {
512
+ const results = [];
513
+ for (const action of actions) {
514
+ // SEC-04: Deterministic idempotency key to prevent replay attacks and race condition double-dispatches
515
+ const idempotencyKey = crypto.createHash('sha256')
516
+ .update(`${caseId}:${action.type}:${action.targetTxId || action.sku || action.amount}`)
517
+ .digest('hex');
518
+
519
+ if (this.executedIdempotencyKeys.has(idempotencyKey)) {
520
+ results.push({
521
+ actionType: action.type,
522
+ parameters: action,
523
+ outcome: { status: 'DUPLICATE_IDEMPOTENT_IGNORED', idempotencyKey, cachedOutcome: this.executedIdempotencyKeys.get(idempotencyKey) },
524
+ executedAt: new Date().toISOString(),
525
+ });
526
+ continue;
527
+ }
528
+
529
+ if (action.type === ActionType.REFUND && action.targetTxId) {
530
+ if (this.refundedTransactions.has(action.targetTxId)) {
531
+ results.push({
532
+ actionType: action.type,
533
+ parameters: action,
534
+ outcome: { status: 'BLOCKED_DUPLICATE_REFUND', error: `Transaction ${action.targetTxId} has already been refunded` },
535
+ executedAt: new Date().toISOString(),
536
+ });
537
+ continue;
538
+ }
539
+ }
540
+
541
+ let outcome;
542
+ switch (action.type) {
543
+ case ActionType.REFUND:
544
+ outcome = await this.executionAdapter.processRefund({
545
+ caseId,
546
+ customerId: customer.id,
547
+ amount: action.amount,
548
+ currency: action.currency || 'USD',
549
+ txId: action.targetTxId,
550
+ idempotencyKey,
551
+ });
552
+ this.refundedTransactions.add(action.targetTxId);
553
+ break;
554
+ case ActionType.REPLACEMENT:
555
+ outcome = await this.executionAdapter.orderReplacement({
556
+ caseId,
557
+ customerId: customer.id,
558
+ sku: action.sku,
559
+ productName: action.productName,
560
+ shippingAddress: customer.shippingAddress || order.shippingAddress,
561
+ idempotencyKey,
562
+ });
563
+ break;
564
+ case ActionType.APOLOGY_CREDIT:
565
+ outcome = await this.executionAdapter.issueCredit({
566
+ caseId,
567
+ customerId: customer.id,
568
+ amount: action.amount,
569
+ currency: action.currency || 'USD',
570
+ breakdown: action.breakdown,
571
+ idempotencyKey,
572
+ });
573
+ break;
574
+ case ActionType.CARRIER_INQUIRY:
575
+ outcome = await this.executionAdapter.escalateCarrier({
576
+ caseId,
577
+ trackingNumber: action.trackingNumber,
578
+ carrier: action.carrier,
579
+ idempotencyKey,
580
+ });
581
+ break;
582
+ default:
583
+ outcome = { status: 'SUCCESS', details: `Executed custom action ${action.type}` };
584
+ break;
585
+ }
586
+
587
+ this.executedIdempotencyKeys.set(idempotencyKey, outcome);
588
+ results.push({
589
+ actionType: action.type,
590
+ parameters: action,
591
+ outcome,
592
+ idempotencyKey,
593
+ executedAt: new Date().toISOString(),
594
+ });
595
+ }
596
+ return results;
597
+ }
598
+
599
+ _recordAudit(entry) {
600
+ const record = {
601
+ id: generateId('AUD'),
602
+ timestamp: new Date().toISOString(),
603
+ ...entry,
604
+ };
605
+ this.auditLog.push(record);
606
+ return record;
607
+ }
608
+
609
+ _generateResolutionSummary(results, diagnosis) {
610
+ const actionSummaries = results.map((r) => {
611
+ if (r.actionType === ActionType.REFUND) return `Processed refund of $${r.parameters.amount}`;
612
+ if (r.actionType === ActionType.REPLACEMENT) return `Dispatched replacement order (${r.parameters.productName})`;
613
+ if (r.actionType === ActionType.APOLOGY_CREDIT) return `Credited $${r.parameters.amount} to account`;
614
+ if (r.actionType === ActionType.CARRIER_INQUIRY) return `Opened priority trace with carrier`;
615
+ return `${r.actionType} completed`;
616
+ });
617
+ return `Resolved ${diagnosis.rootCause}: ${actionSummaries.join(', ')}.`;
618
+ }
619
+
620
+ _defaultExecutionAdapter() {
621
+ return {
622
+ processRefund: async ({ caseId, customerId, amount, currency }) => ({
623
+ success: true,
624
+ referenceId: generateId('RFND'),
625
+ amount,
626
+ currency,
627
+ message: `Refund of ${currency} ${amount} processed successfully for customer ${customerId}`,
628
+ }),
629
+ orderReplacement: async ({ caseId, customerId, sku, productName }) => ({
630
+ success: true,
631
+ replacementOrderId: generateId('ORD-REP'),
632
+ sku,
633
+ productName,
634
+ message: `Replacement order created for ${productName} (SKU: ${sku})`,
635
+ }),
636
+ issueCredit: async ({ caseId, customerId, amount, currency, breakdown }) => ({
637
+ success: true,
638
+ voucherCode: `VCH-${Math.random().toString(36).substring(2, 8).toUpperCase()}`,
639
+ amount,
640
+ currency,
641
+ breakdown,
642
+ message: `Issued credit of ${currency} ${amount}`,
643
+ }),
644
+ escalateCarrier: async ({ caseId, trackingNumber, carrier }) => ({
645
+ success: true,
646
+ ticketNumber: generateId('CARR'),
647
+ trackingNumber,
648
+ carrier,
649
+ status: 'CARRIER_NOTIFIED_PRIORITY',
650
+ }),
651
+ };
652
+ }
653
+
654
+ getPendingApprovals() {
655
+ return Array.from(this.pendingApprovals.values()).filter((t) => t.status === 'PENDING_APPROVAL');
656
+ }
657
+
658
+ getPendingTicket(ticketId) {
659
+ return this.pendingApprovals.get(ticketId) || null;
660
+ }
661
+
662
+ getCase(caseId) {
663
+ return this.cases.get(caseId) || null;
664
+ }
665
+
666
+ getAuditLog(filter = {}) {
667
+ let logs = [...this.auditLog];
668
+ if (filter.caseId) {
669
+ logs = logs.filter((l) => l.caseId === filter.caseId);
670
+ }
671
+ if (filter.stage) {
672
+ logs = logs.filter((l) => l.stage === filter.stage);
673
+ }
674
+ if (filter.actor) {
675
+ logs = logs.filter((l) => l.actor === filter.actor);
676
+ }
677
+ return logs;
678
+ }
679
+ }