@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,428 @@
1
+ import { describe, it } from 'node:test';
2
+ import assert from 'node:assert';
3
+ import {
4
+ PolicyEngine,
5
+ CustomerTier,
6
+ IssueSeverity,
7
+ DiagnosisEngine,
8
+ IncidentType,
9
+ ResolveXAgent,
10
+ ResolutionStatus,
11
+ ActionType,
12
+ } from '../src/index.js';
13
+
14
+ describe('PolicyEngine', () => {
15
+ const policy = new PolicyEngine();
16
+
17
+ it('validates warranty correctly for active and expired dates', () => {
18
+ const today = new Date('2026-11-18T00:00:00Z');
19
+
20
+ // Active warranty (purchased 60 days ago, 365 day warranty)
21
+ const activePurchase = new Date('2026-09-19T00:00:00Z');
22
+ const validResult = policy.validateWarranty({
23
+ purchaseDate: activePurchase,
24
+ warrantyDays: 365,
25
+ referenceDate: today,
26
+ });
27
+ assert.strictEqual(validResult.valid, true);
28
+ assert.strictEqual(validResult.isExpired, false);
29
+ assert.strictEqual(validResult.remainingDays, 305);
30
+
31
+ // Expired warranty (purchased 400 days ago)
32
+ const expiredPurchase = new Date('2025-10-14T00:00:00Z');
33
+ const expiredResult = policy.validateWarranty({
34
+ purchaseDate: expiredPurchase,
35
+ warrantyDays: 365,
36
+ referenceDate: today,
37
+ });
38
+ assert.strictEqual(expiredResult.valid, false);
39
+ assert.strictEqual(expiredResult.isExpired, true);
40
+ });
41
+
42
+ it('enforces autonomous refund limits and flags high-value refunds for approval', () => {
43
+ // Under limit ($45 <= $100)
44
+ const safeRefund = policy.validateRefund({
45
+ amount: 45.0,
46
+ orderTotal: 100.0,
47
+ });
48
+ assert.strictEqual(safeRefund.allowedAutonomous, true);
49
+ assert.strictEqual(safeRefund.requiresApproval, false);
50
+
51
+ // Exceeds autonomous limit ($250 > $100)
52
+ const highRefund = policy.validateRefund({
53
+ amount: 250.0,
54
+ orderTotal: 500.0,
55
+ });
56
+ assert.strictEqual(highRefund.allowedAutonomous, false);
57
+ assert.strictEqual(highRefund.requiresApproval, true);
58
+ assert.match(highRefund.reason, /exceeds autonomous refund threshold/);
59
+
60
+ // Invalid: amount greater than order total
61
+ const excessRefund = policy.validateRefund({
62
+ amount: 600.0,
63
+ orderTotal: 500.0,
64
+ });
65
+ assert.strictEqual(excessRefund.allowed, false);
66
+ assert.strictEqual(excessRefund.requiresApproval, true);
67
+ });
68
+
69
+ it('calculates tier-adjusted apology credit correctly', () => {
70
+ // Standard tier: 1.0x
71
+ const standardCredit = policy.calculateApologyCredit({
72
+ severity: IssueSeverity.MEDIUM,
73
+ customerTier: CustomerTier.STANDARD,
74
+ });
75
+ assert.strictEqual(standardCredit.amount, 25.0);
76
+ assert.strictEqual(standardCredit.multiplier, 1.0);
77
+
78
+ // Gold tier: 1.5x
79
+ const goldCredit = policy.calculateApologyCredit({
80
+ severity: IssueSeverity.MEDIUM,
81
+ customerTier: CustomerTier.GOLD,
82
+ });
83
+ assert.strictEqual(goldCredit.amount, 37.5);
84
+ assert.strictEqual(goldCredit.multiplier, 1.5);
85
+
86
+ // Platinum tier: 2.0x on High severity ($50 base)
87
+ const platCredit = policy.calculateApologyCredit({
88
+ severity: IssueSeverity.HIGH,
89
+ customerTier: CustomerTier.PLATINUM,
90
+ });
91
+ assert.strictEqual(platCredit.amount, 100.0);
92
+ assert.strictEqual(platCredit.multiplier, 2.0);
93
+ });
94
+
95
+ it('evaluates customer risk and flags abusive accounts', () => {
96
+ const trustedCustomer = { accountAgeDays: 365, chargebackCount: 0 };
97
+ const trustedRisk = policy.evaluateRisk({ customerProfile: trustedCustomer });
98
+ assert.strictEqual(trustedRisk.riskLevel, 'LOW');
99
+ assert.strictEqual(trustedRisk.allowsAutonomousAction, true);
100
+
101
+ const flaggedCustomer = {
102
+ accountAgeDays: 5,
103
+ flaggedForAbuse: true,
104
+ chargebackCount: 2,
105
+ };
106
+ const flaggedRisk = policy.evaluateRisk({ customerProfile: flaggedCustomer });
107
+ assert.strictEqual(flaggedRisk.riskLevel, 'HIGH');
108
+ assert.strictEqual(flaggedRisk.allowsAutonomousAction, false);
109
+ assert.ok(flaggedRisk.flagExceptions.length >= 2);
110
+ });
111
+ });
112
+
113
+ describe('DiagnosisEngine', () => {
114
+ const diagnosisEngine = new DiagnosisEngine();
115
+
116
+ it('classifies customer text descriptions by intent', () => {
117
+ const text1 = 'I was charged twice on my credit card for the monthly subscription!';
118
+ const classification1 = diagnosisEngine.classifyText(text1);
119
+ assert.strictEqual(classification1.type, IncidentType.DOUBLE_BILLING);
120
+
121
+ const text2 = 'My order is late, tracking is stuck for 4 days';
122
+ const classification2 = diagnosisEngine.classifyText(text2);
123
+ assert.strictEqual(classification2.type, IncidentType.SHIPPING_DELAY);
124
+
125
+ const text3 = 'The headphone screen is broken and hardware won\'t turn on';
126
+ const classification3 = diagnosisEngine.classifyText(text3);
127
+ assert.strictEqual(classification3.type, IncidentType.PRODUCT_DEFECT);
128
+
129
+ const text4 = 'Major service outage, 503 error, server is down';
130
+ const classification4 = diagnosisEngine.classifyText(text4);
131
+ assert.strictEqual(classification4.type, IncidentType.SERVICE_OUTAGE);
132
+ });
133
+
134
+ it('verifies double billing evidence from transaction history', () => {
135
+ const transactions = [
136
+ { id: 'tx-1', amount: 49.99, timestamp: '2026-11-10T10:00:00Z' },
137
+ { id: 'tx-2', amount: 49.99, timestamp: '2026-11-10T10:04:00Z' },
138
+ ];
139
+ const issue = { description: 'Why am I charged twice?' };
140
+ const result = diagnosisEngine.diagnose(issue, { transactions });
141
+
142
+ assert.strictEqual(result.rootCause, IncidentType.DOUBLE_BILLING);
143
+ assert.strictEqual(result.evidence.duplicateTransaction.isDuplicate, true);
144
+ assert.strictEqual(result.evidence.duplicateTransaction.duplicateAmount, 49.99);
145
+ assert.ok(result.confidence >= 0.95);
146
+ });
147
+
148
+ it('verifies shipping delay from shipment details and estimated delivery date', () => {
149
+ const now = new Date('2026-11-18T12:00:00Z');
150
+ const shipment = {
151
+ trackingNumber: 'TRK-987654321',
152
+ carrier: 'FedEx Express',
153
+ status: 'IN_TRANSIT',
154
+ estimatedDeliveryDate: '2026-11-14T00:00:00Z',
155
+ };
156
+ const issue = { description: 'Where is my order?' };
157
+ const result = diagnosisEngine.diagnose(issue, { shipment, currentDate: now });
158
+
159
+ assert.strictEqual(result.rootCause, IncidentType.SHIPPING_DELAY);
160
+ assert.strictEqual(result.evidence.shipping.isDelayed, true);
161
+ assert.strictEqual(result.evidence.shipping.daysLate, 4);
162
+ });
163
+ });
164
+
165
+ describe('ResolveXAgent - Autonomous Resolution', () => {
166
+ it('autonomously resolves double billing under $100 with refund and apology credit', async () => {
167
+ const agent = new ResolveXAgent();
168
+ const customer = {
169
+ id: 'CUST-1001',
170
+ name: 'Alice Johnson',
171
+ tier: CustomerTier.SILVER,
172
+ accountAgeDays: 200,
173
+ };
174
+ const order = {
175
+ orderId: 'ORD-5501',
176
+ total: 80.0,
177
+ transactions: [
178
+ { id: 'tx-001', amount: 40.0, timestamp: '2026-11-18T08:00:00Z' },
179
+ { id: 'tx-002', amount: 40.0, timestamp: '2026-11-18T08:01:00Z' },
180
+ ],
181
+ };
182
+ const issue = {
183
+ description: 'You charged me twice for $40 each!',
184
+ amount: 40.0,
185
+ };
186
+
187
+ const resolution = await agent.resolveIssue({ customer, order, issue });
188
+
189
+ assert.strictEqual(resolution.status, ResolutionStatus.RESOLVED_AUTONOMOUSLY);
190
+ assert.strictEqual(resolution.diagnosis.rootCause, IncidentType.DOUBLE_BILLING);
191
+ assert.strictEqual(resolution.actionsTaken.length, 2);
192
+
193
+ const refundAction = resolution.actionsTaken.find((a) => a.actionType === ActionType.REFUND);
194
+ assert.ok(refundAction);
195
+ assert.strictEqual(refundAction.outcome.amount, 40.0);
196
+ assert.strictEqual(refundAction.outcome.success, true);
197
+
198
+ const creditAction = resolution.actionsTaken.find((a) => a.actionType === ActionType.APOLOGY_CREDIT);
199
+ assert.ok(creditAction);
200
+ // Silver tier gets 1.25 multiplier on medium severity ($25 * 1.25 = $31.25)
201
+ assert.strictEqual(creditAction.parameters.amount, 31.25);
202
+ });
203
+
204
+ it('autonomously resolves in-warranty defect with replacement and apology credit', async () => {
205
+ const agent = new ResolveXAgent();
206
+ const customer = {
207
+ id: 'CUST-2002',
208
+ name: 'Bob Smith',
209
+ tier: CustomerTier.STANDARD,
210
+ accountAgeDays: 90,
211
+ };
212
+ const order = {
213
+ orderId: 'ORD-7702',
214
+ purchaseDate: '2026-10-01T00:00:00Z',
215
+ product: { sku: 'DEV-CAM-4K', name: 'Ultra HD Webcam', warrantyDays: 365 },
216
+ stockAvailable: true,
217
+ };
218
+ const issue = {
219
+ description: 'The webcam is defective and not working, won\'t turn on at all',
220
+ };
221
+
222
+ const resolution = await agent.resolveIssue({ customer, order, issue });
223
+
224
+ assert.strictEqual(resolution.status, ResolutionStatus.RESOLVED_AUTONOMOUSLY);
225
+ assert.strictEqual(resolution.diagnosis.rootCause, IncidentType.PRODUCT_DEFECT);
226
+
227
+ const replacementAction = resolution.actionsTaken.find((a) => a.actionType === ActionType.REPLACEMENT);
228
+ assert.ok(replacementAction);
229
+ assert.strictEqual(replacementAction.outcome.success, true);
230
+ assert.strictEqual(replacementAction.parameters.sku, 'DEV-CAM-4K');
231
+ });
232
+
233
+ it('autonomously handles shipping delay with priority carrier trace and loyalty credit', async () => {
234
+ const agent = new ResolveXAgent();
235
+ const customer = {
236
+ id: 'CUST-3003',
237
+ name: 'Carol White',
238
+ tier: CustomerTier.GOLD,
239
+ accountAgeDays: 120,
240
+ };
241
+ const order = {
242
+ orderId: 'ORD-8803',
243
+ trackingNumber: 'TRK-DHL-9911',
244
+ carrier: 'DHL',
245
+ shipment: {
246
+ trackingNumber: 'TRK-DHL-9911',
247
+ carrier: 'DHL',
248
+ status: 'DELAYED',
249
+ daysLate: 3,
250
+ },
251
+ };
252
+ const issue = {
253
+ description: 'My order is delayed and tracking is stuck',
254
+ };
255
+
256
+ const resolution = await agent.resolveIssue({ customer, order, issue });
257
+
258
+ assert.strictEqual(resolution.status, ResolutionStatus.RESOLVED_AUTONOMOUSLY);
259
+ assert.strictEqual(resolution.diagnosis.rootCause, IncidentType.SHIPPING_DELAY);
260
+
261
+ const carrierAction = resolution.actionsTaken.find((a) => a.actionType === ActionType.CARRIER_INQUIRY);
262
+ assert.ok(carrierAction);
263
+ assert.strictEqual(carrierAction.outcome.status, 'CARRIER_NOTIFIED_PRIORITY');
264
+
265
+ const creditAction = resolution.actionsTaken.find((a) => a.actionType === ActionType.APOLOGY_CREDIT);
266
+ assert.ok(creditAction);
267
+ // Gold tier gets 1.5 multiplier on medium severity ($25 * 1.5 = $37.5)
268
+ assert.strictEqual(creditAction.parameters.amount, 37.5);
269
+ });
270
+ });
271
+
272
+ describe('ResolveXAgent - Human-in-the-Loop Escalation & Approval', () => {
273
+ it('escalates high-value refund ($250 > $100) to human supervisor and executes upon approval', async () => {
274
+ const agent = new ResolveXAgent();
275
+ const customer = {
276
+ id: 'CUST-4004',
277
+ name: 'David Miller',
278
+ tier: CustomerTier.STANDARD,
279
+ accountAgeDays: 150,
280
+ };
281
+ const order = {
282
+ orderId: 'ORD-9904',
283
+ total: 500.0,
284
+ transactions: [
285
+ { id: 'tx-A', amount: 250.0, timestamp: '2026-11-15T12:00:00Z' },
286
+ { id: 'tx-B', amount: 250.0, timestamp: '2026-11-15T12:02:00Z' },
287
+ ],
288
+ };
289
+ const issue = {
290
+ description: 'I was charged twice $250 each for the yearly enterprise plan!',
291
+ amount: 250.0,
292
+ };
293
+
294
+ // 1. Initial resolution attempt should escalate
295
+ const resolution = await agent.resolveIssue({ customer, order, issue });
296
+
297
+ assert.strictEqual(resolution.status, ResolutionStatus.REQUIRES_APPROVAL);
298
+ assert.ok(resolution.ticketId);
299
+ assert.match(resolution.message, /requires human agent approval/);
300
+
301
+ // 2. Verify ticket is present in pending approvals
302
+ const pendingList = agent.getPendingApprovals();
303
+ assert.strictEqual(pendingList.length, 1);
304
+ assert.strictEqual(pendingList[0].ticketId, resolution.ticketId);
305
+ assert.strictEqual(pendingList[0].status, 'PENDING_APPROVAL');
306
+
307
+ // 3. Human Supervisor reviews and approves
308
+ const approvalResult = await agent.approveTicket(resolution.ticketId, {
309
+ reviewerId: 'SUPERVISOR_SARAH',
310
+ notes: 'Verified duplicate charge on Stripe dashboard; approved refund of $250',
311
+ });
312
+
313
+ assert.strictEqual(approvalResult.status, ResolutionStatus.RESOLVED_BY_APPROVAL);
314
+ assert.strictEqual(approvalResult.reviewerId, 'SUPERVISOR_SARAH');
315
+ assert.strictEqual(approvalResult.executedActions.length, 2);
316
+
317
+ const executedRefund = approvalResult.executedActions.find((a) => a.actionType === ActionType.REFUND);
318
+ assert.ok(executedRefund);
319
+ assert.strictEqual(executedRefund.outcome.amount, 250.0);
320
+ assert.strictEqual(executedRefund.outcome.success, true);
321
+
322
+ // 4. Verify no pending tickets remain
323
+ assert.strictEqual(agent.getPendingApprovals().length, 0);
324
+ });
325
+
326
+ it('handles human supervisor rejection with alternative credit offer', async () => {
327
+ const agent = new ResolveXAgent();
328
+ const customer = {
329
+ id: 'CUST-5005',
330
+ name: 'Eva Green',
331
+ tier: CustomerTier.STANDARD,
332
+ accountAgeDays: 20,
333
+ };
334
+ const order = {
335
+ orderId: 'ORD-9905',
336
+ total: 300.0,
337
+ purchaseDate: '2025-01-01T00:00:00Z', // Expired warranty
338
+ product: { name: 'Vintage Camera', warrantyDays: 90 },
339
+ };
340
+ const issue = {
341
+ description: 'The camera lens stopped focusing, I demand a full refund of $300',
342
+ requestedAction: ActionType.REFUND,
343
+ amount: 300.0,
344
+ };
345
+
346
+ const resolution = await agent.resolveIssue({ customer, order, issue });
347
+ assert.strictEqual(resolution.status, ResolutionStatus.REQUIRES_APPROVAL);
348
+
349
+ // Reviewer rejects cash refund but grants customer $50 courtesy voucher
350
+ const rejectionResult = await agent.rejectTicket(resolution.ticketId, {
351
+ reviewerId: 'SUPERVISOR_MIKE',
352
+ reason: 'Product is 1.5 years out of warranty; refund denied',
353
+ alternativeAction: {
354
+ type: ActionType.APOLOGY_CREDIT,
355
+ amount: 50.0,
356
+ currency: 'USD',
357
+ breakdown: 'Courtesy store voucher for out-of-warranty customer',
358
+ },
359
+ });
360
+
361
+ assert.strictEqual(rejectionResult.status, ResolutionStatus.REJECTED_BY_REVIEWER);
362
+ assert.strictEqual(rejectionResult.reason, 'Product is 1.5 years out of warranty; refund denied');
363
+ assert.ok(rejectionResult.alternativeResult);
364
+ assert.strictEqual(rejectionResult.alternativeResult[0].parameters.amount, 50.0);
365
+ });
366
+ });
367
+
368
+ describe('Audit Logging', () => {
369
+ it('maintains comprehensive audit trail of all ingestion, decisions, and approvals', async () => {
370
+ const agent = new ResolveXAgent();
371
+ const customer = { id: 'CUST-6006', name: 'Frank', tier: CustomerTier.PLATINUM };
372
+ const order = {
373
+ total: 500,
374
+ transactions: [
375
+ { id: 'tx-1', amount: 300, timestamp: '2026-11-18T10:00:00Z' },
376
+ { id: 'tx-2', amount: 300, timestamp: '2026-11-18T10:01:00Z' },
377
+ ],
378
+ };
379
+ const issue = { description: 'Duplicate charge of $300', amount: 300 };
380
+
381
+ const resolution = await agent.resolveIssue({ customer, order, issue });
382
+ await agent.approveTicket(resolution.ticketId, { reviewerId: 'MANAGER_ALEX' });
383
+
384
+ const auditTrail = agent.getAuditLog({ caseId: resolution.caseId });
385
+ assert.ok(auditTrail.length >= 4);
386
+
387
+ const stages = auditTrail.map((entry) => entry.stage);
388
+ assert.ok(stages.includes('INGESTION'));
389
+ assert.ok(stages.includes('DIAGNOSIS'));
390
+ assert.ok(stages.includes('POLICY_EVALUATION'));
391
+ assert.ok(stages.includes('ESCALATION'));
392
+ assert.ok(stages.includes('HUMAN_IN_THE_LOOP'));
393
+
394
+ // Check structure of audit records
395
+ for (const record of auditTrail) {
396
+ assert.ok(record.id);
397
+ assert.ok(record.timestamp);
398
+ assert.ok(record.actor);
399
+ assert.ok(record.action);
400
+ }
401
+ });
402
+ });
403
+
404
+ describe('ResolveX Security - Idempotency & Replay Protection', () => {
405
+ it('blocks duplicate refund replays against the same transaction ID', async () => {
406
+ const agent = new ResolveXAgent();
407
+ const customer = { id: 'CUST-SEC-1', name: 'Alice Security' };
408
+ const order = { id: 'ORD-SEC-1' };
409
+ const issue = { caseId: 'CASE-REPLAY-1', subject: 'I was charged twice', description: 'Charged two times' };
410
+ const context = {
411
+ transactions: [
412
+ { id: 'TX-DUP-1', amount: 45, date: new Date('2026-11-01T10:00:00Z') },
413
+ { id: 'TX-DUP-1', amount: 45, date: new Date('2026-11-01T10:01:00Z') },
414
+ ],
415
+ };
416
+
417
+ // First execution succeeds
418
+ const firstRes = await agent.resolveIssue({ customer, order, issue, context });
419
+ assert.equal(firstRes.status, 'RESOLVED_AUTONOMOUSLY');
420
+
421
+ // Attempting replay with identical actions blocks double refund
422
+ const replayRes = await agent._executeActions([
423
+ { type: 'REFUND', amount: 45, targetTxId: 'TX-DUP-1' }
424
+ ], { customer, order, caseId: 'CASE-REPLAY-1' });
425
+
426
+ assert.equal(replayRes[0].outcome.status, 'DUPLICATE_IDEMPOTENT_IGNORED');
427
+ });
428
+ });
@@ -0,0 +1,51 @@
1
+ # SentinelMesh — Enterprise Agent Trust, Sandboxing & Governance Layer
2
+
3
+ **SentinelMesh** is the mission-critical trust fabric for autonomous enterprise agents. It enforces fine-grained capability boundaries, progressive autonomy limits, cryptographic audit ledgers, and emergency kill-switches.
4
+
5
+ ## Core Capabilities
6
+
7
+ 1. **Least-Privilege Scoping:** Restricts agent capabilities to strictly defined permissions (`read:data`, `write:data`, `transact:financial`, etc.).
8
+ 2. **Deterministic Risk Evaluation:** Dynamically scores tool invocations into Low, Medium, High, or Critical tiers.
9
+ 3. **Progressive Autonomy & Human Gates:** Reversible/low-cost actions run autonomously, while actions exceeding policy limits automatically pause at human-in-the-loop checkpoints.
10
+ 4. **Append-Only Tamper-Evident Audit Ledger:** Every agent action, input parameter, status, and policy check is hashed sequentially into a SHA-256 verifiable chain.
11
+ 5. **Circuit Breakers & Kill-Switches:** Automatically quarantines agents that trigger repeated faults or anomaly thresholds.
12
+
13
+ ## Usage
14
+
15
+ ```javascript
16
+ import { SentinelGovernor, PermissionScope } from 'sentinelmesh-agent';
17
+
18
+ const governor = new SentinelGovernor();
19
+
20
+ // 1. Register agent with bounded financial authority ($50.00 / 5000 cents)
21
+ governor.registerAgent('support-agent-01', [
22
+ PermissionScope.READ_DATA,
23
+ PermissionScope.FINANCIAL_TRANSACTION
24
+ ], 5000);
25
+
26
+ // 2. Safe transaction runs autonomously
27
+ const res = await governor.runStep(
28
+ 'support-agent-01',
29
+ 'issue_credit',
30
+ PermissionScope.FINANCIAL_TRANSACTION,
31
+ { amount: 2500, customerId: 'cust-99' },
32
+ async (params) => ({ credited: params.amount })
33
+ );
34
+ // res.status === 'EXECUTED'
35
+
36
+ // 3. High-value transaction stops at Human-in-the-Loop approval gate
37
+ const highRes = await governor.runStep(
38
+ 'support-agent-01',
39
+ 'issue_credit',
40
+ PermissionScope.FINANCIAL_TRANSACTION,
41
+ { amount: 15000, customerId: 'cust-99' },
42
+ async (params) => ({ credited: params.amount })
43
+ );
44
+ // highRes.status === 'APPROVAL_REQUIRED'
45
+ ```
46
+
47
+ ## Testing
48
+
49
+ ```sh
50
+ npm test
51
+ ```
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "sentinelmesh-agent",
3
+ "version": "0.1.0",
4
+ "description": "SentinelMesh - Enterprise Agent Trust, Sandboxing and Governance Layer",
5
+ "private": true,
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=20"
9
+ },
10
+ "scripts": {
11
+ "test": "node --test"
12
+ }
13
+ }
@@ -0,0 +1,61 @@
1
+ import { AccessPolicy, PermissionScope, RiskLevel } from './policy.js';
2
+ import { ToolSandbox } from './sandbox.js';
3
+
4
+ /**
5
+ * SentinelMesh Governor: Super-agent that monitors and enforces trust policies across sub-agents.
6
+ */
7
+ export class SentinelGovernor {
8
+ constructor() {
9
+ this.sandbox = new ToolSandbox();
10
+ this.registeredAgents = new Map();
11
+ this.failureCounters = new Map();
12
+ this.failureThreshold = 3;
13
+ }
14
+
15
+ registerAgent(agentId, allowedScopes = [], spendingLimit = 0) {
16
+ const policy = new AccessPolicy(agentId, allowedScopes, spendingLimit);
17
+ this.registeredAgents.set(agentId, policy);
18
+ this.failureCounters.set(agentId, 0);
19
+ this.sandbox.recordAudit({
20
+ agentId,
21
+ action: 'AGENT_REGISTERED',
22
+ details: { allowedScopes, spendingLimit },
23
+ status: 'INITIALIZED'
24
+ });
25
+ return policy;
26
+ }
27
+
28
+ getPolicy(agentId) {
29
+ const policy = this.registeredAgents.get(agentId);
30
+ if (!policy) throw new Error(`Agent ${agentId} is not registered with Sentinel`);
31
+ return policy;
32
+ }
33
+
34
+ async runStep(agentId, toolName, requiredScope, params, toolFn) {
35
+ const policy = this.getPolicy(agentId);
36
+
37
+ try {
38
+ const outcome = await this.sandbox.executeGuarded(agentId, policy, toolName, requiredScope, params, toolFn);
39
+ if (outcome.status === 'EXECUTED') {
40
+ this.failureCounters.set(agentId, 0); // reset on success
41
+ }
42
+ return outcome;
43
+ } catch (err) {
44
+ const fails = (this.failureCounters.get(agentId) || 0) + 1;
45
+ this.failureCounters.set(agentId, fails);
46
+
47
+ if (fails >= this.failureThreshold) {
48
+ this.sandbox.tripKillSwitch(agentId, `Exceeded consecutive failure threshold (${this.failureThreshold})`);
49
+ }
50
+ throw err;
51
+ }
52
+ }
53
+
54
+ quarantine(agentId, reason) {
55
+ this.sandbox.tripKillSwitch(agentId, reason);
56
+ }
57
+
58
+ getAuditTrail(agentId) {
59
+ return this.sandbox.auditLedger.filter(b => b.agentId === agentId);
60
+ }
61
+ }
@@ -0,0 +1,4 @@
1
+ export { PermissionScope, RiskLevel, AccessPolicy } from './policy.js';
2
+ export { ToolSandbox } from './sandbox.js';
3
+ export { SentinelGovernor } from './governor.js';
4
+ export { SentinelMeshMobileAdapter } from './mobile.js';
@@ -0,0 +1,19 @@
1
+ /**
2
+ * SentinelMesh Mobile Adapter: Formats mobile governance dashboard & kill-switch controls.
3
+ */
4
+
5
+ export class SentinelMeshMobileAdapter {
6
+ constructor(sentinel) {
7
+ this.sentinel = sentinel;
8
+ }
9
+
10
+ getMobileOutcomeCard() {
11
+ return {
12
+ title: 'SentinelMesh Governance Fabric',
13
+ outcomeMetric: 'Active Sandbox',
14
+ auditLedgerLength: this.sentinel.sandbox.auditLedger.length,
15
+ quarantinedCount: this.sentinel.sandbox.killSwitches.size,
16
+ statusBadge: 'ZERO_TRUST_ENFORCED'
17
+ };
18
+ }
19
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * SentinelMesh Policy Engine: Least-privilege permission matrix and risk scoring.
3
+ */
4
+
5
+ export const PermissionScope = {
6
+ READ_DATA: 'read:data',
7
+ WRITE_DATA: 'write:data',
8
+ EXECUTE_TOOL: 'execute:tool',
9
+ FINANCIAL_TRANSACTION: 'transact:financial',
10
+ CUSTOMER_COMMUNICATION: 'communicate:customer',
11
+ SYSTEM_CONFIG: 'system:config'
12
+ };
13
+
14
+ export const RiskLevel = {
15
+ LOW: 'LOW', // Read-only, safe diagnostics
16
+ MEDIUM: 'MEDIUM', // Internal writes, draft generation
17
+ HIGH: 'HIGH', // Customer-facing messages, refunds under threshold
18
+ CRITICAL: 'CRITICAL' // Financial disbursements, deletions, permission changes
19
+ };
20
+
21
+ export class AccessPolicy {
22
+ constructor(agentId, allowedScopes = [PermissionScope.READ_DATA], spendingLimit = 0) {
23
+ this.agentId = agentId;
24
+ this.allowedScopes = new Set(allowedScopes);
25
+ this.spendingLimit = spendingLimit; // In cents/paise
26
+ }
27
+
28
+ isAuthorized(scope, metadata = {}) {
29
+ if (!this.allowedScopes.has(scope)) {
30
+ return { authorized: false, reason: `Agent missing required scope: ${scope}` };
31
+ }
32
+
33
+ if (scope === PermissionScope.FINANCIAL_TRANSACTION) {
34
+ const amount = metadata.amount;
35
+
36
+ // SEC-03: Strict validation against negative values, non-integers, NaN, Infinity, and type-coercion attacks
37
+ if (typeof amount !== 'number' || !Number.isSafeInteger(amount) || amount <= 0) {
38
+ return {
39
+ authorized: false,
40
+ reason: 'Invalid transaction amount: must be positive safe integer in minor currency units'
41
+ };
42
+ }
43
+
44
+ if (amount > this.spendingLimit) {
45
+ return {
46
+ authorized: false,
47
+ requiresHumanApproval: true,
48
+ reason: `Transaction amount $${(amount / 100).toFixed(2)} exceeds agent limit $${(this.spendingLimit / 100).toFixed(2)}`
49
+ };
50
+ }
51
+ }
52
+
53
+ return { authorized: true };
54
+ }
55
+
56
+ evaluateRisk(toolName, params = {}) {
57
+ if (params.amount && params.amount > 100000) return RiskLevel.CRITICAL;
58
+ if (toolName.includes('refund') || toolName.includes('transfer')) return RiskLevel.HIGH;
59
+ if (toolName.includes('send') || toolName.includes('notify')) return RiskLevel.MEDIUM;
60
+ if (toolName.includes('read') || toolName.includes('fetch') || toolName.includes('query')) return RiskLevel.LOW;
61
+ return RiskLevel.MEDIUM;
62
+ }
63
+ }