From 8a3e7e15c6fef3bdc51ec699ed0570b0776bdc91 Mon Sep 17 00:00:00 2001 From: teknium1 Date: Thu, 12 Mar 2026 21:56:07 -0700 Subject: [PATCH] feat(skills): add NeuroSkill BCI integration as optional built-in skill MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Complete rewrite of the neuroskill-bci skill based on actual source material from the NeuroSkill desktop app and NeuroLoop CLI repos. Supersedes PR #708. Key improvements over #708: - All CLI commands verified against actual NeuroSkill/NeuroLoop source - Added --json flag usage throughout (critical for reliable parsing) - Fixed metric formulas: Focus = σ(β/(α+θ)), Relaxation = σ(α/(β+θ)) - Scores are 0-1 scale (not 0-100 as in #708) - Added all 40+ metrics: FAA, TAR, BAR, TBR, APF, SNR, coherence, consciousness (LZC, wakefulness, integration), complexity (PE, HFD, DFA), cardiac (RMSSD, SDNN, pNN50, LF/HF, stress index, SpO2), motion (stillness, blinks, jaw clenches, nods, shakes) - Added all missing CLI subcommands: session, search-labels, interactive, listen, umap, calibrate, timer, notify, raw - Protocols sourced from actual NeuroLoop protocol repertoire (70+) organized by category (attention, stress, emotional, sleep, somatic, digital, dietary, motivation) - Added full WebSocket/HTTP API reference with all endpoints and JSON response formats - Fixed gamma range: 30-50 Hz (not 30-100) - Added signal quality per electrode with thresholds - Added composite state patterns (flow, fatigue, anxiety, creative, etc.) - Added ZUNA embedding documentation - Placed as optional built-in skill (not bundled by default) Files: - optional-skills/health/DESCRIPTION.md (new category) - optional-skills/health/neuroskill-bci/SKILL.md (main skill) - optional-skills/health/neuroskill-bci/references/metrics.md - optional-skills/health/neuroskill-bci/references/protocols.md - optional-skills/health/neuroskill-bci/references/api.md Refs: #694, #708 --- optional-skills/health/DESCRIPTION.md | 1 + .../health/neuroskill-bci/SKILL.md | 458 ++++++++++++++++++ .../health/neuroskill-bci/references/api.md | 286 +++++++++++ .../neuroskill-bci/references/metrics.md | 220 +++++++++ .../neuroskill-bci/references/protocols.md | 452 +++++++++++++++++ 5 files changed, 1417 insertions(+) create mode 100644 optional-skills/health/DESCRIPTION.md create mode 100644 optional-skills/health/neuroskill-bci/SKILL.md create mode 100644 optional-skills/health/neuroskill-bci/references/api.md create mode 100644 optional-skills/health/neuroskill-bci/references/metrics.md create mode 100644 optional-skills/health/neuroskill-bci/references/protocols.md diff --git a/optional-skills/health/DESCRIPTION.md b/optional-skills/health/DESCRIPTION.md new file mode 100644 index 000000000..9bb6a2d9b --- /dev/null +++ b/optional-skills/health/DESCRIPTION.md @@ -0,0 +1 @@ +Health, wellness, and biometric integration skills — BCI wearables, neurofeedback, sleep tracking, and cognitive state monitoring. diff --git a/optional-skills/health/neuroskill-bci/SKILL.md b/optional-skills/health/neuroskill-bci/SKILL.md new file mode 100644 index 000000000..fb5c68698 --- /dev/null +++ b/optional-skills/health/neuroskill-bci/SKILL.md @@ -0,0 +1,458 @@ +--- +name: neuroskill-bci +description: > + Connect to a running NeuroSkill instance and incorporate the user's real-time + cognitive and emotional state (focus, relaxation, mood, cognitive load, drowsiness, + heart rate, HRV, sleep staging, and 40+ derived EXG scores) into responses. + Requires a BCI wearable (Muse 2/S or OpenBCI) and the NeuroSkill desktop app + running locally. +version: 1.0.0 +author: Hermes Agent + Nous Research +license: MIT +metadata: + hermes: + tags: [BCI, neurofeedback, health, focus, EEG, cognitive-state, biometrics, neuroskill] + category: health + related_skills: [] +--- + +# NeuroSkill BCI Integration + +Connect Hermes to a running [NeuroSkill](https://neuroskill.com/) instance to read +real-time brain and body metrics from a BCI wearable. Use this to give +cognitively-aware responses, suggest interventions, and track mental performance +over time. + +> **⚠️ Research Use Only** — NeuroSkill is an open-source research tool. It is +> NOT a medical device and has NOT been cleared by the FDA, CE, or any regulatory +> body. Never use these metrics for clinical diagnosis or treatment. + +See `references/metrics.md` for the full metric reference, `references/protocols.md` +for intervention protocols, and `references/api.md` for the WebSocket/HTTP API. + +--- + +## Prerequisites + +- **Node.js 20+** installed (`node --version`) +- **NeuroSkill desktop app** running with a connected BCI device +- **BCI hardware**: Muse 2, Muse S, or OpenBCI (4-channel EEG + PPG + IMU via BLE) +- `npx neuroskill status` returns data without errors + +### Verify Setup +```bash +node --version # Must be 20+ +npx neuroskill status # Full system snapshot +npx neuroskill status --json # Machine-parseable JSON +``` + +If `npx neuroskill status` returns an error, tell the user: +- Make sure the NeuroSkill desktop app is open +- Ensure the BCI device is powered on and connected via Bluetooth +- Check signal quality — green indicators in NeuroSkill (≥0.7 per electrode) +- If `command not found`, install Node.js 20+ + +--- + +## CLI Reference: `npx neuroskill ` + +All commands support `--json` (raw JSON, pipe-safe) and `--full` (human summary + JSON). + +| Command | Description | +|---------|-------------| +| `status` | Full system snapshot: device, scores, bands, ratios, sleep, history | +| `session [N]` | Single session breakdown with first/second half trends (0=most recent) | +| `sessions` | List all recorded sessions across all days | +| `search` | ANN similarity search for neurally similar historical moments | +| `compare` | A/B session comparison with metric deltas and trend analysis | +| `sleep [N]` | Sleep stage classification (Wake/N1/N2/N3/REM) with analysis | +| `label "text"` | Create a timestamped annotation at the current moment | +| `search-labels "query"` | Semantic vector search over past labels | +| `interactive "query"` | Cross-modal 4-layer graph search (text → EXG → labels) | +| `listen` | Real-time event streaming (default 5s, set `--seconds N`) | +| `umap` | 3D UMAP projection of session embeddings | +| `calibrate` | Open calibration window and start a profile | +| `timer` | Launch focus timer (Pomodoro/Deep Work/Short Focus presets) | +| `notify "title" "body"` | Send an OS notification via the NeuroSkill app | +| `raw '{json}'` | Raw JSON passthrough to the server | + +### Global Flags +| Flag | Description | +|------|-------------| +| `--json` | Raw JSON output (no ANSI, pipe-safe) | +| `--full` | Human summary + colorized JSON | +| `--port ` | Override server port (default: auto-discover, usually 8375) | +| `--ws` | Force WebSocket transport | +| `--http` | Force HTTP transport | +| `--k ` | Nearest neighbors count (search, search-labels) | +| `--seconds ` | Duration for listen (default: 5) | +| `--trends` | Show per-session metric trends (sessions) | +| `--dot` | Graphviz DOT output (interactive) | + +--- + +## 1. Checking Current State + +### Get Live Metrics +```bash +npx neuroskill status --json +``` + +**Always use `--json`** for reliable parsing. The default output is colorized +human-readable text. + +### Key Fields in the Response + +The `scores` object contains all live metrics (0–1 scale unless noted): + +```jsonc +{ + "scores": { + "focus": 0.70, // β / (α + θ) — sustained attention + "relaxation": 0.40, // α / (β + θ) — calm wakefulness + "engagement": 0.60, // active mental investment + "meditation": 0.52, // alpha + stillness + HRV coherence + "mood": 0.55, // composite from FAA, TAR, BAR + "cognitive_load": 0.33, // frontal θ / temporal α · f(FAA, TBR) + "drowsiness": 0.10, // TAR + TBR + falling spectral centroid + "hr": 68.2, // heart rate in bpm (from PPG) + "snr": 14.3, // signal-to-noise ratio in dB + "stillness": 0.88, // 0–1; 1 = perfectly still + "faa": 0.042, // Frontal Alpha Asymmetry (+ = approach) + "tar": 0.56, // Theta/Alpha Ratio + "bar": 0.53, // Beta/Alpha Ratio + "tbr": 1.06, // Theta/Beta Ratio (ADHD proxy) + "apf": 10.1, // Alpha Peak Frequency in Hz + "coherence": 0.614, // inter-hemispheric coherence + "bands": { + "rel_delta": 0.28, "rel_theta": 0.18, + "rel_alpha": 0.32, "rel_beta": 0.17, "rel_gamma": 0.05 + } + } +} +``` + +Also includes: `device` (state, battery, firmware), `signal_quality` (per-electrode 0–1), +`session` (duration, epochs), `embeddings`, `labels`, `sleep` summary, and `history`. + +### Interpreting the Output + +Parse the JSON and translate metrics into natural language. Never report raw +numbers alone — always give them meaning: + +**DO:** +> "Your focus is solid right now at 0.70 — that's flow state territory. Heart +> rate is steady at 68 bpm and your FAA is positive, which suggests good +> approach motivation. Great time to tackle something complex." + +**DON'T:** +> "Focus: 0.70, Relaxation: 0.40, HR: 68" + +Key interpretation thresholds (see `references/metrics.md` for the full guide): +- **Focus > 0.70** → flow state territory, protect it +- **Focus < 0.40** → suggest a break or protocol +- **Drowsiness > 0.60** → fatigue warning, micro-sleep risk +- **Relaxation < 0.30** → stress intervention needed +- **Cognitive Load > 0.70 sustained** → mind dump or break +- **TBR > 1.5** → theta-dominant, reduced executive control +- **FAA < 0** → withdrawal/negative affect — consider FAA rebalancing +- **SNR < 3 dB** → unreliable signal, suggest electrode repositioning + +--- + +## 2. Session Analysis + +### Single Session Breakdown +```bash +npx neuroskill session --json # most recent session +npx neuroskill session 1 --json # previous session +npx neuroskill session 0 --json | jq '{focus: .metrics.focus, trend: .trends.focus}' +``` + +Returns full metrics with **first-half vs second-half trends** (`"up"`, `"down"`, `"flat"`). +Use this to describe how a session evolved: + +> "Your focus started at 0.64 and climbed to 0.76 by the end — a clear upward trend. +> Cognitive load dropped from 0.38 to 0.28, suggesting the task became more automatic +> as you settled in." + +### List All Sessions +```bash +npx neuroskill sessions --json +npx neuroskill sessions --trends # show per-session metric trends +``` + +--- + +## 3. Historical Search + +### Neural Similarity Search +```bash +npx neuroskill search --json # auto: last session, k=5 +npx neuroskill search --k 10 --json # 10 nearest neighbors +npx neuroskill search --start --end --json +``` + +Finds moments in history that are neurally similar using HNSW approximate +nearest-neighbor search over 128-D ZUNA embeddings. Returns distance statistics, +temporal distribution (hour of day), and top matching days. + +Use this when the user asks: +- "When was I last in a state like this?" +- "Find my best focus sessions" +- "When do I usually crash in the afternoon?" + +### Semantic Label Search +```bash +npx neuroskill search-labels "deep focus" --k 10 --json +npx neuroskill search-labels "stress" --json | jq '[.results[].EXG_metrics.tbr]' +``` + +Searches label text using vector embeddings (Xenova/bge-small-en-v1.5). Returns +matching labels with their associated EXG metrics at the time of labeling. + +### Cross-Modal Graph Search +```bash +npx neuroskill interactive "deep focus" --json +npx neuroskill interactive "deep focus" --dot | dot -Tsvg > graph.svg +``` + +4-layer graph: query → text labels → EXG points → nearby labels. Use `--k-text`, +`--k-EXG`, `--reach ` to tune. + +--- + +## 4. Session Comparison +```bash +npx neuroskill compare --json # auto: last 2 sessions +npx neuroskill compare --a-start --a-end --b-start --b-end --json +``` + +Returns metric deltas with absolute change, percentage change, and direction for +~50 metrics. Also includes `insights.improved[]` and `insights.declined[]` arrays, +sleep staging for both sessions, and a UMAP job ID. + +Interpret comparisons with context — mention trends, not just deltas: +> "Yesterday you had two strong focus blocks (10am and 2pm). Today you've had one +> starting around 11am that's still going. Your overall engagement is higher today +> but there have been more stress spikes — your stress index jumped 15% and +> FAA dipped negative more often." + +```bash +# Sort metrics by improvement percentage +npx neuroskill compare --json | jq '.insights.deltas | to_entries | sort_by(.value.pct) | reverse' +``` + +--- + +## 5. Sleep Data +```bash +npx neuroskill sleep --json # last 24 hours +npx neuroskill sleep 0 --json # most recent sleep session +npx neuroskill sleep --start --end --json +``` + +Returns epoch-by-epoch sleep staging (5-second windows) with analysis: +- **Stage codes**: 0=Wake, 1=N1, 2=N2, 3=N3 (deep), 4=REM +- **Analysis**: efficiency_pct, onset_latency_min, rem_latency_min, bout counts +- **Healthy targets**: N3 15–25%, REM 20–25%, efficiency >85%, onset <20 min + +```bash +npx neuroskill sleep --json | jq '.summary | {n3: .n3_epochs, rem: .rem_epochs}' +npx neuroskill sleep --json | jq '.analysis.efficiency_pct' +``` + +Use this when the user mentions sleep, tiredness, or recovery. + +--- + +## 6. Labeling Moments +```bash +npx neuroskill label "breakthrough" +npx neuroskill label "studying algorithms" +npx neuroskill label "post-meditation" +npx neuroskill label --json "focus block start" # returns label_id +``` + +Auto-label moments when: +- User reports a breakthrough or insight +- User starts a new task type (e.g., "switching to code review") +- User completes a significant protocol +- User asks you to mark the current moment +- A notable state transition occurs (entering/leaving flow) + +Labels are stored in a database and indexed for later retrieval via `search-labels` +and `interactive` commands. + +--- + +## 7. Real-Time Streaming +```bash +npx neuroskill listen --seconds 30 --json +npx neuroskill listen --seconds 5 --json | jq '[.[] | select(.event == "scores")]' +``` + +Streams live WebSocket events (EXG, PPG, IMU, scores, labels) for the specified +duration. Requires WebSocket connection (not available with `--http`). + +Use this for continuous monitoring scenarios or to observe metric changes in real-time +during a protocol. + +--- + +## 8. UMAP Visualization +```bash +npx neuroskill umap --json # auto: last 2 sessions +npx neuroskill umap --a-start --a-end --b-start --b-end --json +``` + +GPU-accelerated 3D UMAP projection of ZUNA embeddings. The `separation_score` +indicates how neurally distinct two sessions are: +- **> 1.5** → Sessions are neurally distinct (different brain states) +- **< 0.5** → Similar brain states across both sessions + +--- + +## 9. Proactive State Awareness + +### Session Start Check +At the beginning of a session, optionally run a status check if the user mentions +they're wearing their device or asks about their state: +```bash +npx neuroskill status --json +``` + +Inject a brief state summary: +> "Quick check-in: focus is building at 0.62, relaxation is good at 0.55, and your +> FAA is positive — approach motivation is engaged. Looks like a solid start." + +### When to Proactively Mention State + +Mention cognitive state **only** when: +- User explicitly asks ("How am I doing?", "Check my focus") +- User reports difficulty concentrating, stress, or fatigue +- A critical threshold is crossed (drowsiness > 0.70, focus < 0.30 sustained) +- User is about to do something cognitively demanding and asks for readiness + +**Do NOT** interrupt flow state to report metrics. If focus > 0.75, protect the +session — silence is the correct response. + +--- + +## 10. Suggesting Protocols + +When metrics indicate a need, suggest a protocol from `references/protocols.md`. +Always ask before starting — never interrupt flow state: + +> "Your focus has been declining for the past 15 minutes and TBR is climbing past +> 1.5 — signs of theta dominance and mental fatigue. Want me to walk you through +> a Theta-Beta Neurofeedback Anchor? It's a 90-second exercise that uses rhythmic +> counting and breath to suppress theta and lift beta." + +Key triggers: +- **Focus < 0.40, TBR > 1.5** → Theta-Beta Neurofeedback Anchor or Box Breathing +- **Relaxation < 0.30, stress_index high** → Cardiac Coherence or 4-7-8 Breathing +- **Cognitive Load > 0.70 sustained** → Cognitive Load Offload (mind dump) +- **Drowsiness > 0.60** → Ultradian Reset or Wake Reset +- **FAA < 0 (negative)** → FAA Rebalancing +- **Flow State (focus > 0.75, engagement > 0.70)** → Do NOT interrupt +- **High stillness + headache_index** → Neck Release Sequence +- **Low RMSSD (< 25ms)** → Vagal Toning + +--- + +## 11. Additional Tools + +### Focus Timer +```bash +npx neuroskill timer --json +``` +Launches the Focus Timer window with Pomodoro (25/5), Deep Work (50/10), or +Short Focus (15/5) presets. + +### Calibration +```bash +npx neuroskill calibrate +npx neuroskill calibrate --profile "Eyes Open" +``` +Opens the calibration window. Useful when signal quality is poor or the user +wants to establish a personalized baseline. + +### OS Notifications +```bash +npx neuroskill notify "Break Time" "Your focus has been declining for 20 minutes" +``` + +### Raw JSON Passthrough +```bash +npx neuroskill raw '{"command":"status"}' --json +``` +For any server command not yet mapped to a CLI subcommand. + +--- + +## Error Handling + +| Error | Likely Cause | Fix | +|-------|-------------|-----| +| `npx neuroskill status` hangs | NeuroSkill app not running | Open NeuroSkill desktop app | +| `device.state: "disconnected"` | BCI device not connected | Check Bluetooth, device battery | +| All scores return 0 | Poor electrode contact | Reposition headband, moisten electrodes | +| `signal_quality` values < 0.7 | Loose electrodes | Adjust fit, clean electrode contacts | +| SNR < 3 dB | Noisy signal | Minimize head movement, check environment | +| `command not found: npx` | Node.js not installed | Install Node.js 20+ | + +--- + +## Example Interactions + +**"How am I doing right now?"** +```bash +npx neuroskill status --json +``` +→ Interpret scores naturally, mentioning focus, relaxation, mood, and any notable + ratios (FAA, TBR). Suggest an action only if metrics indicate a need. + +**"I can't concentrate"** +```bash +npx neuroskill status --json +``` +→ Check if metrics confirm it (high theta, low beta, rising TBR, high drowsiness). +→ If confirmed, suggest an appropriate protocol from `references/protocols.md`. +→ If metrics look fine, the issue may be motivational rather than neurological. + +**"Compare my focus today vs yesterday"** +```bash +npx neuroskill compare --json +``` +→ Interpret trends, not just numbers. Mention what improved, what declined, and + possible causes. + +**"When was I last in a flow state?"** +```bash +npx neuroskill search-labels "flow" --json +npx neuroskill search --json +``` +→ Report timestamps, associated metrics, and what the user was doing (from labels). + +**"How did I sleep?"** +```bash +npx neuroskill sleep --json +``` +→ Report sleep architecture (N3%, REM%, efficiency), compare to healthy targets, + and note any issues (high wake epochs, low REM). + +**"Mark this moment — I just had a breakthrough"** +```bash +npx neuroskill label "breakthrough" +``` +→ Confirm label saved. Optionally note the current metrics to remember the state. + +--- + +## References + +- [NeuroSkill Paper — arXiv:2603.03212](https://arxiv.org/abs/2603.03212) (Kosmyna & Hauptmann, MIT Media Lab) +- [NeuroSkill Desktop App](https://github.com/NeuroSkill-com/skill) (GPLv3) +- [NeuroLoop CLI Companion](https://github.com/NeuroSkill-com/neuroloop) (GPLv3) +- [MIT Media Lab Project](https://www.media.mit.edu/projects/neuroskill/overview/) diff --git a/optional-skills/health/neuroskill-bci/references/api.md b/optional-skills/health/neuroskill-bci/references/api.md new file mode 100644 index 000000000..eac3a2500 --- /dev/null +++ b/optional-skills/health/neuroskill-bci/references/api.md @@ -0,0 +1,286 @@ +# NeuroSkill WebSocket & HTTP API Reference + +NeuroSkill runs a local server (default port **8375**) discoverable via mDNS +(`_skill._tcp`). It exposes both WebSocket and HTTP endpoints. + +--- + +## Server Discovery + +```bash +# Auto-discovery (built into the CLI — usually just works) +npx neuroskill status --json + +# Manual port discovery +NEURO_PORT=$(lsof -i -n -P | grep neuroskill | grep LISTEN | awk '{print $9}' | cut -d: -f2 | head -1) +echo "NeuroSkill on port: $NEURO_PORT" +``` + +The CLI auto-discovers the port. Use `--port ` to override. + +--- + +## HTTP REST Endpoints + +### Universal Command Tunnel +```bash +# POST / — accepts any command as JSON +curl -s -X POST http://127.0.0.1:8375/ \ + -H "Content-Type: application/json" \ + -d '{"command":"status"}' +``` + +### Convenience Endpoints +| Method | Endpoint | Description | +|--------|----------|-------------| +| GET | `/v1/status` | System status | +| GET | `/v1/sessions` | List sessions | +| POST | `/v1/label` | Create label | +| POST | `/v1/search` | ANN search | +| POST | `/v1/compare` | A/B comparison | +| POST | `/v1/sleep` | Sleep staging | +| POST | `/v1/notify` | OS notification | +| POST | `/v1/say` | Text-to-speech | +| POST | `/v1/calibrate` | Open calibration | +| POST | `/v1/timer` | Open focus timer | +| GET | `/v1/dnd` | Get DND status | +| POST | `/v1/dnd` | Force DND on/off | +| GET | `/v1/calibrations` | List calibration profiles | +| POST | `/v1/calibrations` | Create profile | +| GET | `/v1/calibrations/{id}` | Get profile | +| PATCH | `/v1/calibrations/{id}` | Update profile | +| DELETE | `/v1/calibrations/{id}` | Delete profile | + +--- + +## WebSocket Events (Broadcast) + +Connect to `ws://127.0.0.1:8375/` to receive real-time events: + +### EXG (Raw EEG Samples) +```json +{"event": "EXG", "electrode": 0, "samples": [12.3, -4.1, ...], "timestamp": 1740412800.512} +``` + +### PPG (Photoplethysmography) +```json +{"event": "PPG", "channel": 0, "samples": [...], "timestamp": 1740412800.512} +``` + +### IMU (Inertial Measurement Unit) +```json +{"event": "IMU", "ax": 0.01, "ay": -0.02, "az": 9.81, "gx": 0.1, "gy": -0.05, "gz": 0.02} +``` + +### Scores (Computed Metrics) +```json +{ + "event": "scores", + "focus": 0.70, "relaxation": 0.40, "engagement": 0.60, + "rel_delta": 0.28, "rel_theta": 0.18, "rel_alpha": 0.32, + "rel_beta": 0.17, "hr": 68.2, "snr": 14.3 +} +``` + +### EXG Bands (Spectral Analysis) +```json +{"event": "EXG-bands", "channels": [...], "faa": 0.12} +``` + +### Labels +```json +{"event": "label", "label_id": 42, "text": "meditation start", "created_at": 1740413100} +``` + +### Device Status +```json +{"event": "muse-status", "state": "connected"} +``` + +--- + +## JSON Response Formats + +### `status` +```jsonc +{ + "command": "status", "ok": true, + "device": { + "state": "connected", // "connected" | "connecting" | "disconnected" + "name": "Muse-A1B2", + "battery": 73, + "firmware": "1.3.4", + "EXG_samples": 195840, + "ppg_samples": 30600, + "imu_samples": 122400 + }, + "session": { + "start_utc": 1740412800, + "duration_secs": 1847, + "n_epochs": 369 + }, + "signal_quality": { + "tp9": 0.95, "af7": 0.88, "af8": 0.91, "tp10": 0.97 + }, + "scores": { + "focus": 0.70, "relaxation": 0.40, "engagement": 0.60, + "meditation": 0.52, "mood": 0.55, "cognitive_load": 0.33, + "drowsiness": 0.10, "hr": 68.2, "snr": 14.3, "stillness": 0.88, + "bands": { "rel_delta": 0.28, "rel_theta": 0.18, "rel_alpha": 0.32, "rel_beta": 0.17, "rel_gamma": 0.05 }, + "faa": 0.042, "tar": 0.56, "bar": 0.53, "tbr": 1.06, + "apf": 10.1, "coherence": 0.614, "mu_suppression": 0.031 + }, + "embeddings": { "today": 342, "total": 14820, "recording_days": 31 }, + "labels": { "total": 58, "recent": [{"id": 42, "text": "meditation start", "created_at": 1740413100}] }, + "sleep": { "total_epochs": 1054, "wake_epochs": 134, "n1_epochs": 89, "n2_epochs": 421, "n3_epochs": 298, "rem_epochs": 112, "epoch_secs": 5 }, + "history": { "total_sessions": 63, "recording_days": 31, "current_streak_days": 7, "total_recording_hours": 94.2, "longest_session_min": 187, "avg_session_min": 89 } +} +``` + +### `sessions` +```jsonc +{ + "command": "sessions", "ok": true, + "sessions": [ + { "day": "20260224", "start_utc": 1740412800, "end_utc": 1740415510, "n_epochs": 541 }, + { "day": "20260223", "start_utc": 1740380100, "end_utc": 1740382665, "n_epochs": 513 } + ] +} +``` + +### `session` (single session breakdown) +```jsonc +{ + "ok": true, + "metrics": { "focus": 0.70, "relaxation": 0.40, "n_epochs": 541 /* ... ~50 metrics */ }, + "first": { "focus": 0.64 /* first-half averages */ }, + "second": { "focus": 0.76 /* second-half averages */ }, + "trends": { "focus": "up", "relaxation": "down" /* "up" | "down" | "flat" */ } +} +``` + +### `compare` (A/B comparison) +```jsonc +{ + "command": "compare", "ok": true, + "insights": { + "deltas": { + "focus": { "a": 0.62, "b": 0.71, "abs": 0.09, "pct": 14.5, "direction": "up" }, + "relaxation": { "a": 0.45, "b": 0.38, "abs": -0.07, "pct": -15.6, "direction": "down" } + }, + "improved": ["focus", "engagement"], + "declined": ["relaxation"] + }, + "sleep_a": { /* sleep summary for session A */ }, + "sleep_b": { /* sleep summary for session B */ }, + "umap": { "job_id": "abc123" } +} +``` + +### `search` (ANN similarity) +```jsonc +{ + "command": "search", "ok": true, + "result": { + "results": [{ + "neighbors": [{ "distance": 0.12, "metadata": {"device": "Muse-A1B2", "date": "20260223"} }] + }], + "analysis": { + "distance_stats": { "mean": 0.15, "min": 0.08, "max": 0.42 }, + "temporal_distribution": { /* hour-of-day distribution */ }, + "top_days": [["20260223", 5], ["20260222", 3]] + } + } +} +``` + +### `sleep` (sleep staging) +```jsonc +{ + "command": "sleep", "ok": true, + "summary": { "total_epochs": 1054, "wake_epochs": 134, "n1_epochs": 89, "n2_epochs": 421, "n3_epochs": 298, "rem_epochs": 112, "epoch_secs": 5 }, + "analysis": { "efficiency_pct": 87.3, "onset_latency_min": 12.5, "rem_latency_min": 65.0, "bouts": { /* wake/n3/rem bout counts and durations */ } }, + "epochs": [{ "utc": 1740380100, "stage": 0, "rel_delta": 0.15, "rel_theta": 0.22, "rel_alpha": 0.38, "rel_beta": 0.20 }] +} +``` + +### `label` +```json +{"command": "label", "ok": true, "label_id": 42} +``` + +### `search-labels` (semantic search) +```jsonc +{ + "command": "search-labels", "ok": true, + "results": [{ + "text": "deep focus block", + "EXG_metrics": { "focus": 0.82, "relaxation": 0.35, "engagement": 0.75, "hr": 65.0, "mood": 0.60 }, + "EXG_start": 1740412800, "EXG_end": 1740412805, + "created_at": 1740412802, + "similarity": 0.92 + }] +} +``` + +### `umap` (3D projection) +```jsonc +{ + "command": "umap", "ok": true, + "result": { + "points": [{ "x": 1.23, "y": -0.45, "z": 2.01, "session": "a", "utc": 1740412800 }], + "analysis": { + "separation_score": 1.84, + "inter_cluster_distance": 2.31, + "intra_spread_a": 0.82, "intra_spread_b": 0.94, + "centroid_a": [1.23, -0.45, 2.01], + "centroid_b": [-0.87, 1.34, -1.22] + } + } +} +``` + +--- + +## Useful `jq` Snippets + +```bash +# Get just focus score +npx neuroskill status --json | jq '.scores.focus' + +# Get all band powers +npx neuroskill status --json | jq '.scores.bands' + +# Check device battery +npx neuroskill status --json | jq '.device.battery' + +# Get signal quality +npx neuroskill status --json | jq '.signal_quality' + +# Find improving metrics after a session +npx neuroskill session 0 --json | jq '[.trends | to_entries[] | select(.value == "up") | .key]' + +# Sort comparison deltas by improvement +npx neuroskill compare --json | jq '.insights.deltas | to_entries | sort_by(.value.pct) | reverse' + +# Get sleep efficiency +npx neuroskill sleep --json | jq '.analysis.efficiency_pct' + +# Find closest neural match +npx neuroskill search --json | jq '[.result.results[].neighbors[]] | sort_by(.distance) | .[0]' + +# Extract TBR from labeled stress moments +npx neuroskill search-labels "stress" --json | jq '[.results[].EXG_metrics.tbr]' + +# Get session timestamps for manual compare +npx neuroskill sessions --json | jq '{start: .sessions[0].start_utc, end: .sessions[0].end_utc}' +``` + +--- + +## Data Storage + +- **Local database**: `~/.skill/YYYYMMDD/` (SQLite + HNSW index) +- **ZUNA embeddings**: 128-D vectors, 5-second epochs +- **Labels**: Stored in SQLite, indexed with bge-small-en-v1.5 embeddings +- **All data is local** — nothing is sent to external servers diff --git a/optional-skills/health/neuroskill-bci/references/metrics.md b/optional-skills/health/neuroskill-bci/references/metrics.md new file mode 100644 index 000000000..8f2e0bbf0 --- /dev/null +++ b/optional-skills/health/neuroskill-bci/references/metrics.md @@ -0,0 +1,220 @@ +# NeuroSkill Metric Definitions & Interpretation Guide + +> **⚠️ Research Use Only:** All metrics are experimental and derived from +> consumer-grade hardware (Muse 2/S). They are not FDA/CE-cleared and must not +> be used for medical diagnosis or treatment. + +--- + +## Hardware & Signal Acquisition + +NeuroSkill is validated for **Muse 2** and **Muse S** headbands (with OpenBCI +support in the desktop app), streaming at **256 Hz** (EEG) and **64 Hz** (PPG). + +### Electrode Positions (International 10-20 System) +| Channel | Electrode | Position | Primary Signals | +|---------|-----------|----------|-----------------| +| CH1 | TP9 | Left Mastoid | Auditory cortex, verbal memory, jaw-clench artifact | +| CH2 | AF7 | Left Prefrontal | Executive function, approach motivation, eye blinks | +| CH3 | AF8 | Right Prefrontal | Emotional regulation, vigilance, eye blinks | +| CH4 | TP10 | Right Mastoid | Prosody, spatial hearing, non-verbal cognition | + +### Preprocessing Pipeline +1. **Filtering**: High-pass (0.5 Hz), Low-pass (50/60 Hz), Notch filter +2. **Spectral Analysis**: Hann-windowed FFT (512-sample window), Welch periodogram +3. **GPU acceleration**: ~125ms latency via `gpu_fft` + +--- + +## EEG Frequency Bands + +Relative power values (sum ≈ 1.0 across all bands): + +| Band | Range (Hz) | High Means | Low Means | +|------|-----------|------------|-----------| +| **Delta (δ)** | 1–4 | Deep sleep (N3), high-amplitude artifacts | Awake, alert | +| **Theta (θ)** | 4–8 | Drowsiness, REM onset, creative ideation, cognitive load | Alert, focused | +| **Alpha (α)** | 8–13 | Relaxed wakefulness, "alpha blocking" during effort | Active thinking, anxiety | +| **Beta (β)** | 13–30 | Active concentration, problem-solving, alertness | Relaxed, unfocused | +| **Gamma (γ)** | 30–50 | Higher-order processing, perceptual binding, memory | Baseline | + +### JSON Field Names +```json +"bands": { + "rel_delta": 0.28, "rel_theta": 0.18, "rel_alpha": 0.32, + "rel_beta": 0.17, "rel_gamma": 0.05 +} +``` + +--- + +## Core Composite Scores (0–1 Scale) + +### Focus +- **Formula**: σ(β / (α + θ)) — beta dominance over slow waves, sigmoid-mapped +- **> 0.70**: Deep concentration, flow state, task absorption +- **0.40–0.69**: Moderate attention, some mind-wandering +- **< 0.40**: Distracted, fatigued, difficulty concentrating + +### Relaxation +- **Formula**: σ(α / (β + θ)) — alpha dominance, sigmoid-mapped +- **> 0.70**: Calm, stress-free, parasympathetic dominant +- **0.40–0.69**: Mild tension present +- **< 0.30**: Stressed, anxious, sympathetic dominant + +### Engagement +- **0–1 scale**: Active mental investment and motivation +- **> 0.70**: Mentally invested, motivated, active processing +- **0.40–0.69**: Passive participation +- **< 0.30**: Bored, disengaged, autopilot mode + +### Meditation +- **Composite**: Combines alpha elevation, physical stillness (IMU), and HRV coherence +- **> 0.70**: Deep meditative state +- **< 0.30**: Active, non-meditative + +### Mood +- **Composite**: Derived from FAA, TAR, and BAR +- **> 0.60**: Positive affect, approach motivation +- **< 0.40**: Low mood, withdrawal tendency + +### Cognitive Load +- **Formula**: (P_θ_frontal / P_α_temporal) · f(FAA, TBR) — working memory usage +- **> 0.70**: Working memory near capacity, complex processing +- **0.40–0.69**: Moderate mental effort +- **< 0.40**: Task is easy or automatic +- **Interpretation**: High load + high focus = productive struggle. High load + low focus = overwhelmed. + +### Drowsiness +- **Composite**: Weighted TAR + TBR + falling Spectral Centroid +- **> 0.60**: Sleep pressure building, micro-sleep risk +- **0.30–0.59**: Mild fatigue +- **< 0.30**: Alert + +--- + +## EEG Ratios & Spectral Indices + +| Metric | Formula | Interpretation | +|--------|---------|----------------| +| **FAA** | ln(P_α_AF8) − ln(P_α_AF7) | Frontal Alpha Asymmetry. Positive = approach/positive affect. Negative = withdrawal/depression. | +| **TAR** | P_θ / P_α | Theta/Alpha Ratio. > 1.5 = drowsiness or mind-wandering. | +| **BAR** | P_β / P_α | Beta/Alpha Ratio. > 1.5 = alert, engaged cognition. Can also indicate anxiety. | +| **TBR** | P_θ / P_β | Theta/Beta Ratio. ADHD biomarker. Healthy ≈ 1.0, elevated > 1.5, clinical > 3.0. | +| **APF** | argmax_f PSD(f) in [7.5, 12.5] Hz | Alpha Peak Frequency. Typical 8–12 Hz. Higher = faster cognitive processing. Slows with age/fatigue. | +| **SNR** | 10 · log₁₀(P_signal / P_noise) | Signal-to-Noise Ratio. > 10 dB = clean, 3–10 dB = usable, < 3 dB = unreliable. | +| **Coherence** | Inter-hemispheric coherence (0–1) | Cortical connectivity between hemispheres. | +| **Mu Suppression** | Motor cortex suppression index | Low values during movement or motor imagery. | + +--- + +## Complexity & Nonlinear Metrics + +| Metric | Description | Healthy Range | +|--------|-------------|---------------| +| **Permutation Entropy (PE)** | Temporal complexity. Near 1 = maximally irregular. | Consciousness marker | +| **Higuchi Fractal Dimension (HFD)** | Waveform self-similarity. | Waking: 1.3–1.8; higher = complex | +| **DFA Exponent** | Long-range correlations. | Healthy: 0.6–0.9 | +| **PSE** | Power Spectral Entropy. Near 1.0 = white noise. | Lower = organized brain state | +| **PAC θ-γ** | Phase-Amplitude Coupling, theta-gamma. | Working memory mechanism | +| **BPS** | Band-Power Slope (1/f spectral exponent). | Steeper = inhibition-dominated | + +--- + +## Consciousness Metrics + +Derived from the nonlinear metrics above: + +| Metric | Scale | Interpretation | +|--------|-------|----------------| +| **LZC** | 0–100 | Lempel-Ziv Complexity proxy (PE + HFD). > 60 = wakefulness. | +| **Wakefulness** | 0–100 | Inverse drowsiness composite. | +| **Integration** | 0–100 | Cortical integration (Coherence × PAC × Spectral Entropy). | + +Status thresholds: ≥ 50 Green, 25–50 Yellow, < 25 Red. + +--- + +## Cardiac & Autonomic Metrics (from PPG) + +| Metric | Description | Normal / Green Range | +|--------|-------------|---------------------| +| **HR** | Heart rate (bpm) | 55–90 (green), 45–110 (yellow), else red | +| **RMSSD** | Primary vagal tone marker (ms) | > 50 ms healthy, < 20 ms stress | +| **SDNN** | HRV time-domain variability (ms) | Higher = better | +| **pNN50** | Parasympathetic indicator (%) | Higher = more parasympathetic activity | +| **LF/HF Ratio** | Sympatho-vagal balance | > 2.0 = stress, < 0.5 = relaxation | +| **Stress Index** | Baevsky SI: AMo / (2 × MxDMn × Mo) | 0–100 composite. > 200 raw = strong stress | +| **SpO₂ Estimate** | Blood oxygen saturation (uncalibrated) | 95–100% normal (research only) | +| **Respiratory Rate** | Breaths per minute | 12–20 normal | + +--- + +## Motion & Artifact Detection + +| Metric | Description | +|--------|-------------| +| **Stillness** | 0–1 (1 = perfectly still). From IMU accelerometer/gyroscope. | +| **Blink Count** | Eye blinks detected (large spikes in AF7/AF8). Normal: 15–20/min. | +| **Jaw Clench Count** | High-frequency EMG bursts (> 30 Hz) at TP9/TP10. | +| **Nod Count** | Head nods detected via IMU. | +| **Shake Count** | Head shakes detected via IMU. | +| **Head Pitch/Roll** | Head orientation from IMU. | + +--- + +## Signal Quality (Per Electrode) + +| Electrode | Range | Interpretation | +|-----------|-------|----------------| +| **TP9** | 0–1 | ≥ 0.9 = good, ≥ 0.7 = acceptable, < 0.7 = poor | +| **AF7** | 0–1 | Same thresholds | +| **AF8** | 0–1 | Same thresholds | +| **TP10** | 0–1 | Same thresholds | + +If any electrode is below 0.7, recommend the user adjust the headband fit or +moisten the electrode contacts. + +--- + +## Sleep Staging + +Based on 5-second epochs using relative band-power ratios and AASM heuristics: + +| Stage | Code | EEG Signature | Function | +|-------|------|---------------|----------| +| Wake | 0 | Alpha-dominant, BAR > 0.8 | Conscious awareness | +| N1 | 1 | Alpha → Theta transition | Light sleep onset | +| N2 | 2 | Sleep spindles, K-complexes | Memory consolidation | +| N3 (Deep) | 3 | Delta > 20% of epoch, DTR > 2 | Deep restorative sleep | +| REM | 4 | Active EEG, high Theta, low Delta | Emotional processing, dreaming | + +### Healthy Adult Targets (~8h Sleep) +- **N3 (Deep)**: 15–25% of total sleep +- **REM**: 20–25% +- **Sleep Efficiency**: > 85% +- **Sleep Onset Latency**: < 20 min + +--- + +## Composite State Patterns + +| Pattern | Key Metrics | Interpretation | +|---------|-------------|----------------| +| **Flow State** | Focus > 0.75, Engagement > 0.70, Cognitive Load 0.50–0.70, HR steady | Optimal performance zone — protect it | +| **Mental Fatigue** | Focus < 0.40, Drowsiness > 0.60, TBR > 1.5, Theta elevated | Rest or break needed | +| **Anxiety** | Relaxation < 0.30, HR elevated, high Beta, high BAR, stress_index high | Calming intervention helpful | +| **Peak Alert** | Focus > 0.80, Engagement > 0.70, Drowsiness < 0.20 | Best time for hard tasks | +| **Recovery** | Relaxation > 0.70, HRV (RMSSD) rising, Alpha dominant | Integration, light tasks only | +| **Creative Mode** | High Theta, high Alpha, low Beta, moderate focus | Ideation — don't force structure | +| **Withdrawal** | FAA < 0, low Mood, low Engagement | Approach motivation needed | + +--- + +## ZUNA Embeddings + +NeuroSkill uses the **ZUNA Neural Encoder** to convert 5-second EEG epochs into +**128-dimensional vectors** stored in an HNSW index: +- **Search**: Sub-millisecond approximate nearest-neighbor queries +- **UMAP**: GPU-accelerated 3D projection for visual comparison +- **Storage**: Local SQLite + HNSW index in `~/.skill/YYYYMMDD/` diff --git a/optional-skills/health/neuroskill-bci/references/protocols.md b/optional-skills/health/neuroskill-bci/references/protocols.md new file mode 100644 index 000000000..76fd89875 --- /dev/null +++ b/optional-skills/health/neuroskill-bci/references/protocols.md @@ -0,0 +1,452 @@ +# NeuroSkill Guided Protocols + +Over 70 mind-body practices triggered by specific biometric (EXG) signals. These +are sourced from NeuroLoop's protocol repertoire and are designed to be suggested +when the system detects specific cognitive or physiological states. + +> **⚠️ Contraindication**: Wim Hof and hyperventilation-style breathwork are +> unsuitable for epilepsy_risk > 30, known cardiac conditions, or pregnancy. + +--- + +## When to Suggest Protocols + +**Always ask before starting.** Match ONE protocol to the single most salient +metric signal. Explain the metric connection to the user. + +| User State | Recommended Protocol | +|------------|---------------------| +| Focus < 0.40, TBR > 1.5 | Theta-Beta Neurofeedback Anchor or Box Breathing | +| Low engagement, session start | WOOP or Pre-Task Priming | +| Relaxation < 0.30, stress_index high | Cardiac Coherence or 4-7-8 Breathing | +| Cognitive Load > 0.70 sustained | Cognitive Load Offload (Mind Dump) | +| Engagement < 0.30 for > 20 min | Novel Stimulation Burst or Environment Change | +| Flow State (focus > 0.75, engagement > 0.70) | **Do NOT interrupt — protect the session** | +| Drowsiness > 0.60, post-lunch | Ultradian Reset or Power Nap | +| FAA < 0, depression_index elevated | FAA Rebalancing | +| Low RMSSD (< 25ms) | Vagal Toning | +| High stillness + headache signals | Neck Release Sequence | +| Pre-sleep, HRV low | Sleep Wind-Down | +| Post-social-media, low mood | Envy & Comparison Alchemy | + +--- + +## Attention & Focus Protocols + +### Theta-Beta Neurofeedback Anchor +**Duration**: ~90 seconds +**Trigger**: High TBR (> 1.5) and low focus +**Instructions**: +1. Close your eyes +2. Breathe slowly — 4s inhale, 6s exhale +3. Count rhythmically from 1 to 10, matching your breath +4. Focus on the counting — if you lose count, restart from 1 +5. Open your eyes after 4–5 full cycles +**Effect**: Suppresses theta dominance and lifts beta activity + +### Focus Reset +**Duration**: 90 seconds +**Trigger**: Scattered engagement, difficulty settling into task +**Instructions**: +1. Close your eyes completely +2. Take 5 slow, deep breaths +3. Mentally state your intention for the next work block +4. Open your eyes and begin immediately +**Effect**: Resets attentional baseline + +### Working Memory Primer +**Duration**: 3 minutes +**Trigger**: Low PAC θ-γ (theta-gamma coupling), low sample entropy +**Instructions**: +1. Breathe at theta pace: 4s inhale, 6s exhale, 2s hold +2. While breathing, do a verbal 3-back task: listen to or read a sequence + of numbers, say which number appeared 3 positions back +3. Continue for 3 minutes +**Effect**: Lifts theta-gamma coupling and working memory engagement + +### Creativity Unlock +**Duration**: 5 minutes +**Trigger**: High beta, low rel_alpha — system is too analytically locked +**Instructions**: +1. Stop all structured work +2. Let your mind wander without a goal +3. Doodle, look out the window, or listen to ambient sound +4. Don't force any outcome — just observe what arises +5. After 5 minutes, jot down any ideas that surfaced +**Effect**: Promotes alpha and theta activity for creative ideation + +### Dual-N-Back Warm-Up +**Duration**: 3 minutes +**Trigger**: Low PAC θ-γ, low sample entropy +**Instructions**: +1. Read or listen to a sequence of spoken numbers +2. Track which number appeared 2 positions back (2-back) +3. If comfortable, increase to 3-back +**Effect**: Activates prefrontal cortex, lifts executive function + +### Novel Stimulation Burst +**Duration**: 2–3 minutes +**Trigger**: Low APF (< 9 Hz), dementia_index > 30 +**Instructions**: +1. Pick up an unusual object nearby and describe it in detail +2. Name 5 things you can see, 4 you can touch, 3 you can hear +3. Try a quick riddle or lateral thinking puzzle +**Effect**: Counters cortical slowing, raises alpha peak frequency + +--- + +## Autonomic & Stress Regulation Protocols + +### Box Breathing (4-4-4-4) +**Duration**: 2–4 minutes +**Trigger**: High BAR, high anxiety_index, acute stress +**Instructions**: +1. Inhale for 4 counts +2. Hold for 4 counts +3. Exhale for 4 counts +4. Hold for 4 counts +5. Repeat 4–8 cycles +**Effect**: Engages parasympathetic nervous system, reduces beta activity + +### Extended Exhale (4-7-8) +**Duration**: 3–5 minutes +**Trigger**: Acute stress spikes, racing thoughts, high sympathetic activation +**Instructions**: +1. Exhale completely through mouth +2. Inhale through nose for 4 counts +3. Hold for 7 counts +4. Exhale through mouth for 8 counts +5. Repeat 4 cycles +**Effect**: Fastest parasympathetic trigger for acute stress + +### Cardiac Coherence +**Duration**: 5 minutes +**Trigger**: Low RMSSD (< 30 ms), high stress_index +**Instructions**: +1. Breathe evenly: 5-second inhale, 5-second exhale +2. Focus on the area around your heart +3. Recall a positive memory or feeling of appreciation +4. Maintain for 5 minutes +**Effect**: Maximizes HRV, creates coherent heart rhythm pattern + +### Physiological Sigh +**Duration**: 30 seconds (1–3 cycles) +**Trigger**: Rapid overwhelm, acute panic +**Instructions**: +1. Take a quick double inhale through the nose (sniff-sniff) +2. Follow with a long, slow exhale through the mouth +3. Repeat 1–3 times +**Effect**: Rapid parasympathetic activation, immediate calming + +### Alpha Induction (Open Focus) +**Duration**: 5 minutes +**Trigger**: High beta, low relaxation — cannot relax +**Instructions**: +1. Soften your gaze — don't focus on any single object +2. Notice the space between and around objects +3. Expand your awareness to peripheral vision +4. Maintain this "open focus" for 5 minutes +**Effect**: Promotes alpha wave production, reduces beta dominance + +### Open Monitoring +**Duration**: 5–10 minutes +**Trigger**: Low LZC (< 40 on 0-100 scale) — neural complexity too low +**Instructions**: +1. Sit comfortably with eyes closed or softly focused +2. Don't direct attention to anything specific +3. Simply notice whatever arises — thoughts, sounds, sensations +4. Let each observation pass without engagement +**Effect**: Raises neural complexity and consciousness metrics + +### Vagal Toning +**Duration**: 3 minutes +**Trigger**: Low RMSSD (< 25 ms) — weak vagal tone +**Instructions**: +1. Hum a long, steady note on each exhale for 30 seconds +2. Alternatively: gargle cold water for 30 seconds +3. Repeat 3–5 times +**Effect**: Directly stimulates the vagus nerve, increases parasympathetic tone + +--- + +## Emotional Regulation Protocols + +### FAA Rebalancing +**Duration**: 5 minutes +**Trigger**: Negative FAA (right-hemisphere dominant), high depression_index +**Instructions**: +1. Think of something you're genuinely looking forward to (approach motivation) +2. Visualize yourself successfully completing a meaningful goal +3. Squeeze your left hand into a fist for 10 seconds, release +4. Repeat the visualization + left-hand squeeze 3–4 times +**Effect**: Activates left prefrontal cortex, shifts FAA positive + +### Loving-Kindness (Metta) +**Duration**: 5–10 minutes +**Trigger**: Loneliness signals, shame, low mood +**Instructions**: +1. Close your eyes and think of someone you care about +2. Silently repeat: "May you be happy. May you be healthy. May you be safe." +3. Extend the same wishes to yourself +4. Extend to a neutral person, then gradually to someone difficult +**Effect**: Reduces withdrawal motivation, increases positive affect + +### Emotional Discharge +**Duration**: 2 minutes +**Trigger**: High bipolar_index or extreme FAA swings +**Instructions**: +1. Take 30 seconds of vigorous, fast breathing (safely) +2. Stop and take 3 slow, deep breaths +3. Do a 60-second body scan — notice where tension is held +4. Shake out your hands and arms for 15 seconds +**Effect**: Releases trapped sympathetic energy, recalibrates + +### Havening Touch +**Duration**: 3–5 minutes +**Trigger**: Acute distress, trauma activation, overwhelming anxiety +**Instructions**: +1. Gently stroke your arms from shoulder to elbow, palms down +2. Rub your palms together slowly +3. Gently touch your forehead, temples +4. Continue for 3–5 minutes while breathing slowly +**Effect**: Disrupts amygdala-cortex encoding loop, reduces distress + +### Anxiety Surfing +**Duration**: ~8 minutes +**Trigger**: Rising anxiety without clear cause +**Instructions**: +1. Notice where anxiety lives in your body — chest? stomach? throat? +2. Describe the sensation without judging it (tight? hot? buzzing?) +3. Breathe into that area for 3 breaths +4. Notice: is it getting bigger, smaller, or changing shape? +5. Continue observing for 5–8 minutes — anxiety typically peaks then subsides + +### Anger: Palm-Press Discharge +**Duration**: 2 minutes +**Trigger**: Anger signals, high BAR + elevated HR +**Instructions**: +1. Press your palms together firmly for 10 seconds +2. Release and take 3 extended exhales (4s in, 8s out) +3. Repeat 3–4 times + +### Envy & Comparison Alchemy +**Duration**: 3 minutes +**Trigger**: Post-social-media, envy signals +**Instructions**: +1. Name the envy: "I feel envious of ___" +2. Ask: "What does this envy tell me I actually want?" +3. Convert: "My next step toward that is ___" +**Effect**: Converts envy into a desire-signal that identifies personal values + +### Awe Induction +**Duration**: 3–5 minutes +**Trigger**: Existential flatness, low engagement, loss of meaning +**Instructions**: +1. Imagine standing at the edge of the Grand Canyon, or beneath a starry sky +2. Let yourself feel the scale — you are small, and that's beautiful +3. Recall a moment of genuine wonder from your past +4. Notice what changes in your body +**Effect**: Counters hedonic adaptation, restores sense of meaning + +--- + +## Sleep & Recovery Protocols + +### Ultradian Reset +**Duration**: 20 minutes +**Trigger**: End of a 90-minute focus block, drowsiness rising +**Instructions**: +1. Set a timer for 20 minutes +2. No agenda — just rest (don't force sleep) +3. Dim lights if possible, close eyes +4. Let mind wander without structure +**Effect**: Aligns with 90-minute ultradian rhythm, restores cognitive resources + +### Wake Reset +**Duration**: 5 minutes +**Trigger**: narcolepsy_index > 40, severe drowsiness +**Instructions**: +1. Splash cold water on your face and wrists +2. Do 20 seconds of Kapalabhati breath (sharp nasal exhales) +3. Expose yourself to bright light for 2–3 minutes +**Effect**: Acute arousal response, suppresses drowsiness + +### NSDR (Non-Sleep Deep Rest / Yoga Nidra) +**Duration**: 20–30 minutes +**Trigger**: Accumulated fatigue, need deep recovery without sleeping +**Instructions**: +1. Lie on your back, palms up +2. Close your eyes and do a slow body scan from toes to crown +3. At each body part, notice sensation without changing anything +4. If you fall asleep, that's fine — set an alarm +**Effect**: Restores dopamine and cognitive resources without sleep inertia + +### Power Nap +**Duration**: 10–20 minutes (set alarm!) +**Trigger**: Drowsiness > 0.70, post-lunch slump, Theta dominant +**Instructions**: +1. Set alarm for 20 minutes maximum (avoids N3 sleep inertia) +2. Lie down or recline +3. Even if you don't fully sleep, rest with eyes closed +4. On waking: 30 seconds of stretching before resuming work +**Effect**: Restores focus and alertness for 2–3 hours + +### Sleep Wind-Down +**Duration**: 60 minutes before bed +**Trigger**: Evening session, rising drowsiness, pre-sleep +**Instructions**: +1. Dim all screens to night mode +2. Stop new learning or complex tasks +3. Do a mind dump of tomorrow's tasks +4. 10 minutes of progressive relaxation or 4-7-8 breathing +5. Keep room cool (65–68°F / 18–20°C) + +--- + +## Somatic & Physical Protocols + +### Progressive Muscle Relaxation (PMR) +**Duration**: 10 minutes +**Trigger**: Relaxation < 0.25, HRV declining over session +**Instructions**: +1. Start with feet — tense for 5 seconds, release for 8–10 seconds +2. Move upward: calves → thighs → abdomen → hands → arms → shoulders → face +3. Hold each tension 5 seconds, release 8–10 seconds +4. End with 3 deep breaths + +### Grounding (5-4-3-2-1) +**Duration**: 3 minutes +**Trigger**: Panic, dissociation, acute anxiety spike +**Instructions**: +1. Name 5 things you can see +2. Name 4 things you can touch +3. Name 3 things you can hear +4. Name 2 things you can smell +5. Name 1 thing you can taste + +### 20-20-20 Vision Reset +**Duration**: 20 seconds +**Trigger**: Extended screen time, eye strain +**Instructions**: +1. Every 20 minutes of screen time +2. Look at something 20 feet away +3. For 20 seconds + +### Neck Release Sequence +**Duration**: 3 minutes +**Trigger**: High stillness (> 0.85) + headache_index elevated +**Instructions**: +1. Ear-to-shoulder tilt — hold 15 seconds each side +2. Chin tucks — 10 reps (pull chin straight back) +3. Gentle neck circles — 5 each direction +4. Shoulder shrugs — 10 reps (squeeze up, release) + +### Motor Cortex Activation +**Duration**: 2 minutes +**Trigger**: Very high stillness, prolonged static sitting +**Instructions**: +1. Cross-body movements: touch right hand to left knee, alternate 10 times +2. Shake out hands and feet for 15 seconds +3. Roll ankles and wrists 5 times each direction +**Effect**: Resets proprioception, activates motor cortex + +### Cognitive Load Offload (Mind Dump) +**Duration**: 5 minutes +**Trigger**: Cognitive load > 0.70 sustained, racing thoughts, high beta +**Instructions**: +1. Open a blank document or grab paper +2. Write everything on your mind without filtering or organizing +3. Brain-dump worries, tasks, ideas — anything occupying working memory +4. Close the document (review later if needed) +**Effect**: Externalizing working memory can reduce cognitive load by 20–40% + +--- + +## Digital & Lifestyle Protocols + +### Craving Surf +**Duration**: 90 seconds +**Trigger**: Phone addiction signals, urge to check social media +**Instructions**: +1. Notice the urge to check your phone +2. Don't act on it — just observe for 90 seconds +3. Notice: does the urge peak and then fade? +4. Resume what you were doing +**Effect**: Breaks automatic dopamine-seeking loop + +### Dopamine Palette Reset +**Duration**: Ongoing +**Trigger**: Flatness from short-form content spikes +**Instructions**: +1. Identify activities that provide sustained reward (reading, cooking, walking) +2. Replace 15 minutes of scrolling with one sustained-reward activity +3. Track mood before/after for 3 days + +### Digital Sunset +**Duration**: 60–90 minutes before bed +**Trigger**: Evening, pre-sleep routine +**Instructions**: +1. Hard stop on all screens 60–90 minutes before bed +2. Switch to non-screen activities: reading, conversation, stretching +3. If screens are necessary, use night mode at minimum brightness + +--- + +## Dietary Protocols + +### Caffeine Timing +**Trigger**: Morning routine, anxiety_index +**Guidelines**: +- Consume caffeine 90–120 minutes after waking (cortisol has already peaked) +- None after 2 PM (half-life ~6 hours) +- If anxiety_index > 50, stack with L-theanine (200mg) to smooth the curve + +### Post-Meal Energy Crash +**Trigger**: Post-lunch drowsiness spike +**Instructions**: +1. 5-minute brisk walk immediately after eating +2. 10 minutes of sunlight exposure +**Effect**: Counters post-prandial drowsiness + +--- + +## Motivation & Planning Protocols + +### WOOP (Wish, Outcome, Obstacle, Plan) +**Duration**: 5 minutes +**Trigger**: Low engagement before a task +**Instructions**: +1. **Wish**: What do you want to accomplish in this session? +2. **Outcome**: What's the best possible result? Visualize it. +3. **Obstacle**: What internal obstacle might get in the way? +4. **Plan**: "If [obstacle], then I will [action]." +**Effect**: Mental contrasting improves follow-through by 2–3x + +### Pre-Task Priming +**Duration**: 3 minutes +**Trigger**: Low engagement at session start, drowsiness < 0.50 +**Instructions**: +1. Set a clear intention for the next work block +2. Write down the single most important task +3. Do 10 jumping jacks or 20 deep breaths +4. Start with the easiest sub-task to build momentum + +--- + +## Protocol Execution Guidelines + +When guiding the user through a protocol: +1. **Match one protocol** to the single most salient metric signal +2. **Explain the metric connection** — why this protocol for this state +3. **Ask permission** — never start without the user's consent +4. **Announce each step** clearly with timing +5. **Check in after** — run `npx neuroskill status --json` to see if metrics improved +6. **Label the moment** — `npx neuroskill label "post-protocol: [name]"` for tracking + +### Timing Guidelines for Step-by-Step Guidance +- Breath inhale: 3–5 seconds +- Breath hold: 2–4 seconds +- Breath exhale: 4–8 seconds +- Muscle tense: 5 seconds +- Muscle release: 8–10 seconds +- Body-scan region: 10–15 seconds