@spekra.in/agent-os 0.0.0-stage → 1.0.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 (114) 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 +203 -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 +260 -0
  113. package/package.json +51 -4
  114. package/src/index.js +91 -0
@@ -0,0 +1,621 @@
1
+ /**
2
+ * CashHound - Autonomous Decision State Machine
3
+ * Evaluates receivables, enforces risk and governance policies,
4
+ * flags high-value and legal accounts for human approval,
5
+ * and automates safe dunning and payment reconciliation.
6
+ */
7
+
8
+ import { Invoice, InvoiceStatus, AgingBuckets, PriorityLevel } from './invoice.js';
9
+ import { generateDunningMessage, DunningTier } from './dunning.js';
10
+
11
+ export const ActionStatus = Object.freeze({
12
+ PENDING_APPROVAL: 'PENDING_APPROVAL',
13
+ APPROVED: 'APPROVED',
14
+ REJECTED: 'REJECTED',
15
+ AUTO_EXECUTED: 'AUTO_EXECUTED',
16
+ CANCELLED: 'CANCELLED',
17
+ });
18
+
19
+ export const AgentDecisionType = Object.freeze({
20
+ NO_ACTION: 'NO_ACTION',
21
+ SAFE_REMINDER: 'SAFE_REMINDER',
22
+ REQUIRE_APPROVAL: 'REQUIRE_APPROVAL',
23
+ DISPUTE_REVIEW: 'DISPUTE_REVIEW',
24
+ PAYMENT_RECONCILIATION: 'PAYMENT_RECONCILIATION',
25
+ });
26
+
27
+ export class CashHoundAgent {
28
+ /**
29
+ * @param {Object} [config={}]
30
+ * @param {number} [config.highValueThreshold=5000] - Invoices >= this amount require human approval
31
+ * @param {number} [config.cooldownDays=7] - Minimum days between reminders
32
+ * @param {boolean} [config.autoSendSafeReminders=true] - Whether to auto-send low-risk reminders
33
+ * @param {boolean} [config.requireApprovalForFinalDemand=true] - Tier 4 always needs human approval
34
+ * @param {string} [config.agentName='CashHound']
35
+ */
36
+ constructor(config = {}) {
37
+ this.agentName = config.agentName || 'CashHound';
38
+ this.highValueThreshold = typeof config.highValueThreshold === 'number' ? config.highValueThreshold : 5000;
39
+ this.cooldownDays = typeof config.cooldownDays === 'number' ? config.cooldownDays : 7;
40
+ this.autoSendSafeReminders = config.autoSendSafeReminders !== false;
41
+ this.requireApprovalForFinalDemand = config.requireApprovalForFinalDemand !== false;
42
+
43
+ /** @type {Map<string, Invoice>} */
44
+ this.invoices = new Map();
45
+
46
+ /** @type {Map<string, Object>} */
47
+ this.actions = new Map();
48
+
49
+ /** @type {Array<Object>} */
50
+ this.auditTrail = [];
51
+ }
52
+
53
+ /**
54
+ * Registers an invoice with the CashHound agent.
55
+ * @param {Invoice} invoice
56
+ * @returns {Invoice}
57
+ */
58
+ registerInvoice(invoice) {
59
+ if (!(invoice instanceof Invoice)) {
60
+ throw new Error('Expected an instance of Invoice');
61
+ }
62
+ this.invoices.set(invoice.id, invoice);
63
+ this._logAudit('INVOICE_REGISTERED', {
64
+ invoiceId: invoice.id,
65
+ amount: invoice.amount,
66
+ dueDate: invoice.dueDate.toISOString().split('T')[0],
67
+ customer: invoice.customer.name,
68
+ });
69
+ return invoice;
70
+ }
71
+
72
+ /**
73
+ * Retrieves an invoice by ID.
74
+ * @param {string} id
75
+ * @returns {Invoice|undefined}
76
+ */
77
+ getInvoice(id) {
78
+ return this.invoices.get(id);
79
+ }
80
+
81
+ /**
82
+ * Lists registered invoices with optional filtering.
83
+ * @param {Object} [filter={}]
84
+ * @returns {Invoice[]}
85
+ */
86
+ listInvoices(filter = {}) {
87
+ let result = Array.from(this.invoices.values());
88
+
89
+ if (filter.status) {
90
+ result = result.filter(inv => inv.status === filter.status);
91
+ }
92
+ if (filter.agingBucket && filter.asOfDate) {
93
+ result = result.filter(inv => inv.getAgingBucket(filter.asOfDate) === filter.agingBucket);
94
+ }
95
+ if (filter.overdueOnly) {
96
+ const asOf = filter.asOfDate ? new Date(filter.asOfDate) : new Date();
97
+ result = result.filter(inv => inv.getDaysPastDue(asOf) > 0 && inv.balance > 0);
98
+ }
99
+ return result;
100
+ }
101
+
102
+ /**
103
+ * Evaluates an invoice against policy rules and determines next state / action.
104
+ *
105
+ * @param {Invoice} invoice
106
+ * @param {Date|string} [asOfDate=new Date()]
107
+ * @returns {Object} Decision output
108
+ */
109
+ evaluateInvoice(invoice, asOfDate = new Date()) {
110
+ const asOf = new Date(asOfDate);
111
+ const daysOverdue = invoice.getDaysPastDue(asOf);
112
+ const priority = invoice.calculatePriority(asOf);
113
+
114
+ // Rule 1: Paid or zero balance accounts require no recovery action
115
+ if (invoice.balance <= 0 || invoice.status === InvoiceStatus.PAID) {
116
+ return {
117
+ decision: AgentDecisionType.NO_ACTION,
118
+ reason: 'Invoice is fully paid',
119
+ requiresApproval: false,
120
+ priority,
121
+ };
122
+ }
123
+
124
+ // Rule 2: Invoices not yet overdue require no dunning
125
+ if (daysOverdue <= 0) {
126
+ return {
127
+ decision: AgentDecisionType.NO_ACTION,
128
+ reason: `Invoice is current (due in ${Math.abs(daysOverdue)} days)`,
129
+ requiresApproval: false,
130
+ priority,
131
+ };
132
+ }
133
+
134
+ // Rule 3: Legal dispute -> Immediate human approval & legal escalation gate
135
+ if (invoice.isLegalDispute()) {
136
+ return {
137
+ decision: AgentDecisionType.REQUIRE_APPROVAL,
138
+ approvalReasons: ['Active legal dispute requires compliance & human legal sign-off'],
139
+ requiresApproval: true,
140
+ isLegalHold: true,
141
+ priority,
142
+ };
143
+ }
144
+
145
+ // Rule 4: Commercial dispute -> Route for dispute resolution
146
+ if (invoice.isDisputed()) {
147
+ return {
148
+ decision: AgentDecisionType.DISPUTE_REVIEW,
149
+ approvalReasons: [`Commercial dispute open: ${invoice.dispute.reason}`],
150
+ requiresApproval: true,
151
+ isDisputed: true,
152
+ priority,
153
+ };
154
+ }
155
+
156
+ // Rule 5: Check communication cooldown to prevent spamming customers
157
+ const recentComm = this._getMostRecentCommunication(invoice);
158
+ if (recentComm) {
159
+ const diffMs = asOf.getTime() - new Date(recentComm.timestamp).getTime();
160
+ const diffDays = diffMs / (1000 * 60 * 60 * 24);
161
+ if (diffDays < this.cooldownDays) {
162
+ return {
163
+ decision: AgentDecisionType.NO_ACTION,
164
+ reason: `In cooldown window (last contacted ${diffDays.toFixed(1)} days ago, cooldown is ${this.cooldownDays} days)`,
165
+ requiresApproval: false,
166
+ priority,
167
+ };
168
+ }
169
+ }
170
+
171
+ // Generate draft dunning message
172
+ const draftMessage = generateDunningMessage(invoice, { asOfDate: asOf });
173
+ const approvalReasons = [];
174
+
175
+ // Rule 6: High-value account check (>= threshold, default $5,000)
176
+ if (invoice.balance >= this.highValueThreshold) {
177
+ approvalReasons.push(`High-value invoice balance ($${invoice.balance.toLocaleString()} >= $${this.highValueThreshold.toLocaleString()})`);
178
+ }
179
+
180
+ // Rule 7: Tier 4 Final Demand check
181
+ if (this.requireApprovalForFinalDemand && draftMessage.tier === DunningTier.TIER_4_FINAL_DEMAND) {
182
+ approvalReasons.push('Final demand notice (Tier 4) requires human management sign-off');
183
+ }
184
+
185
+ if (approvalReasons.length > 0) {
186
+ return {
187
+ decision: AgentDecisionType.REQUIRE_APPROVAL,
188
+ approvalReasons,
189
+ requiresApproval: true,
190
+ draftMessage,
191
+ priority,
192
+ };
193
+ }
194
+
195
+ // Rule 8: Low-risk, safe reminder
196
+ return {
197
+ decision: AgentDecisionType.SAFE_REMINDER,
198
+ reason: 'Low-risk account passed all automated policy guardrails',
199
+ requiresApproval: false,
200
+ draftMessage,
201
+ priority,
202
+ };
203
+ }
204
+
205
+ /**
206
+ * Processes a single invoice according to the decision state machine.
207
+ *
208
+ * @param {Invoice} invoice
209
+ * @param {Date|string} [asOfDate=new Date()]
210
+ * @returns {Object} Action record or evaluation summary
211
+ */
212
+ processInvoice(invoice, asOfDate = new Date()) {
213
+ const evaluation = this.evaluateInvoice(invoice, asOfDate);
214
+
215
+ if (evaluation.decision === AgentDecisionType.NO_ACTION) {
216
+ return {
217
+ invoiceId: invoice.id,
218
+ decision: evaluation.decision,
219
+ reason: evaluation.reason,
220
+ executed: false,
221
+ };
222
+ }
223
+
224
+ if (evaluation.decision === AgentDecisionType.REQUIRE_APPROVAL || evaluation.decision === AgentDecisionType.DISPUTE_REVIEW) {
225
+ const actionId = `ACT-${Date.now()}-${Math.floor(Math.random() * 10000)}`;
226
+ const actionRecord = {
227
+ id: actionId,
228
+ invoiceId: invoice.id,
229
+ customerName: invoice.customer.name,
230
+ balance: invoice.balance,
231
+ decision: evaluation.decision,
232
+ status: ActionStatus.PENDING_APPROVAL,
233
+ approvalReasons: evaluation.approvalReasons,
234
+ draftMessage: evaluation.draftMessage || null,
235
+ priority: evaluation.priority,
236
+ createdAt: new Date().toISOString(),
237
+ executedAt: null,
238
+ };
239
+
240
+ this.actions.set(actionId, actionRecord);
241
+ this._logAudit('ACTION_FLAGGED_FOR_APPROVAL', {
242
+ actionId,
243
+ invoiceId: invoice.id,
244
+ reasons: evaluation.approvalReasons,
245
+ balance: invoice.balance,
246
+ });
247
+
248
+ return actionRecord;
249
+ }
250
+
251
+ if (evaluation.decision === AgentDecisionType.SAFE_REMINDER) {
252
+ if (this.autoSendSafeReminders) {
253
+ return this._executeReminder(invoice, evaluation.draftMessage, 'AUTOMATED_SAFE_DISPATCH');
254
+ } else {
255
+ const actionId = `ACT-${Date.now()}-${Math.floor(Math.random() * 10000)}`;
256
+ const actionRecord = {
257
+ id: actionId,
258
+ invoiceId: invoice.id,
259
+ customerName: invoice.customer.name,
260
+ balance: invoice.balance,
261
+ decision: evaluation.decision,
262
+ status: ActionStatus.PENDING_APPROVAL,
263
+ approvalReasons: ['Auto-send disabled by configuration'],
264
+ draftMessage: evaluation.draftMessage,
265
+ priority: evaluation.priority,
266
+ createdAt: new Date().toISOString(),
267
+ executedAt: null,
268
+ };
269
+ this.actions.set(actionId, actionRecord);
270
+ return actionRecord;
271
+ }
272
+ }
273
+
274
+ return evaluation;
275
+ }
276
+
277
+ /**
278
+ * Approves a pending action and executes it immediately.
279
+ *
280
+ * @param {string} actionId
281
+ * @param {Object} approverDetails - { name, email, notes }
282
+ * @returns {Object} Executed action record
283
+ */
284
+ approveAction(actionId, approverDetails = {}) {
285
+ const action = this.actions.get(actionId);
286
+ if (!action) {
287
+ throw new Error(`Action not found: ${actionId}`);
288
+ }
289
+ if (action.status !== ActionStatus.PENDING_APPROVAL) {
290
+ throw new Error(`Action ${actionId} cannot be approved from status: ${action.status}`);
291
+ }
292
+
293
+ const invoice = this.getInvoice(action.invoiceId);
294
+ if (!invoice) {
295
+ throw new Error(`Invoice not found for action: ${action.invoiceId}`);
296
+ }
297
+
298
+ action.status = ActionStatus.APPROVED;
299
+ action.approvedBy = {
300
+ name: approverDetails.name || 'System Admin',
301
+ email: approverDetails.email || 'admin@cashhound.io',
302
+ notes: approverDetails.notes || '',
303
+ approvedAt: new Date().toISOString(),
304
+ };
305
+
306
+ if (action.draftMessage) {
307
+ const commRecord = invoice.recordCommunication({
308
+ tier: action.draftMessage.tier,
309
+ tone: action.draftMessage.tone,
310
+ subject: action.draftMessage.subject,
311
+ body: action.draftMessage.body,
312
+ status: 'sent',
313
+ requiresApproval: false,
314
+ });
315
+ action.communicationRecord = commRecord;
316
+ }
317
+
318
+ action.executedAt = new Date().toISOString();
319
+ this._logAudit('ACTION_APPROVED_AND_EXECUTED', {
320
+ actionId,
321
+ invoiceId: invoice.id,
322
+ approver: action.approvedBy.name,
323
+ });
324
+
325
+ return action;
326
+ }
327
+
328
+ /**
329
+ * Rejects a pending action with explanation.
330
+ *
331
+ * @param {string} actionId
332
+ * @param {string} reason
333
+ * @param {Object} [rejectorDetails={}]
334
+ * @returns {Object} Rejected action record
335
+ */
336
+ rejectAction(actionId, reason, rejectorDetails = {}) {
337
+ const action = this.actions.get(actionId);
338
+ if (!action) {
339
+ throw new Error(`Action not found: ${actionId}`);
340
+ }
341
+ if (action.status !== ActionStatus.PENDING_APPROVAL) {
342
+ throw new Error(`Action ${actionId} cannot be rejected from status: ${action.status}`);
343
+ }
344
+
345
+ action.status = ActionStatus.REJECTED;
346
+ action.rejectedBy = {
347
+ name: rejectorDetails.name || 'System Admin',
348
+ email: rejectorDetails.email || 'admin@cashhound.io',
349
+ reason: reason || 'Action rejected by operator',
350
+ rejectedAt: new Date().toISOString(),
351
+ };
352
+
353
+ this._logAudit('ACTION_REJECTED', {
354
+ actionId,
355
+ invoiceId: action.invoiceId,
356
+ reason,
357
+ rejector: action.rejectedBy.name,
358
+ });
359
+
360
+ return action;
361
+ }
362
+
363
+ /**
364
+ * Handles payment arrival, reconciles balance, clears pending dunning actions,
365
+ * drafts/sends a payment receipt, and records audit trail.
366
+ *
367
+ * @param {string} invoiceId
368
+ * @param {Object} paymentDetails - { amount, method, reference, date }
369
+ * @returns {Object} Reconciliation summary
370
+ */
371
+ recordPayment(invoiceId, paymentDetails) {
372
+ const invoice = this.getInvoice(invoiceId);
373
+ if (!invoice) {
374
+ throw new Error(`Invoice not found: ${invoiceId}`);
375
+ }
376
+
377
+ const { amount, method = 'electronic', reference = '', date = new Date() } = paymentDetails;
378
+ const initialBalance = invoice.balance;
379
+ const pmtResult = invoice.applyPayment({ amount, date, method, reference });
380
+
381
+ // Cancel any active pending dunning actions on this invoice
382
+ const cancelledActions = [];
383
+ for (const action of this.actions.values()) {
384
+ if (action.invoiceId === invoiceId && action.status === ActionStatus.PENDING_APPROVAL) {
385
+ action.status = ActionStatus.CANCELLED;
386
+ action.cancelledReason = `Payment of $${amount.toFixed(2)} received; pending action superseded`;
387
+ cancelledActions.push(action.id);
388
+ }
389
+ }
390
+
391
+ // Create receipt acknowledgment message
392
+ const receiptSubject = `Payment Received - Thank You (Invoice ${invoice.id})`;
393
+ const receiptBody = [
394
+ `Dear ${invoice.customer.name},`,
395
+ '',
396
+ `Thank you! We have successfully received and applied your payment of $${amount.toFixed(2)}.`,
397
+ `Invoice: ${invoice.id}`,
398
+ `Payment Reference: ${reference || pmtResult.paymentRecord.id}`,
399
+ `Remaining Balance: $${pmtResult.remainingBalance.toFixed(2)}`,
400
+ '',
401
+ pmtResult.isFullyPaid
402
+ ? `This invoice is now fully settled. We appreciate your business!`
403
+ : `Your remaining balance of $${pmtResult.remainingBalance.toFixed(2)} remains due according to standard terms.`,
404
+ '',
405
+ `Best regards,`,
406
+ `Finance & Accounts Receivable`,
407
+ ].join('\n');
408
+
409
+ const receiptComm = invoice.recordCommunication({
410
+ tier: 0,
411
+ tone: 'friendly',
412
+ subject: receiptSubject,
413
+ body: receiptBody,
414
+ status: 'sent',
415
+ requiresApproval: false,
416
+ });
417
+
418
+ this._logAudit('PAYMENT_RECONCILED', {
419
+ invoiceId,
420
+ amount,
421
+ initialBalance,
422
+ remainingBalance: pmtResult.remainingBalance,
423
+ isFullyPaid: pmtResult.isFullyPaid,
424
+ cancelledPendingActions: cancelledActions,
425
+ });
426
+
427
+ return {
428
+ invoiceId,
429
+ initialBalance,
430
+ amountPaid: amount,
431
+ remainingBalance: pmtResult.remainingBalance,
432
+ isFullyPaid: pmtResult.isFullyPaid,
433
+ receiptCommunication: receiptComm,
434
+ cancelledActions,
435
+ };
436
+ }
437
+
438
+ /**
439
+ * Reconciles a payment received from an external feed/webhook with CashHound.
440
+ * Alias for recordPayment with flexible parameter names.
441
+ *
442
+ * @param {string} invoiceId
443
+ * @param {Object} paymentDetails
444
+ * @returns {Object}
445
+ */
446
+ reconcilePayment(invoiceId, paymentDetails) {
447
+ return this.recordPayment(invoiceId, {
448
+ amount: paymentDetails.amount,
449
+ method: paymentDetails.method || paymentDetails.paymentMethod || 'electronic',
450
+ reference: paymentDetails.reference || paymentDetails.txId || '',
451
+ date: paymentDetails.date || paymentDetails.paidAt || new Date(),
452
+ });
453
+ }
454
+
455
+ /**
456
+ * Raises a dispute on an invoice.
457
+ *
458
+ * @param {string} invoiceId
459
+ * @param {Object} disputeDetails
460
+ * @returns {Invoice}
461
+ */
462
+ raiseDispute(invoiceId, disputeDetails) {
463
+ const invoice = this.getInvoice(invoiceId);
464
+ if (!invoice) throw new Error(`Invoice not found: ${invoiceId}`);
465
+ invoice.markDisputed(disputeDetails);
466
+ this._logAudit('DISPUTE_RAISED', {
467
+ invoiceId,
468
+ isLegal: Boolean(disputeDetails.isLegal),
469
+ reason: disputeDetails.reason,
470
+ });
471
+ return invoice;
472
+ }
473
+
474
+ /**
475
+ * Resolves an open dispute on an invoice.
476
+ *
477
+ * @param {string} invoiceId
478
+ * @param {Object} resolutionDetails
479
+ * @returns {Invoice}
480
+ */
481
+ resolveDispute(invoiceId, resolutionDetails) {
482
+ const invoice = this.getInvoice(invoiceId);
483
+ if (!invoice) throw new Error(`Invoice not found: ${invoiceId}`);
484
+ invoice.resolveDispute(resolutionDetails);
485
+ this._logAudit('DISPUTE_RESOLVED', {
486
+ invoiceId,
487
+ resolution: resolutionDetails.resolution,
488
+ });
489
+ return invoice;
490
+ }
491
+
492
+ /**
493
+ * Retrieves all currently pending actions requiring human approval.
494
+ * @returns {Object[]}
495
+ */
496
+ getPendingApprovals() {
497
+ return Array.from(this.actions.values()).filter(
498
+ act => act.status === ActionStatus.PENDING_APPROVAL
499
+ );
500
+ }
501
+
502
+ /**
503
+ * Executes a periodic evaluation cycle across all registered invoices.
504
+ *
505
+ * @param {Date|string} [asOfDate=new Date()]
506
+ * @returns {Object} Cycle summary report
507
+ */
508
+ runCycle(asOfDate = new Date()) {
509
+ const asOf = new Date(asOfDate);
510
+ const summary = {
511
+ asOfDate: asOf.toISOString(),
512
+ totalInvoices: this.invoices.size,
513
+ totalOutstandingBalance: 0,
514
+ agingBreakdown: {
515
+ [AgingBuckets.CURRENT]: 0,
516
+ [AgingBuckets.DAYS_30]: 0,
517
+ [AgingBuckets.DAYS_60]: 0,
518
+ [AgingBuckets.DAYS_90]: 0,
519
+ },
520
+ actionsAutoSent: 0,
521
+ actionsFlaggedForApproval: 0,
522
+ noActionCount: 0,
523
+ flaggedHighValueCount: 0,
524
+ legalDisputeCount: 0,
525
+ processedInvoices: [],
526
+ };
527
+
528
+ for (const invoice of this.invoices.values()) {
529
+ summary.totalOutstandingBalance = Number((summary.totalOutstandingBalance + invoice.balance).toFixed(2));
530
+ const bucket = invoice.getAgingBucket(asOf);
531
+ summary.agingBreakdown[bucket] = (summary.agingBreakdown[bucket] || 0) + 1;
532
+
533
+ if (invoice.isLegalDispute()) {
534
+ summary.legalDisputeCount++;
535
+ }
536
+ if (invoice.balance >= this.highValueThreshold) {
537
+ summary.flaggedHighValueCount++;
538
+ }
539
+
540
+ const result = this.processInvoice(invoice, asOf);
541
+ summary.processedInvoices.push(result);
542
+
543
+ if (result.status === ActionStatus.PENDING_APPROVAL) {
544
+ summary.actionsFlaggedForApproval++;
545
+ } else if (result.status === ActionStatus.AUTO_EXECUTED) {
546
+ summary.actionsAutoSent++;
547
+ } else {
548
+ summary.noActionCount++;
549
+ }
550
+ }
551
+
552
+ this._logAudit('CYCLE_COMPLETED', {
553
+ totalInvoices: summary.totalInvoices,
554
+ totalBalance: summary.totalOutstandingBalance,
555
+ autoSent: summary.actionsAutoSent,
556
+ flaggedForApproval: summary.actionsFlaggedForApproval,
557
+ });
558
+
559
+ return summary;
560
+ }
561
+
562
+ /**
563
+ * Returns immutable copy of the audit log.
564
+ * @returns {Object[]}
565
+ */
566
+ getAuditLog() {
567
+ return [...this.auditTrail];
568
+ }
569
+
570
+ // --- Internal helpers ---
571
+
572
+ _executeReminder(invoice, draftMessage, executionMode) {
573
+ const commRecord = invoice.recordCommunication({
574
+ tier: draftMessage.tier,
575
+ tone: draftMessage.tone,
576
+ subject: draftMessage.subject,
577
+ body: draftMessage.body,
578
+ status: 'sent',
579
+ requiresApproval: false,
580
+ });
581
+
582
+ const actionId = `ACT-${Date.now()}-${Math.floor(Math.random() * 10000)}`;
583
+ const actionRecord = {
584
+ id: actionId,
585
+ invoiceId: invoice.id,
586
+ customerName: invoice.customer.name,
587
+ balance: invoice.balance,
588
+ decision: AgentDecisionType.SAFE_REMINDER,
589
+ status: ActionStatus.AUTO_EXECUTED,
590
+ executionMode,
591
+ draftMessage,
592
+ communicationRecord: commRecord,
593
+ createdAt: new Date().toISOString(),
594
+ executedAt: new Date().toISOString(),
595
+ };
596
+
597
+ this.actions.set(actionId, actionRecord);
598
+ this._logAudit('SAFE_REMINDER_AUTO_SENT', {
599
+ actionId,
600
+ invoiceId: invoice.id,
601
+ tier: draftMessage.tier,
602
+ balance: invoice.balance,
603
+ });
604
+
605
+ return actionRecord;
606
+ }
607
+
608
+ _getMostRecentCommunication(invoice) {
609
+ if (!invoice.communications || invoice.communications.length === 0) return null;
610
+ return invoice.communications[invoice.communications.length - 1];
611
+ }
612
+
613
+ _logAudit(eventType, payload) {
614
+ this.auditTrail.push({
615
+ id: `AUDIT-${Date.now()}-${Math.floor(Math.random() * 10000)}`,
616
+ timestamp: new Date().toISOString(),
617
+ eventType,
618
+ payload,
619
+ });
620
+ }
621
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * CashHound Real-Time Bank Feed & Webhook Auto-Reconciler:
3
+ * Ingests inbound ACH/wire/Stripe transfer events, extracts invoice tags from memo text,
4
+ * and automatically reconciles accounts, terminating active dunning actions.
5
+ */
6
+
7
+ export class BankFeedReconciler {
8
+ constructor(agent) {
9
+ this.agent = agent;
10
+ this.reconciledEvents = [];
11
+ }
12
+
13
+ processWebhookEvent(event) {
14
+ // event: { amount, memo: "Payment for INV-1094 ref 8923", sender: "Acme Corp", txId: "tx_ach_992" }
15
+ const { amount, memo = '', sender = 'Unknown', txId = `tx_${Date.now()}` } = event;
16
+
17
+ if (typeof amount !== 'number' || amount <= 0) {
18
+ throw new Error('Event amount must be a positive number');
19
+ }
20
+
21
+ // Extract invoice ID matching patterns (e.g. INV-1094, INV_101, INV102)
22
+ const match = memo.match(/\bINV[-_]?[A-Z0-9]+\b/i);
23
+ const invoiceId = match ? match[0].toUpperCase() : null;
24
+
25
+ if (!invoiceId) {
26
+ return {
27
+ matched: false,
28
+ reason: 'No invoice tag found in bank transfer memo',
29
+ txId,
30
+ memo
31
+ };
32
+ }
33
+
34
+ const invoice = this.agent.getInvoice(invoiceId);
35
+ if (!invoice) {
36
+ return {
37
+ matched: false,
38
+ invoiceId,
39
+ reason: `Invoice '${invoiceId}' is not registered with CashHound`,
40
+ txId
41
+ };
42
+ }
43
+
44
+ // Reconcile payment with agent
45
+ const paymentRecord = this.agent.recordPayment(invoiceId, {
46
+ amount,
47
+ method: 'ACH_BANK_TRANSFER',
48
+ reference: txId,
49
+ date: new Date()
50
+ });
51
+
52
+ const reconciliationReceipt = {
53
+ matched: true,
54
+ invoiceId,
55
+ customerName: invoice.customer?.name || sender,
56
+ amountSettled: amount,
57
+ remainingBalance: invoice.balance,
58
+ isFullyPaid: invoice.balance <= 0,
59
+ cancelledPendingDunningCount: paymentRecord.cancelledActions?.length || 0,
60
+ reconciledAt: new Date().toISOString()
61
+ };
62
+
63
+ this.reconciledEvents.push(reconciliationReceipt);
64
+ return reconciliationReceipt;
65
+ }
66
+ }