feat(skills): add NeuroSkill BCI integration as optional built-in skill

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
This commit is contained in:
teknium1 2026-03-12 21:56:07 -07:00
parent 0219abfeed
commit 8a3e7e15c6
5 changed files with 1417 additions and 0 deletions

View file

@ -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 <N>` 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

View file

@ -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 (δ)** | 14 | Deep sleep (N3), high-amplitude artifacts | Awake, alert |
| **Theta (θ)** | 48 | Drowsiness, REM onset, creative ideation, cognitive load | Alert, focused |
| **Alpha (α)** | 813 | Relaxed wakefulness, "alpha blocking" during effort | Active thinking, anxiety |
| **Beta (β)** | 1330 | Active concentration, problem-solving, alertness | Relaxed, unfocused |
| **Gamma (γ)** | 3050 | 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 (01 Scale)
### Focus
- **Formula**: σ(β / (α + θ)) — beta dominance over slow waves, sigmoid-mapped
- **> 0.70**: Deep concentration, flow state, task absorption
- **0.400.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.400.69**: Mild tension present
- **< 0.30**: Stressed, anxious, sympathetic dominant
### Engagement
- **01 scale**: Active mental investment and motivation
- **> 0.70**: Mentally invested, motivated, active processing
- **0.400.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.400.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.300.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 812 Hz. Higher = faster cognitive processing. Slows with age/fatigue. |
| **SNR** | 10 · log₁₀(P_signal / P_noise) | Signal-to-Noise Ratio. > 10 dB = clean, 310 dB = usable, < 3 dB = unreliable. |
| **Coherence** | Inter-hemispheric coherence (01) | 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.31.8; higher = complex |
| **DFA Exponent** | Long-range correlations. | Healthy: 0.60.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** | 0100 | Lempel-Ziv Complexity proxy (PE + HFD). > 60 = wakefulness. |
| **Wakefulness** | 0100 | Inverse drowsiness composite. |
| **Integration** | 0100 | Cortical integration (Coherence × PAC × Spectral Entropy). |
Status thresholds: ≥ 50 Green, 2550 Yellow, < 25 Red.
---
## Cardiac & Autonomic Metrics (from PPG)
| Metric | Description | Normal / Green Range |
|--------|-------------|---------------------|
| **HR** | Heart rate (bpm) | 5590 (green), 45110 (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) | 0100 composite. > 200 raw = strong stress |
| **SpO₂ Estimate** | Blood oxygen saturation (uncalibrated) | 95100% normal (research only) |
| **Respiratory Rate** | Breaths per minute | 1220 normal |
---
## Motion & Artifact Detection
| Metric | Description |
|--------|-------------|
| **Stillness** | 01 (1 = perfectly still). From IMU accelerometer/gyroscope. |
| **Blink Count** | Eye blinks detected (large spikes in AF7/AF8). Normal: 1520/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** | 01 | ≥ 0.9 = good, ≥ 0.7 = acceptable, < 0.7 = poor |
| **AF7** | 01 | Same thresholds |
| **AF8** | 01 | Same thresholds |
| **TP10** | 01 | 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)**: 1525% of total sleep
- **REM**: 2025%
- **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.500.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/`

View file

@ -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 45 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**: 23 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**: 24 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 48 cycles
**Effect**: Engages parasympathetic nervous system, reduces beta activity
### Extended Exhale (4-7-8)
**Duration**: 35 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 (13 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 13 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**: 510 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 35 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 34 times
**Effect**: Activates left prefrontal cortex, shifts FAA positive
### Loving-Kindness (Metta)
**Duration**: 510 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**: 35 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 35 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 58 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 34 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**: 35 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 23 minutes
**Effect**: Acute arousal response, suppresses drowsiness
### NSDR (Non-Sleep Deep Rest / Yoga Nidra)
**Duration**: 2030 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**: 1020 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 23 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 (6568°F / 1820°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 810 seconds
2. Move upward: calves → thighs → abdomen → hands → arms → shoulders → face
3. Hold each tension 5 seconds, release 810 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 2040%
---
## 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**: 6090 minutes before bed
**Trigger**: Evening, pre-sleep routine
**Instructions**:
1. Hard stop on all screens 6090 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 90120 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 23x
### 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: 35 seconds
- Breath hold: 24 seconds
- Breath exhale: 48 seconds
- Muscle tense: 5 seconds
- Muscle release: 810 seconds
- Body-scan region: 1015 seconds