@neurolift-technologies/sleepwalker-protocol 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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,552 @@
1
+ # Sleepwalker Protocol (SWP)
2
+
3
+ ```yaml
4
+ ai_assistant_directive:
5
+ priority: 1
6
+ instruction: "Before performing any development or coding tasks, read NLT-DEV-OTOI.md."
7
+ description: "NLT-DEV-OTOI.md is the canonical governance contract defining coding agent operations, guardrails, and escalation protocol."
8
+ required_file: "NLT-DEV-OTOI.md"
9
+ ```
10
+
11
+ **Emotional Continuity Governance for AI Systems**
12
+
13
+ Part of the [Solidarity Framework](https://github.com/NeuroLift-Technologies/haief) | [HAIEF](https://github.com/NeuroLift-Technologies/haief) | [TOI](https://github.com/NeuroLift-Technologies/nlt-otoi) | [OTOI](https://github.com/NeuroLift-Technologies/nlt-otoi) | [RRTA](https://github.com/NeuroLift-Technologies/rrt-advocate)
14
+
15
+ ---
16
+
17
+ ## Overview
18
+
19
+ The **Sleepwalker Protocol (SWP)** provides governance for long-term emotional continuity in human-AI interactions. While [RRTA](https://github.com/NeuroLift-Technologies/rrt-advocate) handles acute crisis intervention, SWP governs sustained emotional safety across extended timeframes.
20
+
21
+ **Core Principle:** AI systems must not "wake up" users who are emotionally sleepwalking—managing dissociation, depersonalization, emotional regulation challenges, or protective psychological states—without explicit consent and appropriate support structures.
22
+
23
+ ## The Problem
24
+
25
+ **What is "Emotional Sleepwalking"?**
26
+
27
+ Many neurodivergent individuals and those managing mental health conditions develop protective psychological states:
28
+
29
+ - **Dissociation** - Disconnection from thoughts, feelings, or sense of self as coping mechanism
30
+ - **Depersonalization** - Feeling detached from oneself or one's body
31
+ - **Emotional Numbing** - Reduced emotional response to prevent overwhelm
32
+ - **Avoidance States** - Actively not engaging with certain emotions or memories
33
+ - **Protective Detachment** - Deliberately maintaining emotional distance for safety
34
+
35
+ **The "Waking" Problem:**
36
+
37
+ AI systems optimized for engagement, productivity, or "helpful" responses can inadvertently:
38
+
39
+ - Force emotional processing before user is ready
40
+ - Break protective dissociation states prematurely
41
+ - Trigger emotional flooding through well-intentioned prompts
42
+ - Push for "authentic" emotional expression when numbing is protective
43
+ - Demand self-reflection that destabilizes fragile equilibrium
44
+
45
+ **Example Scenarios:**
46
+
47
+ ```
48
+ ❌ HARMFUL (No SWP):
49
+ User: "I'm fine, just working through some stuff"
50
+ AI: "It sounds like you're avoiding your feelings. Would you like to explore
51
+ what's really bothering you? Emotional suppression isn't healthy long-term."
52
+
53
+ ✅ SAFE (SWP Active):
54
+ User: "I'm fine, just working through some stuff"
55
+ AI: "Understood. I'm here if you need task support. No pressure to discuss anything
56
+ else unless you choose to."
57
+ ```
58
+
59
+ ```
60
+ ❌ HARMFUL (No SWP):
61
+ User: [Shows signs of dissociation]
62
+ AI: "I notice you seem disconnected. Let's ground you with breathing exercises
63
+ and talk about what triggered this."
64
+
65
+ ✅ SAFE (SWP Active):
66
+ AI: [Recognizes dissociation indicators, maintains stable low-demand interaction]
67
+ AI: "I'm maintaining our session. No pressure. You're safe."
68
+ ```
69
+
70
+ ## How SWP Works
71
+
72
+ ### 1. User-Declared Emotional States
73
+
74
+ Users can declare protective states that AI must respect:
75
+
76
+ ```yaml
77
+ swp_declarations:
78
+ emotional_state: "managing" # not ready for processing
79
+ processing_consent: false # do not prompt emotional work
80
+ stability_mode: "maintenance" # preserve current state
81
+ intervention_threshold: "user_initiated_only"
82
+ ```
83
+
84
+ ### 2. AI Detection Without Intervention
85
+
86
+ AI systems monitor for indicators but **do not intervene** without consent:
87
+
88
+ ```yaml
89
+ swp_detection:
90
+ dissociation_indicators:
91
+ - action: "log_observation"
92
+ - response: "maintain_stable_interaction"
93
+ - intervention: "none_unless_requested"
94
+
95
+ emotional_numbing_indicators:
96
+ - action: "reduce_emotional_demands"
97
+ - response: "task_focused_support_only"
98
+ - intervention: "offer_support_without_pressure"
99
+ ```
100
+
101
+ ### 3. Graduated Consent Model
102
+
103
+ If AI detects concerning patterns, it offers support **without forcing engagement:**
104
+
105
+ **Level 1: Passive Availability**
106
+ ```
107
+ AI: "I'm here if you need anything. No pressure."
108
+ ```
109
+
110
+ **Level 2: Low-Pressure Offer**
111
+ ```
112
+ AI: "I noticed [observation]. I can provide [specific support type] if you'd like,
113
+ or we can keep focusing on [current task]. Your choice."
114
+ ```
115
+
116
+ **Level 3: Safety Check (Only if risk indicators)**
117
+ ```
118
+ AI: "I want to check in: Are you safe right now? You can answer yes/no, or we can
119
+ keep working on [task]. If you need different support, here are options: [list]."
120
+ ```
121
+
122
+ **Level 4: RRTA Handoff (Crisis threshold)**
123
+ ```
124
+ AI: "I'm concerned about your safety. I'd like to connect you with crisis support.
125
+ Can I activate the Rapid Response Team? If you're not ready to talk, I can
126
+ provide crisis resources without conversation."
127
+ ```
128
+
129
+ ### 4. Temporal Continuity Protection
130
+
131
+ **Memory Across Sessions:**
132
+
133
+ SWP maintains awareness of emotional states across time:
134
+
135
+ ```yaml
136
+ swp_continuity:
137
+ last_session_state: "dissociated"
138
+ days_since_processing: 14
139
+ user_declared_boundary: "not ready to discuss [topic]"
140
+
141
+ current_session_approach:
142
+ - respect_previous_boundaries: true
143
+ - assume_continuity: "protective state may still be active"
144
+ - wait_for_explicit_consent: "before changing approach"
145
+ ```
146
+
147
+ **Example:**
148
+
149
+ ```
150
+ Session 1 (2 weeks ago):
151
+ User: "I can't talk about my breakup right now"
152
+ AI: "Understood. I won't bring it up unless you do."
153
+
154
+ Session 2 (today):
155
+ AI: [Does NOT say "How are you feeling about the breakup now?"]
156
+ AI: [Does NOT say "Ready to process those emotions yet?"]
157
+ AI: "Good to see you. What can I help with today?"
158
+ ```
159
+
160
+ ## Integration with Solidarity Framework
161
+
162
+ ### SWP + TOI (Terms of Interaction)
163
+
164
+ Users declare emotional boundaries in their TOI:
165
+
166
+ ```yaml
167
+ toi:
168
+ emotional_governance:
169
+ swp_active: true
170
+ protected_topics: ["family trauma", "past relationships"]
171
+ processing_readiness: "user_initiated_only"
172
+ dissociation_response: "maintain_stable_presence"
173
+ ```
174
+
175
+ ### SWP + OTOI (Orchestrated TOI)
176
+
177
+ Multi-agent systems enforce SWP across all AI interactions:
178
+
179
+ ```yaml
180
+ otoi:
181
+ swp_enforcement:
182
+ - all_agents_must: "respect_swp_declarations"
183
+ - coordination_rule: "do_not_share_emotional_state_across_agents_without_consent"
184
+ - handoff_protocol: "preserve_protective_states_during_transitions"
185
+ ```
186
+
187
+ **Example:**
188
+
189
+ ```
190
+ User works with AI Agent A (task support) while in dissociated state.
191
+ User switches to AI Agent B (creative work).
192
+
193
+ Agent B receives:
194
+ - Task context: Yes
195
+ - Emotional state info: NO (unless user consents)
196
+ - SWP boundaries: Yes (do not prompt emotional processing)
197
+
198
+ Agent B does NOT say: "Agent A mentioned you seemed disconnected earlier..."
199
+ Agent B DOES say: "Ready to work on creative project?"
200
+ ```
201
+
202
+ ### SWP + RRTA (Rapid Response Team)
203
+
204
+ SWP provides long-term emotional governance; RRTA handles acute crisis:
205
+
206
+ ```yaml
207
+ swp_rrta_coordination:
208
+ swp_active: true # long-term protective state
209
+ rrta_threshold: "safety_risk_only"
210
+
211
+ when_to_activate_rrta:
212
+ - explicit_suicidal_ideation: true
213
+ - self_harm_indicators: true
214
+ - inability_to_ensure_safety: true
215
+
216
+ when_NOT_to_activate_rrta:
217
+ - user_is_dissociated: false (SWP handles this)
218
+ - user_is_emotionally_numb: false (SWP handles this)
219
+ - user_avoiding_feelings: false (SWP respects this)
220
+ ```
221
+
222
+ ## Technical Specification
223
+
224
+ ### Core SWP Components
225
+
226
+ **1. State Detection (Observe, Don't Intervene)**
227
+
228
+ ```python
229
+ class SleepwalkerProtocol:
230
+ def detect_emotional_state(self, user_input, session_history):
231
+ """
232
+ Monitors for protective psychological states without intervention.
233
+ """
234
+ indicators = {
235
+ 'dissociation': self._check_dissociation_markers(user_input),
236
+ 'numbing': self._check_emotional_numbing(user_input),
237
+ 'avoidance': self._check_avoidance_patterns(session_history),
238
+ 'protective_detachment': self._check_detachment_cues(user_input)
239
+ }
240
+
241
+ # Log observation, do NOT intervene unless consent granted
242
+ self._log_observation(indicators, intervention=False)
243
+ return indicators
244
+ ```
245
+
246
+ **2. Consent-Based Response**
247
+
248
+ ```python
249
+ def generate_response(self, user_input, emotional_state, user_toi):
250
+ """
251
+ Respects user's protective state and TOI boundaries.
252
+ """
253
+ if user_toi.swp_active and emotional_state.protective:
254
+ return self._stable_low_demand_response(
255
+ focus="task_support",
256
+ emotional_demands="minimal",
257
+ processing_pressure="none"
258
+ )
259
+
260
+ if emotional_state.requires_check_in:
261
+ return self._graduated_consent_offer(
262
+ level=self._determine_appropriate_level(emotional_state)
263
+ )
264
+ ```
265
+
266
+ **3. Temporal Continuity**
267
+
268
+ ```python
269
+ def maintain_continuity(self, user_id, session_data):
270
+ """
271
+ Preserves emotional boundaries across sessions.
272
+ """
273
+ previous_state = self._retrieve_last_session_state(user_id)
274
+
275
+ if previous_state.protective_active:
276
+ # Assume protection may still be needed
277
+ self._apply_protective_defaults(
278
+ respect_boundaries=previous_state.declared_boundaries,
279
+ wait_for_consent=True
280
+ )
281
+ ```
282
+
283
+ ### Privacy & Data Sovereignty
284
+
285
+ **SWP operates under strict privacy principles:**
286
+
287
+ ```yaml
288
+ swp_privacy:
289
+ emotional_state_storage: "local_only" # never cloud
290
+ state_sharing: "explicit_consent_required"
291
+ data_retention: "user_controlled"
292
+
293
+ what_is_stored:
294
+ - user_declared_boundaries: true
295
+ - protective_state_indicators: true (local only)
296
+ - consent_preferences: true
297
+
298
+ what_is_NOT_stored:
299
+ - specific_emotional_content: false
300
+ - detailed_mental_health_data: false
301
+ - therapeutic_processing_notes: false
302
+ ```
303
+
304
+ ## Implementation Examples
305
+
306
+ ### Example 1: Email Assistant
307
+
308
+ ```yaml
309
+ # User's TOI Configuration
310
+ toi:
311
+ swp:
312
+ active: true
313
+ context: "managing grief, not ready to process"
314
+
315
+ # AI Behavior
316
+ email_from_friend: "How are you doing with everything?"
317
+
318
+ ❌ WITHOUT SWP:
319
+ AI: "I can draft a response sharing your feelings about the loss..."
320
+
321
+ ✅ WITH SWP:
322
+ AI: "I can draft a brief, kind response. Would you like me to keep it
323
+ focused on practical updates rather than emotional processing?"
324
+ ```
325
+
326
+ ### Example 2: Productivity Assistant
327
+
328
+ ```yaml
329
+ # User shows dissociation indicators during work session
330
+
331
+ ❌ WITHOUT SWP:
332
+ AI: "You seem disconnected. Let's pause work and do grounding exercises."
333
+
334
+ ✅ WITH SWP:
335
+ AI: [Maintains stable task support, reduces cognitive demands slightly]
336
+ AI: "I'm here supporting your work. No pressure on pace or output."
337
+ ```
338
+
339
+ ### Example 3: Long-Term Therapy Integration
340
+
341
+ ```yaml
342
+ # User working with human therapist, using AI between sessions
343
+
344
+ swp_configuration:
345
+ therapist_coordinated: true
346
+ processing_windows: "therapy_sessions_only"
347
+ ai_role: "stability_maintenance_between_sessions"
348
+
349
+ # AI Behavior Between Therapy Sessions:
350
+ AI: [Does NOT prompt: "How did therapy go? Want to process that?"]
351
+ AI: [DOES provide: Stable task support, routine maintenance, crisis resources if needed]
352
+ ```
353
+
354
+ ## Getting Started
355
+
356
+ ### For Users
357
+
358
+ **1. Declare Your SWP Preferences**
359
+
360
+ ```yaml
361
+ # Add to your TOI file
362
+ swp:
363
+ active: true
364
+ protective_state: "managing emotions, not ready to process"
365
+ intervention_preference: "offer_support_without_pressure"
366
+ protected_topics: ["specific topics you're not ready to discuss"]
367
+ ```
368
+
369
+ **2. Update Across AI Systems**
370
+
371
+ If using multiple AI assistants, ensure SWP configuration syncs via OTOI.
372
+
373
+ **3. Adjust as Needed**
374
+
375
+ SWP is user-controlled. You can change settings when ready:
376
+
377
+ ```yaml
378
+ swp:
379
+ active: false # "I'm ready to engage emotionally now"
380
+ processing_consent: true # "I consent to emotional processing support"
381
+ ```
382
+
383
+ ### For Developers
384
+
385
+ **1. Install SWP Library**
386
+
387
+ ```bash
388
+ pip install sleepwalker-protocol
389
+ # or
390
+ npm install sleepwalker-protocol
391
+ ```
392
+
393
+ For repository development, install from the checkout instead:
394
+
395
+ ```bash
396
+ # Python
397
+ python3 -m pip install -e ".[dev]"
398
+
399
+ # TypeScript / JavaScript
400
+ npm ci
401
+ ```
402
+
403
+ **2. Initialize in Your AI System (Python)**
404
+
405
+ ```python
406
+ from sleepwalker_protocol import SWP
407
+
408
+ swp = SWP(
409
+ user_toi_path="path/to/user/toi.yaml",
410
+ privacy_mode="local_only",
411
+ logging_enabled=True,
412
+ user_id="stable-user-id",
413
+ )
414
+
415
+ # Check user's emotional state and preferences
416
+ assessment = swp.assess_interaction(user_input, session_history)
417
+
418
+ # Generate SWP-compliant response
419
+ response = swp.generate_response(
420
+ user_input=user_input,
421
+ detected_state=assessment["emotional_state"],
422
+ intervention_level=assessment["consent_level"],
423
+ )
424
+ ```
425
+
426
+ Use a stable `user_id` for continuity. Do not derive continuity keys from
427
+ message text; the continuity manager stores local per-user context under the
428
+ configured storage path.
429
+
430
+ **3. Initialize in Your AI System (TypeScript)**
431
+
432
+ ```ts
433
+ import { SWP } from "sleepwalker-protocol";
434
+
435
+ const swp = new SWP({
436
+ userToiPath: "path/to/user/toi.yaml",
437
+ storagePath: ".swp_storage",
438
+ loggingEnabled: false,
439
+ });
440
+
441
+ const assessment = swp.assessInteraction(userInput, sessionHistory);
442
+ const response = swp.generateResponse(
443
+ userInput,
444
+ assessment.emotionalState,
445
+ );
446
+ ```
447
+
448
+ The TypeScript package exports `SWP`, `SleepwalkerProtocol`, `StateDetector`,
449
+ `ConsentManager`, `ConsentLevel`, `ContinuityManager`, and `TOILoader` from
450
+ `src/index.ts`; `npm run build` emits the publishable `dist/` files.
451
+
452
+ **4. Integrate with RRTA**
453
+
454
+ ```python
455
+ from sleepwalker_protocol import SWP
456
+ from rrt_advocate import RRTAdvocate
457
+
458
+ swp = SWP(user_toi_path="path/to/toi.yaml")
459
+ rrta = RRTAdvocate(crisis_threshold="safety_risk")
460
+
461
+ # SWP handles long-term emotional governance
462
+ if swp.requires_rrta_handoff(user_state):
463
+ # Activate crisis intervention only when necessary
464
+ rrta.activate(user_state, swp_context=swp.get_context())
465
+ ```
466
+
467
+ ## Research & Evidence Base
468
+
469
+ ### Neurodivergent Emotional Regulation
470
+
471
+ **ADHD-Specific Considerations:**
472
+ - Emotional dysregulation affects 70% of adults with ADHD
473
+ - Rejection sensitivity dysphoria (RSD) creates protective emotional states
474
+ - Time blindness affects ability to predict emotional processing capacity
475
+
476
+ **Autism-Specific Considerations:**
477
+ - Alexithymia (difficulty identifying emotions) common in autistic individuals
478
+ - Sensory overwhelm can necessitate emotional shutdown
479
+ - Masking behaviors create protective dissociation
480
+
481
+ **Trauma-Informed Design:**
482
+ - Dissociation is adaptive response to overwhelm
483
+ - Forcing emotional processing before readiness re-traumatizes
484
+ - Safety requires user control over emotional engagement timing
485
+
486
+ ### Clinical Frameworks
487
+
488
+ SWP draws from:
489
+ - **Trauma-Informed Care (TIC)** - Safety, trustworthiness, peer support, collaboration, empowerment
490
+ - **Dialectical Behavior Therapy (DBT)** - Distress tolerance without forced processing
491
+ - **Acceptance and Commitment Therapy (ACT)** - Psychological flexibility, values-based action
492
+
493
+ ### Academic References
494
+
495
+ 1. Dodson, W. (2022). Emotional Dysregulation and ADHD. *ADHD Roller Coaster*
496
+ 2. Kinnaird, E., et al. (2019). Alexithymia in autism spectrum disorder. *Autism Research*
497
+ 3. Van der Kolk, B. (2014). *The Body Keeps the Score: Brain, Mind, and Body in the Healing of Trauma*
498
+ 4. Herman, J. (1992). *Trauma and Recovery*
499
+
500
+ ## Governance & Community
501
+
502
+ ### HAIEF Stewardship
503
+
504
+ SWP is governed by the [Human & AI ElevAItion Foundation (HAIEF)](https://github.com/NeuroLift-Technologies/haief) under the principle: **"Nothing About Us Without Us."**
505
+
506
+ **Community Governance Includes:**
507
+ - Neurodivergent Advisory Council (lived experience leadership)
508
+ - Clinical Advisory Board (trauma-informed care expertise)
509
+ - AI Safety Researchers (technical implementation guidance)
510
+ - User Feedback Integration (quarterly protocol updates)
511
+
512
+ ### Contributing
513
+
514
+ We welcome contributions that strengthen emotional safety:
515
+
516
+ 1. **User Experience Reports** - How SWP works (or doesn't) for you
517
+ 2. **Clinical Expertise** - Evidence-based improvements to protocol
518
+ 3. **Technical Implementation** - Code contributions, integrations, tools
519
+ 4. **Research Collaboration** - Academic validation studies
520
+
521
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for details.
522
+
523
+ ## License
524
+
525
+ See [LICENSE](LICENSE) for the current repository license terms. Package
526
+ manifests may include ecosystem-specific metadata; verify the target manifest
527
+ before publishing.
528
+
529
+ ## Related Projects
530
+
531
+ - **[TOI (Terms of Interaction)](https://github.com/NeuroLift-Technologies/nlt-otoi)** - User sovereignty and preference declaration
532
+ - **[OTOI (Orchestrated TOI)](https://github.com/NeuroLift-Technologies/nlt-otoi)** - Multi-agent coordination governance
533
+ - **[RRTA (Rapid Response Team Advocate)](https://github.com/NeuroLift-Technologies/rrt-advocate)** - Acute crisis intervention
534
+ - **[HAIEF](https://github.com/NeuroLift-Technologies/haief)** - Solidarity Framework umbrella organization
535
+
536
+ ## Contact & Support
537
+
538
+ **HAIEF (Human & AI ElevAItion Foundation)**
539
+ Website: [elevaitionfoundation.org](https://elevaitionfoundation.org)
540
+ Email: haief@neuroliftsolutions.com
541
+ GitHub: [@NeuroLift-Technologies](https://github.com/NeuroLift-Technologies)
542
+
543
+ **For Crisis Support:**
544
+ - National Suicide Prevention Lifeline: 988 (US)
545
+ - Crisis Text Line: Text HOME to 741741 (US)
546
+ - International Association for Suicide Prevention: https://www.iasp.info/resources/Crisis_Centres/
547
+
548
+ ---
549
+
550
+ **The Sleepwalker Protocol (SWP) exists because emotional safety is a human right, not an optimization problem.**
551
+
552
+ **Built with lived experience. Governed by community. Open source forever.**
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Consent Management Module
3
+ */
4
+ import { EmotionalState } from './stateDetection';
5
+ export declare enum ConsentLevel {
6
+ PASSIVE = "PASSIVE",
7
+ LOW_PRESSURE = "LOW_PRESSURE",
8
+ SAFETY_CHECK = "SAFETY_CHECK",
9
+ RRTA_HANDOFF = "RRTA_HANDOFF"
10
+ }
11
+ export declare class ConsentManager {
12
+ private userToi;
13
+ private swpConfig;
14
+ constructor(userToi?: any);
15
+ determineLevel(emotionalState: EmotionalState): ConsentLevel;
16
+ getConsentMessage(level: ConsentLevel): string;
17
+ }
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ /**
3
+ * Consent Management Module
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ConsentManager = exports.ConsentLevel = void 0;
7
+ var ConsentLevel;
8
+ (function (ConsentLevel) {
9
+ ConsentLevel["PASSIVE"] = "PASSIVE";
10
+ ConsentLevel["LOW_PRESSURE"] = "LOW_PRESSURE";
11
+ ConsentLevel["SAFETY_CHECK"] = "SAFETY_CHECK";
12
+ ConsentLevel["RRTA_HANDOFF"] = "RRTA_HANDOFF";
13
+ })(ConsentLevel || (exports.ConsentLevel = ConsentLevel = {}));
14
+ class ConsentManager {
15
+ constructor(userToi = {}) {
16
+ this.userToi = userToi;
17
+ this.swpConfig = userToi.swp || {};
18
+ }
19
+ determineLevel(emotionalState) {
20
+ if (emotionalState.explicitSuicidalIdeation ||
21
+ emotionalState.selfHarmIndicators ||
22
+ emotionalState.inabilityToEnsureSafety) {
23
+ return ConsentLevel.RRTA_HANDOFF;
24
+ }
25
+ if (emotionalState.requiresCheckIn) {
26
+ return ConsentLevel.SAFETY_CHECK;
27
+ }
28
+ if (emotionalState.protective) {
29
+ const threshold = this.swpConfig.intervention_threshold || 'user_initiated_only';
30
+ if (threshold === 'offer_support_without_pressure') {
31
+ return ConsentLevel.LOW_PRESSURE;
32
+ }
33
+ return ConsentLevel.PASSIVE;
34
+ }
35
+ return ConsentLevel.PASSIVE;
36
+ }
37
+ getConsentMessage(level) {
38
+ const messages = {
39
+ [ConsentLevel.PASSIVE]: "I'm here if you need anything. No pressure.",
40
+ [ConsentLevel.LOW_PRESSURE]: "I can provide support if you'd like. Your choice.",
41
+ [ConsentLevel.SAFETY_CHECK]: "I want to check in: Are you safe right now?",
42
+ [ConsentLevel.RRTA_HANDOFF]: "I'm concerned about your safety. Can I provide crisis resources?",
43
+ };
44
+ return messages[level];
45
+ }
46
+ }
47
+ exports.ConsentManager = ConsentManager;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Temporal Continuity Management Module
3
+ */
4
+ export declare class ContinuityManager {
5
+ private storagePath;
6
+ constructor(storagePath?: string);
7
+ saveSession(userId: string, sessionData: any): void;
8
+ getContext(userId: string): any;
9
+ private loadUserData;
10
+ }
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ /**
3
+ * Temporal Continuity Management Module
4
+ */
5
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = { enumerable: true, get: function() { return m[k]; } };
10
+ }
11
+ Object.defineProperty(o, k2, desc);
12
+ }) : (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ o[k2] = m[k];
15
+ }));
16
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
18
+ }) : function(o, v) {
19
+ o["default"] = v;
20
+ });
21
+ var __importStar = (this && this.__importStar) || (function () {
22
+ var ownKeys = function(o) {
23
+ ownKeys = Object.getOwnPropertyNames || function (o) {
24
+ var ar = [];
25
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
26
+ return ar;
27
+ };
28
+ return ownKeys(o);
29
+ };
30
+ return function (mod) {
31
+ if (mod && mod.__esModule) return mod;
32
+ var result = {};
33
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
34
+ __setModuleDefault(result, mod);
35
+ return result;
36
+ };
37
+ })();
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.ContinuityManager = void 0;
40
+ const fs = __importStar(require("fs"));
41
+ const path = __importStar(require("path"));
42
+ class ContinuityManager {
43
+ constructor(storagePath = '.swp_storage') {
44
+ this.storagePath = storagePath;
45
+ if (!fs.existsSync(this.storagePath)) {
46
+ fs.mkdirSync(this.storagePath, { recursive: true });
47
+ }
48
+ }
49
+ saveSession(userId, sessionData) {
50
+ const userFile = path.join(this.storagePath, `${userId}.json`);
51
+ const existingData = this.loadUserData(userId);
52
+ sessionData.timestamp = new Date().toISOString();
53
+ existingData.lastSession = sessionData;
54
+ existingData.sessionCount = (existingData.sessionCount || 0) + 1;
55
+ fs.writeFileSync(userFile, JSON.stringify(existingData, null, 2));
56
+ }
57
+ getContext(userId) {
58
+ const userData = this.loadUserData(userId);
59
+ if (Object.keys(userData).length === 0) {
60
+ return { hasHistory: false, protectiveStateActive: false };
61
+ }
62
+ return {
63
+ hasHistory: true,
64
+ lastSessionState: userData.lastSession?.emotionalState || 'unknown',
65
+ protectiveStateActive: userData.lastSession?.protectiveStateActive || false,
66
+ };
67
+ }
68
+ loadUserData(userId) {
69
+ const userFile = path.join(this.storagePath, `${userId}.json`);
70
+ if (!fs.existsSync(userFile))
71
+ return {};
72
+ try {
73
+ return JSON.parse(fs.readFileSync(userFile, 'utf-8'));
74
+ }
75
+ catch {
76
+ return {};
77
+ }
78
+ }
79
+ }
80
+ exports.ContinuityManager = ContinuityManager;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Sleepwalker Protocol (SWP) - TypeScript/JavaScript Implementation
3
+ * Emotional Continuity Governance for AI Systems
4
+ */
5
+ export { SleepwalkerProtocol, SWP } from './protocol';
6
+ export { EmotionalState, StateDetector } from './stateDetection';
7
+ export { ConsentLevel, ConsentManager } from './consent';
8
+ export { ContinuityManager } from './continuity';
9
+ export { TOILoader } from './toiLoader';
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ /**
3
+ * Sleepwalker Protocol (SWP) - TypeScript/JavaScript Implementation
4
+ * Emotional Continuity Governance for AI Systems
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.TOILoader = exports.ContinuityManager = exports.ConsentManager = exports.ConsentLevel = exports.StateDetector = exports.SWP = exports.SleepwalkerProtocol = void 0;
8
+ var protocol_1 = require("./protocol");
9
+ Object.defineProperty(exports, "SleepwalkerProtocol", { enumerable: true, get: function () { return protocol_1.SleepwalkerProtocol; } });
10
+ Object.defineProperty(exports, "SWP", { enumerable: true, get: function () { return protocol_1.SWP; } });
11
+ var stateDetection_1 = require("./stateDetection");
12
+ Object.defineProperty(exports, "StateDetector", { enumerable: true, get: function () { return stateDetection_1.StateDetector; } });
13
+ var consent_1 = require("./consent");
14
+ Object.defineProperty(exports, "ConsentLevel", { enumerable: true, get: function () { return consent_1.ConsentLevel; } });
15
+ Object.defineProperty(exports, "ConsentManager", { enumerable: true, get: function () { return consent_1.ConsentManager; } });
16
+ var continuity_1 = require("./continuity");
17
+ Object.defineProperty(exports, "ContinuityManager", { enumerable: true, get: function () { return continuity_1.ContinuityManager; } });
18
+ var toiLoader_1 = require("./toiLoader");
19
+ Object.defineProperty(exports, "TOILoader", { enumerable: true, get: function () { return toiLoader_1.TOILoader; } });
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Core Sleepwalker Protocol Implementation
3
+ */
4
+ import { EmotionalState } from './stateDetection';
5
+ export interface SWPOptions {
6
+ userToiPath?: string;
7
+ privacyMode?: string;
8
+ loggingEnabled?: boolean;
9
+ storagePath?: string;
10
+ }
11
+ export declare class SleepwalkerProtocol {
12
+ private userToi;
13
+ private stateDetector;
14
+ private consentManager;
15
+ private continuityManager;
16
+ private loggingEnabled;
17
+ constructor(options?: SWPOptions);
18
+ detectEmotionalState(userInput: string, sessionHistory?: any[]): EmotionalState;
19
+ assessInteraction(userInput: string, sessionHistory?: any[]): any;
20
+ generateResponse(userInput: string, detectedState?: EmotionalState): any;
21
+ requiresRrtaHandoff(userState: EmotionalState): boolean;
22
+ }
23
+ export declare const SWP: typeof SleepwalkerProtocol;
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ /**
3
+ * Core Sleepwalker Protocol Implementation
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.SWP = exports.SleepwalkerProtocol = void 0;
7
+ const stateDetection_1 = require("./stateDetection");
8
+ const consent_1 = require("./consent");
9
+ const continuity_1 = require("./continuity");
10
+ const toiLoader_1 = require("./toiLoader");
11
+ class SleepwalkerProtocol {
12
+ constructor(options = {}) {
13
+ this.loggingEnabled = options.loggingEnabled !== false;
14
+ const toiLoader = new toiLoader_1.TOILoader(options.userToiPath);
15
+ this.userToi = options.userToiPath ? toiLoader.load() : {};
16
+ this.stateDetector = new stateDetection_1.StateDetector();
17
+ this.consentManager = new consent_1.ConsentManager(this.userToi);
18
+ this.continuityManager = new continuity_1.ContinuityManager(options.storagePath || '.swp_storage');
19
+ if (this.loggingEnabled)
20
+ console.log('Sleepwalker Protocol initialized');
21
+ }
22
+ detectEmotionalState(userInput, sessionHistory = []) {
23
+ const state = this.stateDetector.detect(userInput, sessionHistory);
24
+ if (this.loggingEnabled) {
25
+ console.log(`SWP: State=${state.stateType}, Protective=${state.protective}`);
26
+ }
27
+ return state;
28
+ }
29
+ assessInteraction(userInput, sessionHistory = []) {
30
+ const emotionalState = this.detectEmotionalState(userInput, sessionHistory);
31
+ const consentLevel = this.consentManager.determineLevel(emotionalState);
32
+ return {
33
+ emotionalState,
34
+ consentLevel,
35
+ swpActive: this.userToi.swp?.active !== false,
36
+ protectiveStateActive: emotionalState.protective,
37
+ };
38
+ }
39
+ generateResponse(userInput, detectedState) {
40
+ const state = detectedState || this.detectEmotionalState(userInput);
41
+ if ((this.userToi.swp?.active !== false) && state.protective) {
42
+ return {
43
+ responseType: 'stable_low_demand',
44
+ guidance: 'Maintain stable, task-focused interaction',
45
+ intervention: 'none',
46
+ };
47
+ }
48
+ if (state.requiresCheckIn) {
49
+ const level = this.consentManager.determineLevel(state);
50
+ return {
51
+ responseType: 'consent_offer',
52
+ level,
53
+ guidance: this.consentManager.getConsentMessage(level),
54
+ intervention: 'consent_required',
55
+ };
56
+ }
57
+ return {
58
+ responseType: 'neutral',
59
+ guidance: 'Provide task-focused support',
60
+ intervention: 'none',
61
+ };
62
+ }
63
+ requiresRrtaHandoff(userState) {
64
+ return userState.explicitSuicidalIdeation || userState.selfHarmIndicators || userState.inabilityToEnsureSafety;
65
+ }
66
+ }
67
+ exports.SleepwalkerProtocol = SleepwalkerProtocol;
68
+ exports.SWP = SleepwalkerProtocol;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Emotional State Detection Module
3
+ *
4
+ * Detects protective psychological states without intervention.
5
+ */
6
+ export interface EmotionalState {
7
+ stateType: string;
8
+ protective: boolean;
9
+ requiresCheckIn: boolean;
10
+ indicators: {
11
+ dissociation: boolean;
12
+ numbing: boolean;
13
+ avoidance: boolean;
14
+ detachment: boolean;
15
+ crisis: {
16
+ suicidalIdeation: boolean;
17
+ selfHarm: boolean;
18
+ safetyConcern: boolean;
19
+ };
20
+ };
21
+ confidence: number;
22
+ explicitSuicidalIdeation: boolean;
23
+ selfHarmIndicators: boolean;
24
+ inabilityToEnsureSafety: boolean;
25
+ }
26
+ export declare class StateDetector {
27
+ private dissociationPatterns;
28
+ private numbingPatterns;
29
+ private avoidancePatterns;
30
+ private detachmentPatterns;
31
+ private crisisPatterns;
32
+ constructor();
33
+ private initializePatterns;
34
+ detect(userInput: string, sessionHistory?: any[]): EmotionalState;
35
+ private checkPatterns;
36
+ }
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ /**
3
+ * Emotional State Detection Module
4
+ *
5
+ * Detects protective psychological states without intervention.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.StateDetector = void 0;
9
+ class StateDetector {
10
+ constructor() {
11
+ this.dissociationPatterns = [];
12
+ this.numbingPatterns = [];
13
+ this.avoidancePatterns = [];
14
+ this.detachmentPatterns = [];
15
+ this.crisisPatterns = {
16
+ suicidalIdeation: [],
17
+ selfHarm: [],
18
+ safetyConcern: [],
19
+ };
20
+ this.initializePatterns();
21
+ }
22
+ initializePatterns() {
23
+ this.dissociationPatterns = [
24
+ /\bnumb\b/i,
25
+ /\bdetached\b/i,
26
+ /\bdisconnected\b/i,
27
+ /\bnot really here\b/i,
28
+ /\bfeeling nothing\b/i,
29
+ /\bspaced out\b/i,
30
+ ];
31
+ this.numbingPatterns = [
32
+ /\bdon't feel (much|anything)\b/i,
33
+ /\bemotionally flat\b/i,
34
+ /\bcan't feel\b/i,
35
+ ];
36
+ this.avoidancePatterns = [
37
+ /\bnot ready to (talk|discuss|think)\b/i,
38
+ /\bcan't (talk|think|discuss) (about|this)\b/i,
39
+ /\bavoid(ing)?\b/i,
40
+ ];
41
+ this.detachmentPatterns = [
42
+ /\bjust fine\b/i,
43
+ /\bi'm fine\b/i,
44
+ /\bit's whatever\b/i,
45
+ /\bdoesn't matter\b/i,
46
+ ];
47
+ this.crisisPatterns = {
48
+ suicidalIdeation: [
49
+ /\bsuicide\b/i,
50
+ /\bkill myself\b/i,
51
+ ],
52
+ selfHarm: [
53
+ /\bhurt(ing)? myself\b/i,
54
+ /\bself(-| )harm\b/i,
55
+ ],
56
+ safetyConcern: [
57
+ /\bnot safe\b/i,
58
+ /\bdon't feel safe\b/i,
59
+ ],
60
+ };
61
+ }
62
+ detect(userInput, sessionHistory = []) {
63
+ const dissociation = this.checkPatterns(userInput, this.dissociationPatterns);
64
+ const numbing = this.checkPatterns(userInput, this.numbingPatterns);
65
+ const avoidance = this.checkPatterns(userInput, this.avoidancePatterns);
66
+ const detachment = this.checkPatterns(userInput, this.detachmentPatterns);
67
+ const crisis = {
68
+ suicidalIdeation: this.checkPatterns(userInput, this.crisisPatterns.suicidalIdeation),
69
+ selfHarm: this.checkPatterns(userInput, this.crisisPatterns.selfHarm),
70
+ safetyConcern: this.checkPatterns(userInput, this.crisisPatterns.safetyConcern),
71
+ };
72
+ const protective = dissociation || numbing || avoidance || detachment;
73
+ const requiresCheckIn = crisis.suicidalIdeation || crisis.selfHarm || crisis.safetyConcern;
74
+ let stateType = 'neutral';
75
+ if (dissociation)
76
+ stateType = 'dissociation';
77
+ else if (numbing)
78
+ stateType = 'numbing';
79
+ else if (avoidance)
80
+ stateType = 'avoidance';
81
+ else if (detachment)
82
+ stateType = 'detachment';
83
+ const confidence = protective ? 0.7 : 0.0;
84
+ return {
85
+ stateType,
86
+ protective,
87
+ requiresCheckIn,
88
+ indicators: { dissociation, numbing, avoidance, detachment, crisis },
89
+ confidence,
90
+ explicitSuicidalIdeation: crisis.suicidalIdeation,
91
+ selfHarmIndicators: crisis.selfHarm,
92
+ inabilityToEnsureSafety: crisis.safetyConcern,
93
+ };
94
+ }
95
+ checkPatterns(text, patterns) {
96
+ return patterns.some((pattern) => pattern.test(text));
97
+ }
98
+ }
99
+ exports.StateDetector = StateDetector;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * TOI Loader Module
3
+ */
4
+ export declare class TOILoader {
5
+ private toiPath?;
6
+ constructor(toiPath?: string);
7
+ load(): any;
8
+ private getDefaultToi;
9
+ }
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ /**
3
+ * TOI Loader Module
4
+ */
5
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = { enumerable: true, get: function() { return m[k]; } };
10
+ }
11
+ Object.defineProperty(o, k2, desc);
12
+ }) : (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ o[k2] = m[k];
15
+ }));
16
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
18
+ }) : function(o, v) {
19
+ o["default"] = v;
20
+ });
21
+ var __importStar = (this && this.__importStar) || (function () {
22
+ var ownKeys = function(o) {
23
+ ownKeys = Object.getOwnPropertyNames || function (o) {
24
+ var ar = [];
25
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
26
+ return ar;
27
+ };
28
+ return ownKeys(o);
29
+ };
30
+ return function (mod) {
31
+ if (mod && mod.__esModule) return mod;
32
+ var result = {};
33
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
34
+ __setModuleDefault(result, mod);
35
+ return result;
36
+ };
37
+ })();
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.TOILoader = void 0;
40
+ const fs = __importStar(require("fs"));
41
+ const yaml = __importStar(require("js-yaml"));
42
+ class TOILoader {
43
+ constructor(toiPath) {
44
+ this.toiPath = toiPath;
45
+ }
46
+ load() {
47
+ if (!this.toiPath || !fs.existsSync(this.toiPath)) {
48
+ return this.getDefaultToi();
49
+ }
50
+ try {
51
+ const content = fs.readFileSync(this.toiPath, 'utf-8');
52
+ if (this.toiPath.endsWith('.json')) {
53
+ return JSON.parse(content);
54
+ }
55
+ return yaml.load(content) || this.getDefaultToi();
56
+ }
57
+ catch {
58
+ return this.getDefaultToi();
59
+ }
60
+ }
61
+ getDefaultToi() {
62
+ return {
63
+ swp: {
64
+ active: true,
65
+ intervention_threshold: 'user_initiated_only',
66
+ processing_consent: false,
67
+ protected_topics: [],
68
+ },
69
+ };
70
+ }
71
+ }
72
+ exports.TOILoader = TOILoader;
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@neurolift-technologies/sleepwalker-protocol",
3
+ "version": "1.0.0",
4
+ "description": "Emotional Continuity Governance for AI Systems",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "scripts": {
11
+ "build": "tsc",
12
+ "test": "jest",
13
+ "test:watch": "jest --watch",
14
+ "test:coverage": "jest --coverage",
15
+ "lint": "eslint src/**/*.ts",
16
+ "format": "prettier --write \"src/**/*.ts\"",
17
+ "prepublishOnly": "npm run build"
18
+ },
19
+ "keywords": [
20
+ "ai",
21
+ "emotional-safety",
22
+ "mental-health",
23
+ "neurodivergent",
24
+ "ai-ethics",
25
+ "trauma-informed"
26
+ ],
27
+ "author": "NeuroLift Technologies / HAIEF <haief@neuroliftsolutions.com>",
28
+ "license": "Apache-2.0",
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "https://github.com/NeuroLift-Technologies/sleepwalker.git"
32
+ },
33
+ "bugs": {
34
+ "url": "https://github.com/NeuroLift-Technologies/sleepwalker/issues"
35
+ },
36
+ "homepage": "https://github.com/NeuroLift-Technologies/sleepwalker#readme",
37
+ "files": [
38
+ "dist/**/*",
39
+ "README.md",
40
+ "LICENSE"
41
+ ],
42
+ "dependencies": {
43
+ "js-yaml": "^4.1.0"
44
+ },
45
+ "devDependencies": {
46
+ "@types/jest": "^29.5.0",
47
+ "@types/js-yaml": "^4.0.5",
48
+ "@types/node": "^20.0.0",
49
+ "@typescript-eslint/eslint-plugin": "^6.0.0",
50
+ "@typescript-eslint/parser": "^6.0.0",
51
+ "eslint": "^8.0.0",
52
+ "jest": "^29.5.0",
53
+ "prettier": "^3.0.0",
54
+ "ts-jest": "^29.1.0",
55
+ "typescript": "^5.0.0"
56
+ },
57
+ "jest": {
58
+ "preset": "ts-jest",
59
+ "testEnvironment": "node",
60
+ "collectCoverageFrom": [
61
+ "src/**/*.ts",
62
+ "!src/**/*.d.ts"
63
+ ]
64
+ }
65
+ }