@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,47 @@
1
+ import { SubscriptionManager } from './subscription-manager.js';
2
+ import { ConflictEngine } from './conflict-engine.js';
3
+
4
+ /**
5
+ * OmniLife Agent: Autonomous Life Operating System with Human-in-the-Loop Safeguards.
6
+ */
7
+ export class OmniLifeAgent {
8
+ constructor(userName = 'User') {
9
+ this.userName = userName;
10
+ this.subscriptions = new SubscriptionManager();
11
+ this.conflictEngine = new ConflictEngine();
12
+ this.actionHistory = [];
13
+ }
14
+
15
+ evaluateLifeOSStatus(calendarEvents = [], passportExpiry = null, upcomingTripDeparture = null) {
16
+ const dormantSubs = this.subscriptions.findDormantSubscriptions(90);
17
+ const subPlans = dormantSubs.map(s => this.subscriptions.planCancellation(s.id));
18
+
19
+ let passportAlert = null;
20
+ if (passportExpiry && upcomingTripDeparture) {
21
+ passportAlert = this.conflictEngine.checkPassportValidity(passportExpiry, upcomingTripDeparture);
22
+ }
23
+
24
+ const calendarConflicts = this.conflictEngine.detectCalendarConflicts(calendarEvents);
25
+
26
+ return {
27
+ user: this.userName,
28
+ dormantSubscriptions: subPlans,
29
+ passportAlert,
30
+ calendarConflicts,
31
+ pendingApprovals: subPlans.filter(p => p.requiresHumanApproval)
32
+ };
33
+ }
34
+
35
+ approveCancellation(subId, approved = true) {
36
+ if (!approved) {
37
+ return { status: 'REJECTED_BY_USER', subId };
38
+ }
39
+ const cancelled = this.subscriptions.cancelSubscription(subId, approved);
40
+ this.actionHistory.push({
41
+ action: 'CANCEL_SUBSCRIPTION',
42
+ subId,
43
+ timestamp: new Date().toISOString()
44
+ });
45
+ return { status: 'CANCELLED_SUCCESSFULLY', subscription: cancelled };
46
+ }
47
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * OmniLife Bill Negotiation Striker: Scans utility and telecom bills,
3
+ * detects expired promotional discounts, and generates negotiation battlecards.
4
+ */
5
+
6
+ export const MARKET_BENCHMARKS = {
7
+ internet_fiber: { benchmarkMonthlyCents: 5500, maxAcceptableMonthlyCents: 7500 },
8
+ wireless_single_line: { benchmarkMonthlyCents: 4500, maxAcceptableMonthlyCents: 7000 },
9
+ cable_bundle: { benchmarkMonthlyCents: 8500, maxAcceptableMonthlyCents: 12000 }
10
+ };
11
+
12
+ export class BillNegotiator {
13
+ analyzeBill(bill) {
14
+ const { provider, category = 'internet_fiber', currentMonthlyCents, tenureMonths = 12 } = bill;
15
+ const benchmark = MARKET_BENCHMARKS[category] || MARKET_BENCHMARKS.internet_fiber;
16
+
17
+ const isOverpaying = currentMonthlyCents > benchmark.benchmarkMonthlyCents;
18
+ const monthlyOverpaymentCents = isOverpaying ? currentMonthlyCents - benchmark.benchmarkMonthlyCents : 0;
19
+ const projectedAnnualSavingsCents = monthlyOverpaymentCents * 12;
20
+
21
+ const leveragePoints = [
22
+ `Customer has been with ${provider} for ${tenureMonths} consecutive months with on-time payments.`,
23
+ `Competitor offers in your zip code currently provide equivalent service for $${(benchmark.benchmarkMonthlyCents / 100).toFixed(2)}/mo.`,
24
+ `Promotion rate has expired, causing an unnotified monthly surcharge of $${(monthlyOverpaymentCents / 100).toFixed(2)}.`
25
+ ];
26
+
27
+ const battlecard = {
28
+ provider,
29
+ category,
30
+ currentMonthlyFormatted: `$${(currentMonthlyCents / 100).toFixed(2)}`,
31
+ targetMonthlyFormatted: `$${(benchmark.benchmarkMonthlyCents / 100).toFixed(2)}`,
32
+ projectedAnnualSavingsFormatted: `$${(projectedAnnualSavingsCents / 100).toFixed(2)}`,
33
+ recommendedScript: `Hello, I noticed my introductory promotion expired and my rate increased to $${(currentMonthlyCents / 100).toFixed(2)}/mo. Competitors are offering the same speed for $${(benchmark.benchmarkMonthlyCents / 100).toFixed(2)}. I value your service, but I need to lower my bill or cancel before the next cycle. What loyalty discounts can you apply today?`,
34
+ leveragePoints
35
+ };
36
+
37
+ return {
38
+ hasSavingsOpportunity: isOverpaying,
39
+ annualSavingsCents: projectedAnnualSavingsCents,
40
+ battlecard
41
+ };
42
+ }
43
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * OmniLife Zero-Click Cancellation Planner: Synthesizes automated browser navigation steps
3
+ * to bypass provider retention funnels and complete account cancellation once approved.
4
+ */
5
+
6
+ export class BrowserCancellationPlanner {
7
+ buildNavigationGraph(serviceName, accountIdentifier) {
8
+ const serviceSlug = serviceName.toLowerCase().replace(/\s+/g, '_');
9
+
10
+ const steps = [
11
+ { step: 1, action: 'NAVIGATE', target: `https://${serviceSlug}.com/account/settings/billing` },
12
+ { step: 2, action: 'AUTHENTICATE_SESSION', targetSelector: '#account-security-badge', account: accountIdentifier },
13
+ { step: 3, action: 'CLICK_TERMINATION', targetSelector: 'button[data-action="cancel-subscription"]' },
14
+ { step: 4, action: 'DISMISS_RETENTION_OFFERS', targetSelector: '.retention-modal .btn-decline-offer', reason: 'User confirmed cancellation' },
15
+ { step: 5, action: 'CONFIRM_FINAL_TERMINATION', targetSelector: '#confirm-cancellation-checkbox', verifyState: true },
16
+ { step: 6, action: 'CAPTURE_RECEIPT', targetSelector: '.cancellation-confirmation-code', saveArtifact: true }
17
+ ];
18
+
19
+ return {
20
+ serviceName,
21
+ accountIdentifier,
22
+ totalSteps: steps.length,
23
+ isFullyAutomated: true,
24
+ executionPlan: steps,
25
+ safetyCheck: 'Requires explicit user approval before step 5 execution.'
26
+ };
27
+ }
28
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * OmniLife Conflict & Deadline Engine: Discovers travel passport validity windows and calendar collisions.
3
+ */
4
+
5
+ export class ConflictEngine {
6
+ checkPassportValidity(passportExpiryIso, departureDateIso) {
7
+ const expiry = new Date(passportExpiryIso).getTime();
8
+ const departure = new Date(departureDateIso).getTime();
9
+
10
+ // 6-month validity rule standard for international travel
11
+ const sixMonthsMs = 180 * 24 * 60 * 60 * 1000;
12
+ const remainingTime = expiry - departure;
13
+
14
+ if (remainingTime < sixMonthsMs) {
15
+ const daysLeft = Math.floor(remainingTime / (24 * 60 * 60 * 1000));
16
+ return {
17
+ compliant: false,
18
+ severity: 'CRITICAL',
19
+ issue: `Passport expires within ${daysLeft} days of travel. Minimum 6 months (180 days) validity required by immigration.`,
20
+ recommendedAction: 'EXPEDITE_PASSPORT_RENEWAL'
21
+ };
22
+ }
23
+
24
+ return { compliant: true };
25
+ }
26
+
27
+ detectCalendarConflicts(events = []) {
28
+ const sorted = [...events].sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime());
29
+ const conflicts = [];
30
+
31
+ for (let i = 0; i < sorted.length - 1; i++) {
32
+ const current = sorted[i];
33
+ const next = sorted[i + 1];
34
+
35
+ const currentEnd = new Date(current.end).getTime();
36
+ const nextStart = new Date(next.start).getTime();
37
+
38
+ if (currentEnd > nextStart) {
39
+ conflicts.push({
40
+ eventA: current,
41
+ eventB: next,
42
+ overlapMinutes: Math.round((currentEnd - nextStart) / (60 * 1000))
43
+ });
44
+ }
45
+ }
46
+
47
+ return conflicts;
48
+ }
49
+ }
@@ -0,0 +1,6 @@
1
+ export { SubscriptionManager } from './subscription-manager.js';
2
+ export { ConflictEngine } from './conflict-engine.js';
3
+ export { OmniLifeAgent } from './agent.js';
4
+ export { OmniLifeMobileAdapter } from './mobile.js';
5
+ export { BillNegotiator } from './bill-negotiator.js';
6
+ export { BrowserCancellationPlanner } from './browser-cancel.js';
@@ -0,0 +1,18 @@
1
+ /**
2
+ * OmniLife Mobile Adapter: Formats mobile life OS cards and 1-tap subscription cancellation payloads.
3
+ */
4
+
5
+ export class OmniLifeMobileAdapter {
6
+ constructor(agent) {
7
+ this.agent = agent;
8
+ }
9
+
10
+ getMobileOutcomeCard() {
11
+ return {
12
+ title: 'OmniLife Operating System',
13
+ outcomeMetric: 'Optimized',
14
+ user: this.agent.userName,
15
+ statusBadge: 'GUARDIAN_ONLINE'
16
+ };
17
+ }
18
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * OmniLife Subscription Manager: Audits recurring expenses, detects dormancy, and plans safe cancellation.
3
+ * Hardened to prevent unauthorized contract cancellations without explicit user approval.
4
+ */
5
+
6
+ export class SubscriptionManager {
7
+ constructor() {
8
+ this.subscriptions = [];
9
+ }
10
+
11
+ addSubscription(sub) {
12
+ this.subscriptions.push({
13
+ id: sub.id || `sub_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
14
+ name: sub.name,
15
+ monthlyCostCents: sub.monthlyCostCents,
16
+ lastUsedDaysAgo: sub.lastUsedDaysAgo || 0,
17
+ hasEarlyTerminationPenalty: Boolean(sub.hasEarlyTerminationPenalty),
18
+ penaltyAmountCents: sub.penaltyAmountCents || 0,
19
+ status: 'ACTIVE'
20
+ });
21
+ }
22
+
23
+ findDormantSubscriptions(dormantThresholdDays = 90) {
24
+ return this.subscriptions.filter(
25
+ s => s.status === 'ACTIVE' && s.lastUsedDaysAgo >= dormantThresholdDays
26
+ );
27
+ }
28
+
29
+ planCancellation(subId) {
30
+ const sub = this.subscriptions.find(s => s.id === subId);
31
+ if (!sub) throw new Error(`Subscription ${subId} not found`);
32
+
33
+ const annualSavingsCents = sub.monthlyCostCents * 12;
34
+
35
+ if (sub.hasEarlyTerminationPenalty) {
36
+ return {
37
+ subscription: sub,
38
+ requiresHumanApproval: true,
39
+ reason: `Early cancellation penalty of $${(sub.penaltyAmountCents / 100).toFixed(2)} applies`,
40
+ projectedNetYearlySavingsCents: annualSavingsCents - sub.penaltyAmountCents,
41
+ action: 'HUMAN_APPROVAL_REQUIRED'
42
+ };
43
+ }
44
+
45
+ return {
46
+ subscription: sub,
47
+ requiresHumanApproval: false,
48
+ projectedNetYearlySavingsCents: annualSavingsCents,
49
+ action: 'SAFE_TO_CANCEL'
50
+ };
51
+ }
52
+
53
+ // SEC-09: Require explicit approval authorization before cancelling subscriptions with financial penalties
54
+ cancelSubscription(subId, isUserApproved = false) {
55
+ const sub = this.subscriptions.find(s => s.id === subId);
56
+ if (!sub) throw new Error(`Subscription ${subId} not found`);
57
+
58
+ if (sub.hasEarlyTerminationPenalty && !isUserApproved) {
59
+ throw new Error(`Cancellation blocked: subscription '${sub.name}' incurs penalty of $${(sub.penaltyAmountCents / 100).toFixed(2)} and demands explicit user authorization.`);
60
+ }
61
+
62
+ sub.status = 'CANCELLED';
63
+ sub.cancelledAt = new Date().toISOString();
64
+ return sub;
65
+ }
66
+ }
@@ -0,0 +1,29 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { BillNegotiator, BrowserCancellationPlanner } from '../src/index.js';
4
+
5
+ test('OmniLife Bill Negotiator: analyzes telecom bill and generates negotiation battlecard', () => {
6
+ const negotiator = new BillNegotiator();
7
+ const bill = {
8
+ provider: 'Comcast Xfinity',
9
+ category: 'internet_fiber',
10
+ currentMonthlyCents: 9500, // $95/mo vs $55 benchmark
11
+ tenureMonths: 24
12
+ };
13
+
14
+ const analysis = negotiator.analyzeBill(bill);
15
+ assert.equal(analysis.hasSavingsOpportunity, true);
16
+ // (9500 - 5500) * 12 = 48000 cents ($480/yr)
17
+ assert.equal(analysis.annualSavingsCents, 48000);
18
+ assert.equal(analysis.battlecard.projectedAnnualSavingsFormatted, '$480.00');
19
+ assert.ok(analysis.battlecard.recommendedScript.includes('loyalty discounts'));
20
+ });
21
+
22
+ test('OmniLife Cancellation Planner: builds automated navigation graph to bypass retention steps', () => {
23
+ const planner = new BrowserCancellationPlanner();
24
+ const plan = planner.buildNavigationGraph('Gym Fitness', 'member-10294');
25
+
26
+ assert.equal(plan.totalSteps, 6);
27
+ assert.equal(plan.executionPlan[3].action, 'DISMISS_RETENTION_OFFERS');
28
+ assert.equal(plan.executionPlan[4].action, 'CONFIRM_FINAL_TERMINATION');
29
+ });
@@ -0,0 +1,12 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { OmniLifeAgent, OmniLifeMobileAdapter } from '../src/index.js';
4
+
5
+ test('OmniLife Mobile Adapter: formats mobile life OS cards', () => {
6
+ const agent = new OmniLifeAgent('Jane');
7
+ const mobile = new OmniLifeMobileAdapter(agent);
8
+
9
+ const card = mobile.getMobileOutcomeCard();
10
+ assert.equal(card.title, 'OmniLife Operating System');
11
+ assert.equal(card.statusBadge, 'GUARDIAN_ONLINE');
12
+ });
@@ -0,0 +1,71 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { OmniLifeAgent } from '../src/index.js';
4
+
5
+ test('OmniLife: detects dormant subscriptions and enforces approval for penalties', () => {
6
+ const agent = new OmniLifeAgent('Jane');
7
+ agent.subscriptions.addSubscription({
8
+ id: 'sub-gym',
9
+ name: 'Fitness Gym Gold',
10
+ monthlyCostCents: 6000,
11
+ lastUsedDaysAgo: 120,
12
+ hasEarlyTerminationPenalty: true,
13
+ penaltyAmountCents: 5000
14
+ });
15
+
16
+ agent.subscriptions.addSubscription({
17
+ id: 'sub-stream',
18
+ name: 'Obsolete Streaming App',
19
+ monthlyCostCents: 1500,
20
+ lastUsedDaysAgo: 95,
21
+ hasEarlyTerminationPenalty: false
22
+ });
23
+
24
+ const status = agent.evaluateLifeOSStatus();
25
+ assert.equal(status.dormantSubscriptions.length, 2);
26
+ assert.equal(status.pendingApprovals.length, 1);
27
+ assert.equal(status.pendingApprovals[0].subscription.id, 'sub-gym');
28
+
29
+ // User approves cancellation
30
+ const cancelRes = agent.approveCancellation('sub-gym', true);
31
+ assert.equal(cancelRes.status, 'CANCELLED_SUCCESSFULLY');
32
+ assert.equal(cancelRes.subscription.status, 'CANCELLED');
33
+ });
34
+
35
+ test('OmniLife: warns on international passport validity window violation', () => {
36
+ const agent = new OmniLifeAgent('Jane');
37
+
38
+ // Trip departure: 2027-01-01, Passport expiry: 2027-02-01 (< 6 months)
39
+ const status = agent.evaluateLifeOSStatus([], '2027-02-01T00:00:00Z', '2027-01-01T00:00:00Z');
40
+ assert.equal(status.passportAlert.compliant, false);
41
+ assert.equal(status.passportAlert.severity, 'CRITICAL');
42
+ assert.equal(status.passportAlert.recommendedAction, 'EXPEDITE_PASSPORT_RENEWAL');
43
+ });
44
+
45
+ test('OmniLife: detects calendar collisions', () => {
46
+ const agent = new OmniLifeAgent('Jane');
47
+ const events = [
48
+ { title: 'Dentist', start: '2026-12-10T10:00:00Z', end: '2026-12-10T11:30:00Z' },
49
+ { title: 'Project Review', start: '2026-12-10T11:00:00Z', end: '2026-12-10T12:00:00Z' }
50
+ ];
51
+
52
+ const status = agent.evaluateLifeOSStatus(events);
53
+ assert.equal(status.calendarConflicts.length, 1);
54
+ assert.equal(status.calendarConflicts[0].overlapMinutes, 30);
55
+ });
56
+
57
+ test('OmniLife Security: blocks unapproved cancellation of penalty subscriptions', () => {
58
+ const agent = new OmniLifeAgent('Jane');
59
+ agent.subscriptions.addSubscription({
60
+ id: 'sub-penalty-gym',
61
+ name: 'Hardcore Gym',
62
+ monthlyCostCents: 5000,
63
+ hasEarlyTerminationPenalty: true,
64
+ penaltyAmountCents: 10000
65
+ });
66
+
67
+ // Direct cancellation without approval throws error
68
+ assert.throws(() => {
69
+ agent.subscriptions.cancelSubscription('sub-penalty-gym', false);
70
+ }, /demands explicit user authorization/);
71
+ });
@@ -0,0 +1,42 @@
1
+ # PulseMD — Autonomous Clinical Operations & Prior-Authorization Agent
2
+
3
+ **PulseMD** reduces clinician administrative burden by converting raw clinical encounters into structured SOAP chart notes, automating prior-authorization verification against payer criteria, and strictly enforcing licensed clinician sign-off gates.
4
+
5
+ ## Capabilities
6
+
7
+ 1. **Autonomous SOAP Charting:** Generates structured Subjective, Objective, Assessment, and Plan drafts directly from patient encounters.
8
+ 2. **Prior-Authorization Verification Engine:** Cross-checks patient treatment records against payer prerequisite rules (CPT codes, physical therapy trials, radiographic evidence) before submission.
9
+ 3. **Mandatory Clinician Approval Gate:** Enforces human-in-the-loop sign-off on all clinical documentation and insurer filings to guarantee patient safety and regulatory compliance.
10
+ 4. **Audit & Traceability:** Retains complete cryptographic logs of revisions and physician signatures.
11
+
12
+ ## Usage
13
+
14
+ ```javascript
15
+ import { PulseMDAgent } from 'pulsemd-agent';
16
+
17
+ const agent = new PulseMDAgent();
18
+
19
+ // 1. Process encounter notes into draft SOAP record
20
+ const draft = agent.processEncounter({
21
+ patientId: 'pt-1001',
22
+ chiefComplaint: 'Right knee pain after sports injury',
23
+ vitals: { bp: '124/82', hr: '76' },
24
+ conversation: 'Twisted knee during soccer match.'
25
+ });
26
+
27
+ // 2. Clinician reviews and signs
28
+ const lockedNote = agent.signAndFinalizeNote(draft.draftNote.draftId, 'dr-smith-md');
29
+
30
+ // 3. Evaluate prior-auth criteria for MRI
31
+ const paResult = agent.evaluatePriorAuth('pt-1001', 'mri_lumbar', {
32
+ physical_therapy_completed: true,
33
+ conservative_management_6_weeks: true,
34
+ radiograph_completed: true
35
+ });
36
+ ```
37
+
38
+ ## Testing
39
+
40
+ ```sh
41
+ npm test
42
+ ```
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "pulsemd-agent",
3
+ "version": "0.1.0",
4
+ "description": "PulseMD - Autonomous Clinical Operations, Charting & Prior-Auth Agent",
5
+ "private": true,
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=20"
9
+ },
10
+ "scripts": {
11
+ "test": "node --test"
12
+ }
13
+ }
@@ -0,0 +1,67 @@
1
+ import { ChartingEngine } from './charting.js';
2
+ import { PriorAuthEngine } from './prior-auth.js';
3
+ import { ClinicianAuth } from './auth.js';
4
+
5
+ /**
6
+ * PulseMD Agent: Orchestrates clinical documentation & authorizations with strict clinician sign-off gates.
7
+ */
8
+ export class PulseMDAgent {
9
+ constructor(authSecret = ClinicianAuth.DEFAULT_SECRET) {
10
+ this.charting = new ChartingEngine();
11
+ this.priorAuth = new PriorAuthEngine();
12
+ this.authSecret = authSecret;
13
+ this.signedRecords = [];
14
+ }
15
+
16
+ processEncounter(encounter) {
17
+ const draftNote = this.charting.draftSoapNote(encounter);
18
+ return {
19
+ status: 'AWAITING_CLINICIAN_SIGNATURE',
20
+ draftNote,
21
+ guidance: 'All clinical assessments and orders must be verified and signed by a licensed practitioner.'
22
+ };
23
+ }
24
+
25
+ /**
26
+ * Enforces SEC-02: Cryptographic clinician token verification to prevent impersonation.
27
+ */
28
+ signAndFinalizeNote(draftNoteId, clinicianId, modifications = {}, signatureToken = null) {
29
+ if (!clinicianId) throw new Error('Clinician ID required to sign medical documentation.');
30
+
31
+ const verification = ClinicianAuth.verifyToken(signatureToken, clinicianId, this.authSecret);
32
+ if (!verification.valid) {
33
+ throw new Error(`Unauthorized signature attempt: ${verification.error}`);
34
+ }
35
+
36
+ const finalized = {
37
+ recordId: draftNoteId,
38
+ clinicianId,
39
+ verifiedRole: verification.role,
40
+ signedAt: new Date().toISOString(),
41
+ status: 'FINALIZED_AND_LOCKED',
42
+ signatureToken: signatureToken.slice(0, 16) + '...',
43
+ modifications
44
+ };
45
+
46
+ this.signedRecords.push(finalized);
47
+ return finalized;
48
+ }
49
+
50
+ evaluatePriorAuth(patientId, procedureKey, patientHistory) {
51
+ const packet = this.priorAuth.buildAuthPacket(patientId, procedureKey, patientHistory);
52
+
53
+ if (!packet.isCompliant) {
54
+ return {
55
+ action: 'FLAG_DEFICIENCY',
56
+ missing: packet.missingPrerequisites,
57
+ message: `Payer prior-auth criteria not met: missing ${packet.missingPrerequisites.join(', ')}`
58
+ };
59
+ }
60
+
61
+ return {
62
+ action: 'SUBMIT_FOR_CLINICIAN_APPROVAL',
63
+ packet,
64
+ message: 'Prior authorization criteria verified. Awaiting clinician signature to submit to payer portal.'
65
+ };
66
+ }
67
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * PulseMD Ambient Medical Scribe: Ingests continuous multi-speaker encounter dialogues,
3
+ * synthesizes structured clinical observations, and maps them into FHIR-ready records.
4
+ */
5
+
6
+ export class AmbientMedicalScribe {
7
+ processDialogueStream(dialogueTurns = []) {
8
+ // dialogueTurns: [{ speaker: 'DOCTOR'|'PATIENT', text: '...', timestamp: '...' }]
9
+ const patientStatements = dialogueTurns.filter(t => t.speaker === 'PATIENT').map(t => t.text).join(' ');
10
+ const doctorStatements = dialogueTurns.filter(t => t.speaker === 'DOCTOR').map(t => t.text).join(' ');
11
+
12
+ const lowerPatient = patientStatements.toLowerCase();
13
+
14
+ // Extract symptoms
15
+ const detectedSymptoms = [];
16
+ if (lowerPatient.includes('chest pain') || lowerPatient.includes('pressure')) detectedSymptoms.push('Chest Pressure/Pain');
17
+ if (lowerPatient.includes('shortness of breath') || lowerPatient.includes('breathing')) detectedSymptoms.push('Dyspnea on exertion');
18
+ if (lowerPatient.includes('knee') || lowerPatient.includes('joint')) detectedSymptoms.push('Joint Arthralgia');
19
+ if (lowerPatient.includes('headache') || lowerPatient.includes('migraine')) detectedSymptoms.push('Cephalea/Migraine');
20
+
21
+ // Extract duration
22
+ let duration = 'Undetermined duration';
23
+ if (lowerPatient.includes('3 days') || lowerPatient.includes('few days')) duration = 'Acute (3-4 days)';
24
+ if (lowerPatient.includes('weeks') || lowerPatient.includes('month')) duration = 'Subacute / Chronic';
25
+
26
+ return {
27
+ transcriptLength: dialogueTurns.length,
28
+ extractedObservations: {
29
+ symptoms: detectedSymptoms,
30
+ clinicalDuration: duration,
31
+ patientSubjectiveSummary: patientStatements.slice(0, 300),
32
+ clinicianDirectives: doctorStatements.slice(0, 300)
33
+ },
34
+ fhirResourceDraft: {
35
+ resourceType: 'ClinicalImpression',
36
+ status: 'draft',
37
+ investigation: [
38
+ {
39
+ code: { text: 'Clinical Encounter Symptom Stream' },
40
+ item: detectedSymptoms.map(sym => ({ display: sym }))
41
+ }
42
+ ]
43
+ }
44
+ };
45
+ }
46
+ }
@@ -0,0 +1,63 @@
1
+ import crypto from 'node:crypto';
2
+
3
+ /**
4
+ * PulseMD Clinician Cryptographic Authentication & Token Verifier
5
+ * Enforces non-repudiation and prevents clinician impersonation.
6
+ */
7
+ export class ClinicianAuth {
8
+ static DEFAULT_SECRET = 'pulsemd_secure_signing_key_internal_2026';
9
+
10
+ /**
11
+ * Generates a tamper-proof cryptographic signature token.
12
+ */
13
+ static generateToken(clinicianId, role = 'PHYSICIAN', secret = ClinicianAuth.DEFAULT_SECRET, expiresInMs = 300000) {
14
+ const expiresAt = Date.now() + expiresInMs;
15
+ const nonce = crypto.randomBytes(16).toString('hex');
16
+ const payload = `${clinicianId}:${role}:${expiresAt}:${nonce}`;
17
+ const signature = crypto.createHmac('sha256', secret).update(payload).digest('hex');
18
+ return Buffer.from(`${payload}:${signature}`).toString('base64');
19
+ }
20
+
21
+ /**
22
+ * Validates cryptographic signature token and expiration.
23
+ */
24
+ static verifyToken(token, expectedClinicianId, secret = ClinicianAuth.DEFAULT_SECRET) {
25
+ if (!token || typeof token !== 'string') {
26
+ return { valid: false, error: 'Signature token is missing or malformed' };
27
+ }
28
+
29
+ try {
30
+ const decoded = Buffer.from(token, 'base64').toString('utf-8');
31
+ const parts = decoded.split(':');
32
+ if (parts.length !== 5) {
33
+ return { valid: false, error: 'Invalid token structure' };
34
+ }
35
+
36
+ const [clinicianId, role, expiresAtStr, nonce, receivedSig] = parts;
37
+ const expiresAt = Number.parseInt(expiresAtStr, 10);
38
+
39
+ if (clinicianId !== expectedClinicianId) {
40
+ return { valid: false, error: `Token clinician ID '${clinicianId}' does not match claimed '${expectedClinicianId}'` };
41
+ }
42
+
43
+ if (Date.now() > expiresAt) {
44
+ return { valid: false, error: 'Signature token has expired' };
45
+ }
46
+
47
+ if (role !== 'PHYSICIAN' && role !== 'PRACTITIONER') {
48
+ return { valid: false, error: `Unauthorized clinical role '${role}': must be licensed PHYSICIAN or PRACTITIONER` };
49
+ }
50
+
51
+ const payload = `${clinicianId}:${role}:${expiresAtStr}:${nonce}`;
52
+ const expectedSig = crypto.createHmac('sha256', secret).update(payload).digest('hex');
53
+
54
+ if (!crypto.timingSafeEqual(Buffer.from(receivedSig), Buffer.from(expectedSig))) {
55
+ return { valid: false, error: 'Cryptographic signature verification failed' };
56
+ }
57
+
58
+ return { valid: true, clinicianId, role };
59
+ } catch (err) {
60
+ return { valid: false, error: `Token verification error: ${err.message}` };
61
+ }
62
+ }
63
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * PulseMD Charting Engine: Converts clinical encounter transcripts into structured SOAP notes.
3
+ * Enforces HIPAA-compliant Protected Health Information (PHI) sanitization.
4
+ */
5
+
6
+ export class ChartingEngine {
7
+ /**
8
+ * Redacts sensitive personal identifiers from clinical free-text.
9
+ */
10
+ static sanitizePhi(text) {
11
+ if (!text || typeof text !== 'string') return '';
12
+ return text
13
+ // SSN: 000-00-0000
14
+ .replace(/\b\d{3}-\d{2}-\d{4}\b/g, '[REDACTED_SSN]')
15
+ // Phone: 555-555-5555
16
+ .replace(/\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b/g, '[REDACTED_PHONE]')
17
+ // Email
18
+ .replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g, '[REDACTED_EMAIL]');
19
+ }
20
+
21
+ draftSoapNote(encounter) {
22
+ const { patientId, chiefComplaint, vitals = {}, conversation = '', clinicianName } = encounter;
23
+
24
+ const sanitizedComplaint = ChartingEngine.sanitizePhi(chiefComplaint);
25
+ const sanitizedConversation = ChartingEngine.sanitizePhi(conversation);
26
+
27
+ const subjective = `Patient presents with: ${sanitizedComplaint}. Encounter notes: ${sanitizedConversation}`;
28
+ const objective = `Vitals: BP ${vitals.bp || '120/80'}, HR ${vitals.hr || '72'}, Temp ${vitals.temp || '98.6F'}.`;
29
+
30
+ // Extract preliminary assessment hints
31
+ let assessment = 'Evaluation of symptoms noted in chief complaint.';
32
+ if (sanitizedComplaint.toLowerCase().includes('knee pain')) {
33
+ assessment = 'Suspected internal derangement or osteoarthritis of knee.';
34
+ } else if (sanitizedComplaint.toLowerCase().includes('hypertension')) {
35
+ assessment = 'Essential hypertension, follow-up control.';
36
+ }
37
+
38
+ const plan = 'Draft recommendation: obtain diagnostic imaging or lab follow-up as reviewed by physician.';
39
+
40
+ return {
41
+ draftId: `soap_${Date.now()}`,
42
+ patientId: ChartingEngine.sanitizePhi(patientId),
43
+ clinicianName,
44
+ status: 'DRAFT_PENDING_PHYSICIAN_SIGNATURE',
45
+ soap: {
46
+ subjective,
47
+ objective,
48
+ assessment,
49
+ plan
50
+ },
51
+ createdAt: new Date().toISOString()
52
+ };
53
+ }
54
+ }