# Phoebe — Systems Deep Dive

> The `libs/phoebe/` area: four Nx libraries implementing the typed,
> standards-grounded core of the **Phoebe** domain — the science and medicine of
> the brain and mind — covering domain primitives, validated psychometric
> instruments, computational-psychiatry models, and measurement-based care.

## What this area is

Phoebe is the Oshun domain for neuroscience and clinical psychology. The
`libs/phoebe/README.md` describes a large planned package map (~30 packages
spanning neural acquisition, signal processing, decoding, neuromodulation,
connectomics, governance, and more), but only **four** of those packages are
actually built and tracked in the repo today: `@phoebe/core`,
`@phoebe/assessment`, `@phoebe/comp-psychiatry`, and `@phoebe/mbc`. Every other
row in that table is marked `planned` and has no source on disk. This page
documents the four that exist; it does not credit the planned-but-absent ones
with capabilities they don't have.

The four real libraries form a small, layered, dependency-honest stack.
`@phoebe/core` sits at the bottom: it owns the shared vocabulary — branded
identifiers, a generic finite-state-machine helper, neural/clinical types, the
RDoC and HiTOP dimensional models, the consent / IRB / preregistration / crisis
lifecycle machines, and a W3C-PROV provenance graph. The other three depend on
`@phoebe/core` (visible in their `import { ... } from '@phoebe/core'`
statements) and build domain logic on top of it: `@phoebe/assessment` implements
the actual scoring algorithms for clinical instruments,
`@phoebe/comp-psychiatry` implements computational models and decision support,
and `@phoebe/mbc` implements measurement-based and collaborative care over
symptom trajectories.

All four are pure-TypeScript ESM libraries with `@nx/js:tsc` builds and
`@nx/vite:test` Vitest suites (each `*.ts` has a sibling `*.spec.ts`). They have
**zero runtime npm dependencies** (`dependencies: {}` in every `package.json`);
the only cross-package coupling is the three leaf libraries importing
`@phoebe/core`. There are no engines, no databases, no network calls — these are
deterministic, well-typed computational libraries.

A consistent design discipline runs through them, matching the domain's "hard
requirements" in the README: **fail loud, never fabricate**. Illegal
state-machine transitions throw (`IllegalTransitionError`) rather than silently
no-op; suicidality signals are never silently dismissed; treatment matching is
gated as clinician-advisory and a literal `autonomousPrescribe()` seam throws;
and research-use-only signals (biotypes, EEG markers, active inference) are
labelled as such with explicit status constants rather than dressed up as
validated clinical tools.

## How it fits the wider system

These libraries are the deterministic, standards-native substrate for the wider
Phoebe domain (architecture under `DOMAINS/phoebe/`, roadmap in
`TODOS/phase-181.md`). Per the README, Phoebe is "a standalone domain that
depends on existing assets via contracts" (Iris BCI device layer, Aphrodite
biosignals, Psyche affective computing, the Phase-178 research substrate, Kalika
research agents) rather than absorbing their code; the four libraries here are
the in-domain core that those integrations would build against.

The internal boundaries are clean and one-directional: `@phoebe/core` is the
shared spine with no Phoebe dependencies, and `assessment`, `comp-psychiatry`,
and `mbc` each consume it without depending on each other. The clearest
load-bearing seam is the **crisis backbone**: `@phoebe/core` defines the
`CRISIS_ESCALATION_MACHINE` and the `CrisisFlag` contract, `@phoebe/assessment`
derives crisis flags from instrument scores and bridges them onto that machine
(`assessment/src/crisis.ts`), and `@phoebe/mbc` surfaces active-crisis cases in
its caseload registry. The `@phoebe/core` dimensional model (RDoC/HiTOP) is the
other shared seam — `comp-psychiatry/src/markers.ts` maps computational
parameters onto it so model fits are transdiagnostic rather than tied to a
single DSM disorder.

**Update — the Phase-181 build-out has since landed.** Beyond the original four
libraries, `libs/phoebe/` now holds ~28 more packages with real source on disk
(the README's once-"planned" rows). They are documented per-entity below; the
same "fail loud, never fabricate" discipline holds — external tools and devices
appear as honest `not_configured` seams rather than mocked successes. New
families:

- **Autonomous discovery loop** — `@phoebe/ai` (closed-loop supervisor + AI-IRB
  gate), `@phoebe/hypothesis`, `@phoebe/design`, `@phoebe/experiment-runtime`,
  and `@phoebe/reproducibility`. The orchestration/scoring is real; the domain
  science and LLM steps arrive through injected handlers.
- **Knowledge & evidence** — `@phoebe/knowledge-graph`, `@phoebe/literature`,
  `@phoebe/evidence-synthesis`, and `@phoebe/datasets`. Real graph/retrieval/
  extraction algorithms; corpus fetching and NWB/DANDI I/O are fail-loud seams.
- **Neural data, signal & modelling** — `@phoebe/signal` and `@phoebe/decoding`
  (real dependency-free DSP and decoders), plus `@phoebe/neural-io`,
  `@phoebe/neuro-analysis`, `@phoebe/analysis`, `@phoebe/simulation`, and
  `@phoebe/brain-models`, which are TypeScript job interfaces over real Python
  backends (LSL/pylsl, SpikeInterface, Brian2, TVB) that fail loud when the
  Python runtime or a device is absent.
- **Neuromodulation (Rust real-time)** — `@phoebe/neuromodulation`, the only
  Rust crate in Phoebe, for the bounded-latency closed-loop stimulation path
  with a hard thermal/charge-density safety governor and append-only audit.
- **Clinical & phenotyping** — `@phoebe/phenotyping`, `@phoebe/therapeutics`,
  and `@phoebe/subjects`. Decision-support and clinician-gated, not autonomous
  diagnosis or treatment; effect sizes are reported with calibrated uncertainty.
- **Governance, safety & regulatory** — `@phoebe/governance`, `@phoebe/safety`,
  and `@phoebe/regulatory`: neurorights/privacy, the crisis + human-in-the-loop
  backbone, and the FDA SaMD lifecycle harness (advisory, not a filing).
- **Platform** — `@phoebe/gateway` (fail-closed capability-token gateway +
  topology) and `@phoebe/integration` (fail-loud cross-domain adapters that
  route to upstream domains rather than re-implementing them).

## Entity reference

### @phoebe/core

The domain spine (`libs/phoebe/core/src`), depending on nothing else in Phoebe.
It barrels eleven modules from `src/index.ts`: `branded.ts` (brand-typed IDs
like `SubjectId`/`StudyId` to prevent ID mix-ups), `state-machine.ts` (a generic
FSM helper whose `applyEvent` throws `IllegalTransitionError` on any undefined
transition — the "fail loud" rule applied to lifecycle state), `neural.ts`
(modality/channel/device descriptors plus an information-throughput-ceiling
model — `throughputCeilingBps`/`assessUseCaseFeasibility` with constants like
`NON_INVASIVE_INFO_CEILING_BPS = 63` — and LSL/XDF + NWB/BIDS references),
`dimensional.ts` (first-class RDoC matrix — six domains, eight units of
analysis, per-domain constructs, `isValidRdocCoordinate` — and the six HiTOP
spectra plus the `p_factor` general factor), `clinical.ts` (assessment
result/band/`CrisisFlag` types and `bandForScore`),
`consent.ts`/`study.ts`/`crisis.ts` (the consent, IRB approval,
preregistration-lock, and crisis-escalation state machines), `entities.ts`
(Subject/Session/Recording/Trial/Claim/Dataset entities), and `provenance.ts` (a
W3C-PROV-aligned `ProvenanceGraph`). All types-and-algorithms, no I/O.

### @phoebe/assessment

Validated psychometric instruments (`libs/phoebe/assessment/src`), depending on
`@phoebe/core`. It implements exact scoring with published cutoffs/bands for
four instruments: PHQ-9 (`phq9.ts` — 9 items 0–3, Kroenke/Spitzer severity
bands, ≥10 major-depression cutoff, and item-9 self-harm → `CrisisFlag`), GAD-7
(`gad7.ts` — 7 items, ≥10 cutoff, explicitly no suicidality item so no crisis
flag), PCL-5 (`pcl5.ts` — 20 items, both the cutoff total (default 33) and the
full DSM-5 four-cluster provisional-PTSD diagnostic algorithm), and the C-SSRS
screener (`cssrs.ts` — ordered 1–5 ideation severity plus behavior → risk
stratification). `crisis.ts` is the bridge: it maps instrument risk onto a legal
event path through `@phoebe/core`'s `CRISIS_ESCALATION_MACHINE`, so a positive
signal hard-routes to the crisis backbone rather than being silently dropped.

### @phoebe/comp-psychiatry

Computational psychiatry (`libs/phoebe/comp-psychiatry/src`), depending on
`@phoebe/core`. It implements real, literature-cited models: `ddm.ts` is the
pure drift-diffusion model with Bogacz et al. (2006) closed-form error-rate and
decision-time expressions (including the A→0 limits); `reinforcement.ts` is
Rescorla-Wagner/Q-learning with reward-sensitivity scaling, softmax action
selection, and model-based/model-free weighting; `active-inference.ts` provides
precision-weighted Gaussian belief updates as an explicitly-flagged _lens_
(`ACTIVE_INFERENCE_STATUS = 'lens_not_validated_mechanism'`). `markers.ts` maps
those computational parameters onto the `@phoebe/core` RDoC/HiTOP model;
`biotypes.ts` encodes the six-circuit depression biotype taxonomy as
research-use only (`BIOTYPE_EVIDENCE_STATUS = 'research_use_only_single_study'`,
no fabricated circuit→drug claims); and `treatment-matching.ts` is
clinician-advisory decision support that ranks options by treatment-resistance
status, refuses to drive treatment off automated suicide-risk prediction (the
`REACH_VET_CAVEAT`), and exposes a hard `autonomousPrescribe()` seam that throws
`AutonomousPrescribingProhibitedError`.

### @phoebe/mbc

Measurement-based and collaborative care (`libs/phoebe/mbc/src`), depending on
`@phoebe/core`. Four modules: `trajectory.ts` (`analyzeTrajectory` reads
**response** = ≥50% reduction from baseline and **remission** = latest score
below an instrument threshold, with ready-made `PHQ9_MBC_CRITERIA` /
`GAD7_MBC_CRITERIA` and a requirement of ≥2 measurements or it throws);
`schedule.ts` (fixed-cadence administration — `nextDueMs` / `isAssessmentDue` /
`daysOverdue`, where a never-administered schedule is due immediately);
`targets.ts` (`evaluateTarget` is treat-to-target logic that classifies a case
as `target_met` / `on_track` / `not_improving` / `worsening` against an
expected-response deadline and decides whether to alert); and `registry.ts`
(`reviewCase` / `flaggedForReview` implement the Collaborative Care / IMPACT
caseload-registry review, surfacing patients needing attention by reason —
`crisis`, `worsening`, `not_improving`, or `assessment_due`). It composes its
own modules and `@phoebe/core`'s `SubjectId`, with no other dependencies.

### @phoebe/ai

Autonomous closed-loop neuroscientist supervisor (`libs/phoebe/ai/src`, depends
on `@phoebe/core`). `supervisor.ts`'s `runClosedLoop` chains hypothesis → design
→ AI-IRB gate → execution → analysis → theory-update through injected handlers;
`ai-irb.ts` is a fail-closed ethics gate (`evaluateProtocol`, `canEnroll`,
`monitorSafety` with automatic stopping rules), `hallucination.ts`'s
`detectFabrication` flags any `AnalysisClaim` whose evidence is not in the
supplied evidence set, and `theory-update.ts` contradiction-checks model updates
into the `ClaimGraph`. The orchestration and verification logic is real; the
domain science itself arrives through injected handlers rather than being
implemented here.

### @phoebe/analysis

Neuro/behavioural statistics and causal inference (`libs/phoebe/analysis/src`,
zero runtime deps). Real implementations: `multiple-comparison.ts`
(`bonferroni`, `benjaminiHochberg`, `benjaminiYekutieli`,
`permutationMaxStatFwe`, `tfce1d`) behind an `enforceCorrection` gate,
`mixed-effects.ts` (`fitRandomIntercept`, `randomEffectsGuidance`), and
`causal.ts`'s DoWhy-style `estimateAndRefute` flow (`pcSkeleton` discovery,
`backdoorEstimate`, `twoStageLeastSquares`, `mediation`, `refuteEstimate`).
`pipelines.ts` orchestrates BIDS-App/MNE containers through a fail-loud
`ContainerRuntime` seam (`runPipeline` returns `not_configured` without a
runtime) rather than shipping the neuroimaging tools inline.

### @phoebe/brain-models

Circuit/region digital twins (`libs/phoebe/brain-models/src`, zero runtime
deps). `runVirtualBrainTwin` shells to a real The-Virtual-Brain backend
(`python/tvb_backend.py`) and always returns per-region ensemble uncertainty
(`regionSd`), returns `out_of_validated_scope` for whole-brain-emulation
requests, and `not_configured` when TVB is absent — never a prediction without
uncertainty bounds. GPU foundation-model training (`trainFoundationModel` for
BrainLM/TopoLoss/MEI) is an honest `not_configured` fail-loud seam, with
`tvbAvailable` probing the backend.

### @phoebe/datasets

FAIR dataset catalog and BIDS/NWB I/O (`libs/phoebe/datasets/src`, zero runtime
deps). `catalog.ts` is a real RO-Crate/schema.org `DATASET_CATALOG` of major
neuro/behavioural datasets (UKB/HCP/ABCD/ENIGMA/OpenNeuro…) with
`Modality`/`AccessTier`, and `bids.ts` implements real structural validation
(`validateBidsDataset`, `validateBidsFilename`, `parseEntities`). `nwb.ts`'s
HDF5 read/write (`readNwb`, `nwbRoundTrip`) and DANDI/IBL streaming
(`streamDandiHeader`) are fail-loud seams — `pynwbAvailable`/`dandiReachable`
probe them and they return `not_configured` when the Python/network dependencies
are absent.

### @phoebe/decoding

Neural decoders and foundation-model plumbing (`libs/phoebe/decoding/src`, zero
runtime deps). Real dependency-free math: a `linalg.ts` core (`cholesky`,
`solve`) plus seeded `prng.ts`, `kalman.ts`'s `KalmanFilterDecoder` with
least-squares fitting, a hot-swappable `runtime.ts` (`DecoderRuntime`,
`ModelRegistry`, linear/RNN/Kalman), `brain-to-text.ts` CTC `beamSearch` +
`NgramLanguageModel` rescoring, cross-subject `adaptation.ts`
(`EuclideanAlignment`, `OnlineRecalibrator`), and a chance-calibrated
`benchmark.ts` (`coBitsPerSpike`, WER/ITR). The foundation-model tokenizers
(`PoyoTokenizer`, `Ndt2Tokenizer`, `LabramTokenizer`, `MindEyeTokenizer`)
compute real tokens, but their training/inference dispatch is a fail-loud
`not_configured` `Outcome` unless a `WeightsBackend` is injected.

### @phoebe/design

Optimal experimental design and adaptive trials (`libs/phoebe/design/src`, zero
runtime deps). Real statistics throughout: Bayesian expected information gain
(`eig.ts`), adaptive-design optimization (`ado.ts`, `adoRun`), group-sequential
`boundaries.ts` (`alphaSpent`, `SpendingFunction`), BOIN dose-finding
(`boinBoundaries`, `boinDecision`), Beta-Binomial machinery (`betaBinomialPmf`,
`betaCdf`, `bayesUpdate`), basket/umbrella `master-protocol.ts`, and SMART
sequencing (`smart.ts`, `DynamicTreatmentRegime`) with Q-learning
(`QLearningResult`) plus an amortized `trainPolicy`. All computational — no
external optimizer or live trial engine.

### @phoebe/evidence-synthesis

Living reviews and GraphRAG (`libs/phoebe/evidence-synthesis/src`, zero runtime
deps). `screening.ts` does active-learning screening with `majorityVote`
adjudication and `extractPico`/`overallRiskOfBias` extraction,
`living-review.ts` runs `detectContradictions` across the claim graph into
versioned `ReviewVersion`s, `graphrag.ts` is hybrid vector+graph retrieval
(`localSearch`, `globalSearch`, `rankByRelevance`, label-propagation
communities), and `kgarevion.ts`'s `verifyTriple`/`verifyAnswer` filter
KG-unsupported or contradicted triples before an answer is returned. The
retrieval and verification algorithms are real; LLM adjudication is an
injected-model seam.

### @phoebe/experiment-runtime

Experiment authoring and closed-loop control
(`libs/phoebe/experiment-runtime/src`, zero runtime deps). `experiment.ts` is a
plugin-based `ExperimentSpec` with a deterministic seeded `sequence` trial
sequencer and `validateExperiment`, `timing.ts` models frame-precise onset
(`estimateTiming`, `checkPrecision`, `MACOS_DISPLAY` compositor delay,
`PrecisionBudget` flagging), and `closed-loop.ts` does brain-state phase-locked
triggering (`estimatePhase`, `shouldTrigger`). The robotic/wet-lab `backends.ts`
(Opentrons/Strateos/patch-clamp/DeepLabCut/SLEAP via
`submitProtocol`/`ExecutionClient`) are fail-loud seams, not live instrument
drivers.

### @phoebe/gateway

API gateway and service topology (`libs/phoebe/gateway/src`, zero runtime deps).
`auth.ts` is fail-closed capability-token authorization (`issueToken`,
`verifyToken`, `authorize`, `ROLE_CAPABILITIES`, `roleHasCapability`),
`topology.ts` is the real-time/batch/knowledge/clinical `PHOEBE_TOPOLOGY`
service map with a Kafka `routeEvent` bus, `validation.ts` wraps injected
Zod-style guards (`validatorFromGuard`, `processRequest`), and `streams.ts` maps
LSL/XDF descriptors onto NWB `ElectricalSeries` and BIDS entities
(`toNwbElectricalSeries`, `toBidsEntities`). It is a typed
topology/authorization model — the actual services and broker are external.

### @phoebe/governance

Neuroethics, neurorights and privacy (`libs/phoebe/governance/src`, depends on
`@phoebe/core`). `neural-data.ts` classifies neural data and gates
consent-scoped export (`NeuralDataClass`, `evaluateExport`) against the
Chile/Colorado/California neurorights laws, `deident.ts` implements HIPAA Safe
Harbor de-identification with a `kAnonymity` expert-determination gate and a
mandatory `defacingGate` for neuroimaging, and `privacy-compute.ts` provides
real differential privacy (`laplaceMechanism`, `gaussianMechanism`,
`PrivacyBudget` composition) plus `fedAvg` federated averaging.
`access-control.ts` runs a dbGaP-style `DAR_MACHINE` with a hash-chained
`verifyAuditChain` audit trail; `smpcGwas` is a fail-loud SMPC/HE seam that
returns `not_configured` rather than computing insecurely.

### @phoebe/hypothesis

KG-grounded hypothesis engine (`libs/phoebe/hypothesis/src`, depends on
`@phoebe/core` and `@phoebe/knowledge-graph`). `generation.ts`'s
`runDiscoveryLoop` orchestrates generate/`debate`/rank/`evolve` over injected
Phase-178/Kalika adapters, `tournament.ts` is real Elo pairwise ranking
(`runTournament`, `updateElo`, `expectedScore`), `novelty.ts` derives
`noveltyScore` from KG distance plus predication absence (`PredicationIndex`),
and `feasibility.ts` computes `feasibilityScore` with explainable multi-hop
evidence paths from the Biolink graph. The scoring and ranking are real;
hypothesis text and critiques come from injected generators/critics.

### @phoebe/integration

Cross-domain hub (`libs/phoebe/integration/src`, zero runtime deps).
`adapter.ts`'s `ContractAdapter` and `registry.ts`'s `IntegrationHub` are the
single entry point for all access to Iris/Aphrodite/Psyche and the
Nous/Kalika/Mnemosyne/Maat/Veritas/Themis substrate (`UPSTREAM_DOMAINS`,
`ADAPTER_MANIFEST`); each `makeAdapter` delegates to an injected
`UpstreamClient` and returns `not_configured` when unwired rather than
fabricating a result. Deliberately thin — Phoebe never re-implements upstream
device/affect code, it routes to it through these fail-loud adapters.

### @phoebe/knowledge-graph

Biolink knowledge graph and ontologies (`libs/phoebe/knowledge-graph/src`, zero
runtime deps). `biolink.ts` is a schema-validated typed graph (`BiolinkGraph`,
`BIOLINK_CATEGORIES`, `PREDICATE_SCHEMAS`, `SchemaViolationError`),
`embeddings.ts` implements real TransE/RotatE with link prediction
(`TransEModel`, `RotatEModel`, `evaluateTailRanking`), `rdoc-ontology.ts` is the
machine-readable RDoC scheme as SKOS/JSON-LD (`RDOC_DOMAINS`, `allConstructs`,
`getConstruct`), and `crosswalk.ts` is an SSSOM crosswalk across
DSM-5-TR/ICD-11/MeSH/SNOMED/Cognitive-Atlas (`SssomMapping`, `allMappings`).
`ingest.ts` normalizes external KG rows (Hetionet/PrimeKG/SPOKE/DRKG/Monarch)
and `ontology-service.ts` is a versioned registry with fail-loud lookups
(`OntologyService`, `ResolveResult`).

### @phoebe/literature

Literature ingestion and claim extraction (`libs/phoebe/literature/src`, zero
runtime deps). `connectors.ts` are fail-loud corpus connectors
(PubMed/OpenAlex/Semantic-Scholar/Europe-PMC/preprints) with real record
normalization (`normalizePubmed`, `normalizeOpenAlex`, and `reconstructAbstract`
for OpenAlex inverted-index abstracts), `extraction.ts` does SciFact-style
SUPPORTS/REFUTES/NOINFO claim-evidence classification (`extractStance`,
`Stance`, `lexicalAlignment`) with a macro-F1 `evaluate` harness, and
`citation.ts` is scite-style smart-citation typing (`typeCitation`,
`CitationType`). The normalization, extraction and evaluation are real; network
fetching is the fail-loud connector seam.

### @phoebe/neural-io

Multimodal acquisition and time-sync (`libs/phoebe/neural-io/src`, zero runtime
deps). `lslSyncTest` runs a real Lab-Streaming-Layer loopback via
`python/lsl_backend.py` (pylsl) and measures cross-stream jitter (`jitterSdUs`,
`subMillisecond` ≤200 µs target), with XDF record/replay backed by
`python/xdf_io.py`; physical device adapters (Neuropixels/ScanImage/Argo) are
fail-loud seams returning `not_configured` until a device is attached. The LSL
sync and XDF I/O run for real when the Python runtime is present — the module
never fabricates a sync result.

### @phoebe/neuro-analysis

Spike sorting and latent-dynamics harness (`libs/phoebe/neuro-analysis/src`,
zero runtime deps). `benchmarkSpikeSorting` orchestrates a real SpikeInterface
pipeline via `python/spike_sort.py` (ground-truth → bandpass + common-reference
→ `detect_peaks` → PCA + KMeans → compare) and, crucially, also scores a
random-label sorter (`randomAccuracy`, `beatsChance`) so the harness proves it
measures sorting accuracy, not data flow. GPU sorters (Kilosort4/MountainSort5)
and deep latent models (LFADS/CEBRA, via
`python/latent_dynamics.py`/`representation.py`) plug in behind the same
interface and fail loud with `not_configured` when the Python/SpikeInterface
runtime is absent.

### @phoebe/neuromodulation

Hard-real-time closed-loop neuromodulation — the one Rust crate in Phoebe
(`libs/phoebe/neuromodulation/src`, crate `phoebe-neuromodulation`, no external
deps), in Rust for the bounded-latency fail-safe path the rest of the platform
is not. `safety.rs` is a thermal/charge-density governor that hard-caps
stimulation regardless of policy (`shannon_charge_density_limit`, `SHANNON_K`,
`charge_density`, `estimate_temperature_rise_c`, `MAX_TEMP_RISE_C` ≤0.5 °C),
`adbs.rs` holds the aDBS `BetaBandPolicy` and RNS `RnsState`
detect-and-stimulate machines, `control_loop.rs`'s `ClosedLoop::step` runs the
decode→stimulate loop with per-iteration deadlines and a
`LoopOutcome::FailSafeStop` watchdog, `sensory.rs` is biomimetic ICMS encoding,
`noninvasive.rs` is tFUS/TI control (`mechanical_index`, `within_mi_ceiling`),
and `ledger.rs` is an append-only hash-chained audit (`append`, `verify`). Every
stimulation path terminates in the governor and is logged; nothing fabricates a
delivered pulse or an unreached safe state.

### @phoebe/phenotyping

Digital phenotyping and JITAI (`libs/phoebe/phenotyping/src`, zero runtime
deps). `jitai.ts` is a Thompson-sampling contextual-bandit intervention engine
(`JitaiPolicy`, `BayesianLinear`) with nightly re-fit, `mrt.ts` estimates
micro-randomized-trial causal-excursion effects via WCLS
(`causalExcursionEffect`, `ExcursionEffect`), `sensing.ts` computes
passive-sensing features (`locationEntropy`, `normalizedLocationEntropy`,
`estimateSleepHours` from inactivity), and `voice.ts` derives acoustic
biomarkers (`acousticBiomarkers`, `semanticCoherence`, `voiceDecisionSupport`).
`assessAnomaly` reports calibrated uncertainty and small effect sizes are not
overstated — this is decision support, not diagnosis.

### @phoebe/regulatory

FDA SaMD lifecycle and validation harness (`libs/phoebe/regulatory/src`, depends
on `@phoebe/core`). `samd.ts` does IMDRF risk categorization and pathway
suggestion (`classifySamd`, `SamdClassification`,
`SAMD_LIFECYCLE`/`advanceLifecycle` total-product-life-cycle machine), `pccp.ts`
models Predetermined Change Control Plans (`Pccp`, `evaluateUpdate`), `bias.ts`
runs race-stratified equity testing (`biasGate`, `fairnessReport`,
`SubgroupMetrics`), `drift.ts` is PSI/KS model-drift detection (`assessDrift`,
`ksStatistic`), and `promotion.ts`'s `evaluatePromotion` is the gate that blocks
an inequitable or drifted model update. `modelcard.ts` emits model cards and
ClinicalTrials.gov/WHO-ICTRP registration records (`generateModelCard`,
`emitTrialRegistration`); the FDA-pathway output is advisory, not a filing.

### @phoebe/reproducibility

Preregistration, multiverse and provenance (`libs/phoebe/reproducibility/src`,
depends on `@phoebe/core`). `preregistration.ts` does machine-readable
auto-preregistration with real a-priori power analysis (`requiredNPerGroup`,
`twoSampleTPower`, `normalCdf`, `normalQuantile`) and a content-hash
`lockPreregistration`, `multiverse.ts` enumerates specification-curve analyses
(`enumerateSpecifications`, `SpecificationCurve`), `prereg-diff.ts`'s
`diffPreregistration` flags undisclosed researcher degrees of freedom
(`Divergence`), `provenance.ts` is a W3C-PROV/RO-Crate `ProvenanceLedger` with
recompute ordering, and `fair-export.ts` scores FAIR compliance and mints DOIs
(`assessFair`, `mintDoi`, `emitBidsDescription`).

### @phoebe/safety

Crisis-safety and compliance backbone (`libs/phoebe/safety/src`, depends on
`@phoebe/core`). `crisis-routing.ts` routes to real crisis resources
(`CRISIS_RESOURCES`, `resourcesForRegion` — 988/Samaritans/findahelpline) and
builds escalation plans (`buildEscalationPlan`), `detection.ts` is deterministic
conversational risk detection (`detectRisk`, `severityFromDetection` — no
randomness), `jurisdiction.ts` is the 2025–26 AI-therapy-law feature gate
(`JURISDICTION_RULES`, `resolveFeature`, `resolveStrictest`), `compliance.ts`
handles age-gating and mandatory AI disclosure (`checkAgeGate`,
`requireAiDisclosure`), and `hitl.ts`'s `evaluateCheckpoint` is the
human-in-the-loop gate every patient-facing autonomous action must pass.
Deterministic and fail-closed by construction.

### @phoebe/signal

Real-time streaming signal processing for neural interfaces
(`libs/phoebe/signal/src`, depends on `@phoebe/core`). Real, dependency-free
DSP/linear algebra: `filters.ts` streaming IIR (`Biquad`, `biquadBandpass`,
`biquadNotch`, `butterworthBandpass`, `StreamingFilter`), `ica.ts` FastICA
artifact separation (`FastIcaResult`, `ComponentClassification`), `csp.ts`
CSP/xDAWN spatial filters (`CspResult`, `XdawnResult`), `riemann.ts`
SPD-covariance Riemannian methods (`averageCovariance`, `MdmClassifier`),
`drift.ts` online change detection (`Cusum`, `PageHinkley`), and `features.ts`
streaming spike/band-power (`bandPower`, `EEG_BANDS`, `StreamingSpikeBinner`).
No external DSP library — the numerics are implemented in-repo.

### @phoebe/simulation

Multi-scale neural simulation (`libs/phoebe/simulation/src`, zero runtime deps).
`runSimulation` is a TypeScript job interface over a real Brian2 spiking backend
(`python/brian2_backend.py`): a LIF `SimJob` goes in and a `SimRaster` (spike
times + firing rates) comes back, or a fail-loud `SimNotConfigured` when the
Python/Brian2 runtime is absent — never a fabricated raster. `scheduler.ts` adds
a resource-aware `JobScheduler` plus a Slurm submission seam (`submitToSlurm`),
and NEST/NEURON/Arbor + SONATA multi-backend runners plug in behind the same
interface (`runSonataTwoBackends`, `runArborTvbCosim`,
`buildBmtkSonataNetwork`).

### @phoebe/subjects

Subject and panel management (`libs/phoebe/subjects/src`, depends on
`@phoebe/core`). `panels.ts` are recruitment-panel connectors with per-panel
quality metadata (`PANEL_REGISTRY`, `connectPanel`), `quality-firewall.ts` is
the two-tier adversarial data-quality firewall (`screenSubmission`,
`llmTextSignatureScore` — naive IMC plus bot/LLM/duplicate detection),
`allocation.ts` is seeded randomization (`simpleRandomization`,
`permutedBlockRandomization`, `stratifiedRandomization`) with a consent-gated
`LongitudinalTracker`, and `eligibility.ts`'s `matchPatientToTrial` is
clinician-reviewed patient↔trial matching (`evaluateCriterion`,
`MatchRecommendation`). Real screening and randomization; the matching is
advisory.

### @phoebe/therapeutics

Therapeutic content and clinician copilot (`libs/phoebe/therapeutics/src`,
depends on `@phoebe/core` and `@phoebe/safety`). `content.ts` is
modality-specific (CBT/DBT/ACT/MI) retrieval-grounded technique lookup
(`retrieveTechniques`, `TECHNIQUE_LIBRARY`, `Modality`), `anti-sycophancy.ts`'s
`guardResponse`/`classifyBelief` challenge rather than confirm delusional or
false beliefs, `session.ts`'s `evaluateTurn` runs per-turn crisis detection plus
jurisdiction/supervision gating through `@phoebe/safety`, and `scribe.ts` is a
clinician-signoff-gated ambient scribe (`generateNote`, `signOff`,
SOAP/GIRP/BIRP/DAP `NoteFormat`). Content is retrieval-grounded and
clinician-gated — it does not autonomously treat.
