In Silico · system structure
CDSS Design for Early Detection of Mental Health Crises
Four decision-support designs for crisis prevention: early detection, rule-bound safety planning, on-device isolation detection and immediate handoff to a counsellor.
This is a research record, not a help service. If you are in Korea and need to talk to someone now, the suicide prevention counselling line 109 can be reached by phone. Elsewhere, contact your local emergency number.
What this work is
Design specifications and a reference implementation for four decision-support units around mental-health crises: early detection from coded records, a template-constrained safety-plan engine, on-device detection of isolation transitions, and crisis screening with counsellor handoff. The software flags cases, sets the order of review or selects approved wording. Assessment and action stay with the specialist, case manager, welfare worker or counsellor.
Scope The reference implementation runs on fixed synthetic inputs and reports virtual metrics; it is not an evaluation on a real cohort, clinical validity has not been assessed and no auditor has signed the result. It is not a counselling service.
P1 · Synthetic harness · prevent12
Early detection of acute crises from de-identified records
Uses coded longitudinal event sequences to raise an early alert for an acute crisis event and to order face-to-face assessment by a specialist. The alert does not replace the specialist's assessment.
- Zero-raw-text schema checkSynthetic coded event rows from the seeded generator → Admitted sequences, or reason codes for rejection
- Censored hazard risk modelEvent histories as observable on the training cut day → Channel weights and a risk score per evaluation time
- Recall-bound alert thresholdPeak scores before each calibration event, with weights → Frozen threshold, or none if positives are too few
- Review-queue routingScore, threshold, ensemble spread, history size, latest grade → Route and reason code
- Subgroup recall auditTest rows with group, score, outcome and weight → Per-group table, gap and verdict code
- Independent audit recomputationRun evidence document and frozen fixtures → Gate verdicts and benchmark entry
| Component | What it does | Input → output | Code |
|---|---|---|---|
| Zero-raw-text schema check | Admits only coded and numeric event rows. A row with an unlisted field or free text is rejected whole, and each sequence is checked for order and gaps. | Synthetic coded event rows from the seeded generator → Admitted sequences, or reason codes for rejection | prevent12/ |
| Censored hazard risk model | Fits an additive hazard with time decay to the training histories, allowing for subjects whose follow-up ended early, and scores the risk within the prediction horizon. | Event histories as observable on the training cut day → Channel weights and a risk score per evaluation time | prevent12/ |
| Recall-bound alert threshold | Sets the alert threshold from calibration positives by an order-statistic rule so that recall stays above the target with stated confidence, weighting for censoring. | Peak scores before each calibration event, with weights → Frozen threshold, or none if positives are too few | prevent12/ |
| Review-queue routing | Applies ordered rules to each score: priority alert, clinician review or routine. Missing model output and uncertain or near-threshold cases go to clinician review. | Score, threshold, ensemble spread, history size, latest grade → Route and reason code | prevent12/ |
| Subgroup recall audit | Computes recall per abstract subgroup at the frozen threshold and reports whether a group is below target or the gap between groups exceeds the tolerance. | Test rows with group, score, outcome and weight → Per-group table, gap and verdict code | prevent12/ |
| Independent audit recomputation | Without importing the unit's code, recomputes threshold, recall, group gap and routes from the evidence rows in exact rational arithmetic and compares them with the run. | Run evidence document and frozen fixtures → Gate verdicts and benchmark entry | prevent12/ |
Flow
- A seeded generator produces synthetic coded event sequences for abstract subgroups, and no clinical record or note text is read.
- Every row passes the zero-raw-text schema check, and subjects are split by enrolment day into training, calibration, embargo and test parts.
- The risk model is fitted only on what was observable at the training cut day, with change-point alarms from a numeric channel as one input channel.
- The alert threshold is set on the calibration part and frozen before it is applied to test subjects.
- Each test score is routed to a priority alert, clinician review or routine follow-up, and recall is compared across subgroups.
- The run document is hashed, and the independent audit recomputes the figures before a verdict is recorded.
What is guarded
- A subject the model cannot score goes to clinician review, never to routine follow-up, and a deterministic grade rule raises an alert regardless of the model score.
- The as-of split is checked for leakage: the audit fails if subjects overlap between parts or if information after a cut day was used.
- The run stops if the calibration part has too few positives for the recall bound, or if the generator's branching matrix breaks the stationarity condition.
- Every string in the run document must be an identifier-like token; free text is caught by the executor's own check and again by the first audit gate.
- The audit fails if the designed counter-cases are no longer exercised: a subgroup below target, a gap beyond tolerance and the clinician-review route.
Not built or not run
- Evaluation on a real cohort: no clinical records are in the repository, and the evaluation registry has no row roster yet for this unit's endpoint.
- The time-decay attention network exists only as an optional interface with shape and masking tests. The run uses a simpler additive hazard model and trains no network.
- Privacy checks for synthetic data fitted to real aggregates (nearest-record distance, membership-inference attack) are planned items and were not run.
- The operational controls in the specification, such as tracking recall and per-group alert rates in use, are not implemented.
Result and documents
Recall on the synthetic test set, weighted for censoring, was 0.9155 against the internal target of 0.90. The alert burden was 46.1 per 100 patient-months and episode-level precision was 0.079.
Synthetic inputs only (synthetic_only). These are virtual metrics on synthetic inputs. No real cohort has been evaluated, clinical validity has not been assessed and no auditor has signed the result.
Measured values, limits and gates on the P1 record · Early Detection of Acute Mental-Health Crises
P1 design specification: early detection of acute crises (KR) · P1 to P4 replay record (KR) · Audit record (JSON) · Run output (JSON)
P2 · Synthetic harness · prevent12
Risk trajectory and rule-constrained safety-plan support
Supports a case manager's follow-up after emergency-department discharge: it flags a rising risk trajectory from structured scale scores and walks through the safety-plan components using approved wording only. It is not a free-text chatbot, and a high-risk transition is connected to counsellors and the crisis network by fixed rules.
- Risk-trajectory flagContact intervals, response flags, integer scale grades → Flag code mapped to an engine event
- Safety-plan state machineCurrent state and one enumerated event → Next state and entry effects
- Approved template renderingState, plan reference IDs, confirmation mask → Canonical output with mandatory links
- Deterministic policy gate (gate A)Candidate output and the template manifest → Rejection codes (empty if accepted)
- Fail-closed release (with gate B)Candidate, gate A codes, classifier verdict → Released candidate or the fixed safe notice
- Independent audit of the engineRun evidence document and frozen manifest → Gate verdicts and benchmark entry
| Component | What it does | Input → output | Code |
|---|---|---|---|
| Risk-trajectory flag | Filters a hidden-state model over contact intervals, response and integer grades, then decides in a fixed order: rule, model, outreach. Invalid input is held for a human. | Contact intervals, response flags, integer scale grades → Flag code mapped to an engine event | prevent12/ |
| Safety-plan state machine | Applies the transition function to enumerated events. Handoff tickets, case-team notices and counsellor connection fire on state entry, whatever gates or generator do. | Current state and one enumerated event → Next state and entry effects | prevent12/ |
| Approved template rendering | Builds the canonical output for a state from its one approved template, slots that hold reference IDs matching a fixed grammar, and the mandatory escalation links. | State, plan reference IDs, confirmation mask → Canonical output with mandatory links | prevent12/ |
| Deterministic policy gate (gate A) | Rejects any candidate that is not the byte-exact rendering of an approved template with valid slots and all mandatory links, or that the external policy lexicon reports. | Candidate output and the template manifest → Rejection codes (empty if accepted) | prevent12/ |
| Fail-closed release (with gate B) | Releases the candidate only if gate A and an independent classifier both accept. Any rejection, fault or timeout discards it and returns the fixed notice. | Candidate, gate A codes, classifier verdict → Released candidate or the fixed safe notice | prevent12/ |
| Independent audit of the engine | Without importing the engine, rebuilds every transition from a separate rule table and checks template placeholders, hashes and the full fail-closed release matrix. | Run evidence document and frozen manifest → Gate verdicts and benchmark entry | prevent12/ |
Flow
- The trajectory flag turns structured follow-up observations into one engine event: high risk, outreach due, low risk or unrecognised.
- The state machine moves to the next state and fixes that state's entry effects before any output is generated or gated.
- The canonical output for the new state is rendered from the approved template, plan reference IDs and mandatory links.
- An untrusted generator is optional and is not called when the next state is terminal, which includes the crisis escalation state.
- If either gate rejects the candidate or fails, the fixed notice is sent, the session moves to the fail-safe state and a counsellor connection is requested.
- The audit recomputes transitions, release decisions and trajectory forecasts by different methods and compares them with the run.
What is guarded
- Closed output space: every output is the rendering of an approved template with grammar-valid slots and mandatory links, or the fixed notice. The property rests on the assumption that the approved wording has passed clinical review.
- From any non-terminal state a high-risk event leads to the crisis escalation state with its handoff effects and links, and the generator is not called.
- Terminal states are absorbing: a gate fault can replace the message with the fixed notice but cannot move the session or start new actions, so a session closed by withdrawal stays closed.
- Unrecognised input, a timeout, a request for a person or an invalid plan item goes to human review. The environment-safety component is not handled by the engine and becomes a clinician task.
- The manifest is verified at start (template hashes, link registry, fixed notice), and the audit fails if any transition or release decision differs from its own rule table.
Not built or not run
- Clinical review of the approved template wording: templates hold placeholders, and the approved text is kept in an external store and compared by hash.
- The policy lexicon and the independent classifier exist as interfaces with test stand-ins that read abstract tags. No real lexicon or trained classifier is included.
- The intent classifier that turns a user's free input into enumerated events and the plan store prepared with a clinician are specified only. The engine receives events and reference IDs directly.
- Parameter estimation for the trajectory model and its evaluation on follow-up data were not done; the model coefficients are virtual values.
Result and documents
Disallowed output events on the synthetic test: 0 of 30,210, against a target of zero. The value holds within the closed template space, on the assumption that the approved wording has passed clinical review.
Synthetic inputs only (synthetic_only). These are virtual metrics on synthetic inputs. No real cohort has been evaluated, clinical validity has not been assessed and no auditor has signed the result.
Measured values, limits and gates on the P2 record · Safety-Plan Support after Emergency Care
P2 design specification: risk trajectory and safety-plan engine (KR) · P1 to P4 replay record (KR) · Audit record (JSON) · Run output (JSON)
P3 · Synthetic harness · prevent12
Consent-based on-device detection of isolation transitions
With prior explicit consent that can be withdrawn at any time, uses daily statistics aggregated on the device to detect a sustained transition into social isolation and to order wellbeing checks by a community welfare worker. It is not a location-tracking or content-monitoring tool, and a person does the checking.
- Daily aggregate featuresHourly activity, relative distances, beat intervals → Daily numeric features
- Change-point detection on baselineDaily residual series with unworn days as gaps → Length and mean of the last segment
- Sustained-shift rule gateWear mask, residual series, last-segment summary → Reason code, and features if scored
- Precision-certified thresholdCalibration scores and labels → Certified threshold or none, with the test table
- Consent and export gatePayload, consent ledger, scope, privacy ledger → Accept, or the first refusal code
- Independent audit recomputationRun evidence document and frozen scenarios → Gate verdicts and benchmark entry
| Component | What it does | Input → output | Code |
|---|---|---|---|
| Daily aggregate features | Computes rest-activity regularity, relative movement dispersion, interaction counts and a physiological load index. It accepts no coordinates, content or identifiers. | Hourly activity, relative distances, beat intervals → Daily numeric features | prevent12/ |
| Change-point detection on baseline | On series standardised against the person's own baseline, runs Bayesian online change-point detection to find when the last segment began and how far its level moved. | Daily residual series with unworn days as gaps → Length and mean of the last segment | prevent12/ |
| Sustained-shift rule gate | Declines to judge when wear is too low, the baseline is too short or the shift is not sustained. Only subjects that pass receive multi-scale features for scoring. | Wear mask, residual series, last-segment summary → Reason code, and features if scored | prevent12/ |
| Precision-certified threshold | Tests a fixed grid of thresholds with an exact binomial test and keeps the lowest one whose precision is certified above the target. It returns none if none is certified. | Calibration scores and labels → Certified threshold or none, with the test table | prevent12/ |
| Consent and export gate | Before anything leaves the device, checks live consent for that scope, then the exact allow-list schema, then the privacy budget, and names the first cause of refusal. | Payload, consent ledger, scope, privacy ledger → Accept, or the first refusal code | prevent12/ |
| Independent audit recomputation | Without importing the unit's code, recomputes the certification test, confidence bounds and prevalence-shift bounds from the evidence rows in exact rational arithmetic. | Run evidence document and frozen scenarios → Gate verdicts and benchmark entry | prevent12/ |
Flow
- Sensor readings are designed to be reduced to daily aggregates on the device, while the reference run starts from synthetic daily series of several scenario types.
- Each channel is standardised against the person's own baseline, and the change-point detector locates the last segment.
- The rule gate withholds judgement for low wear, a short baseline or an unsustained shift, and a logistic classifier scores the rest.
- A threshold is certified on a separate calibration cohort and then applied to the test cohort.
- The certified threshold is re-examined under lower assumed prevalences, and each prevalence is marked certified or not certified.
- Sharing a result or contributing a noised aggregate must pass the consent, allow-list and privacy-budget gate, and the audit then recomputes the figures.
What is guarded
- Export follows an exact allow-list: an extra, missing or forbidden key is refused, and so is an out-of-range value or a finer time or region resolution.
- Consent is opt-in per scope and scopes are independent. Withdrawal closes every scope at once and issues directives to stop sensing, erase local keys and request server deletion.
- Differential-privacy noise is applied only to research aggregates, and a ledger refuses any release that would exceed the privacy budget.
- The run stops if no threshold can be certified on the calibration cohort. A prevalence is certified only when a conservative lower bound on precision reaches the target.
- The audit re-judges the payload cases with an exact-key check instead of the forbidden-word list, and fails unless both accept and reject verdicts and both certified and not-certified outcomes occur.
Not built or not run
- Evaluation on real participants: no sensor data from people was used, and the public datasets named in the specification carry no label for an isolation transition.
- The subject-wise cross-validation and the semi-synthetic evaluation designed for those datasets are planned items and were not run.
- The relation that maps regional statistics to isolation prevalence is an external input that has not been estimated.
- There is no device runtime (sensor capture, volatile buffer, key erasure), and the multi-scale neural classifier is an optional interface. The run scores synthetic series with logistic regression.
Result and documents
Synthetic precision for detecting a sustained transition was 0.978, with a one-sided 95% lower bound of 0.933, against the internal target of 0.85. Whether the threshold stays certified depends on the assumed prevalence, listed below.
Synthetic inputs only (synthetic_only). These are virtual metrics on synthetic inputs. No real cohort has been evaluated, clinical validity has not been assessed and no auditor has signed the result.
Measured values, limits and gates on the P3 record · Consent-Based Detection of Transitions into Isolation
P3 design specification: on-device isolation transition detection (KR) · P1 to P4 replay record (KR) · Audit record (JSON) · Run output (JSON)
P4 · Synthetic harness · prevent12
Crisis screening and immediate counsellor handoff
On a public youth counselling platform, classifies each turn for signs of crisis; when a turn is flagged it stops autonomous AI replies and hands the session to a human counsellor and the official crisis lines. The handoff guarantee covers detected turns only, and how many turns the screen detects is a separate measure.
- Text normaliserOne turn of text → Normalised symbol sequence
- External lexicon matcherSymbol sequence and the digest bundle → Match, no match or unavailable
- Screening verdict and triggerRule verdict, model probability, threshold → Trigger or safe verdict for the turn
- Default-deny generation gatewaySession state and a per-turn grant → Generation and delivery allowed or dropped
- Fail-closed handoff routerTriggered turn and an injected fault schedule → Timed event trace and terminal handoff state
- Independent trace auditRun evidence document and frozen router settings → Gate verdicts and benchmark entry
| Component | What it does | Input → output | Code |
|---|---|---|---|
| Text normaliser | Reduces one turn of text to a sequence of consonant, vowel and other symbols so that spelling variants of the same expression arrive at one form. It holds no vocabulary. | One turn of text → Normalised symbol sequence | prevent12/ |
| External lexicon matcher | Matches symbol windows against a signed bundle of keyed digests from an authorised institution. The bundle holds no term text; failed verification makes it unavailable. | Symbol sequence and the digest bundle → Match, no match or unavailable | prevent12/ |
| Screening verdict and trigger | Maps a model probability to safe, risk or error; a missing model or invalid output is an error. A rule match, a model risk or any unavailable screening part triggers. | Rule verdict, model probability, threshold → Trigger or safe verdict for the turn | prevent12/ |
| Default-deny generation gateway | Is the only holder of the generator. Generation needs a safe verdict for this session and this turn on an unlatched session, and the latch is checked again at delivery. | Session state and a per-turn grant → Generation and delivery allowed or dropped | prevent12/ |
| Fail-closed handoff router | On a trigger, first latches the session, then shows the official contact panel, records the handoff, queues a counsellor and escalates to a person or the hotline bridge. | Triggered turn and an injected fault schedule → Timed event trace and terminal handoff state | prevent12/ |
| Independent trace audit | Without importing the router, derives the expected events and timing of every fault combination from the fault code and timing settings alone and compares each trace. | Run evidence document and frozen router settings → Gate verdicts and benchmark entry | prevent12/ |
Flow
- Each turn is normalised to a symbol sequence and matched against the externally supplied lexicon bundle.
- The rule verdict and the model verdict are combined by OR, and an unavailable lexicon or a model timeout or error also counts as a trigger.
- If the turn is safe, the gateway issues a grant valid for that turn only and the AI reply is delivered.
- If the turn triggers, the session is latched at once, any unsent AI reply is cancelled, and the official contact panel is shown by the server or the client watchdog.
- The handoff is committed with retries, a counsellor queue is assigned, and acknowledgment escalates through three roles, ending in a hotline bridge if no one answers.
- Later turns in a latched session go to the human channel without screening, and the audit rebuilds every trace independently.
What is guarded
- After a trigger there is no generation grant and no AI reply in that turn or in any later turn of the session.
- The memory latch is set immediately after the trigger, before storage or notification. A client-side latch lets the handoff restart after a server crash.
- Each failure has a defined path: a failed commit leads to degraded mode with an out-of-band page and an incident record, a full queue to a reserve pool, and no answer to the hotline bridge.
- The whole modelled fault space is enumerated and each turn is judged against the handoff invariants. The audit fails if any fallback branch was not exercised or a trace differs from the expected one.
- Code, fixtures and property-test files are scanned for Hangul characters and must contain none, so that no vocabulary can be embedded. Inputs are placeholder tokens.
Not built or not run
- The screening model is not trained, so screening recall is not measured. The multi-task network exists only as an optional interface.
- The authorised lexicon and an eligible counselling corpus are external inputs; the harness uses placeholder tokens.
- Times are sums of virtual configuration values, not measured latency. Separating the generation service by process and network policy is modelled only as object ownership.
- A model-checking specification that covers message reordering and races between servers was not written.
Result and documents
Immediate handoff on the synthetic test: 1,584 of 1,584 detected turns, across 1,728 fault combinations. The value lies within detected turns and the modelled fault space; screening recall was not measured.
Synthetic inputs only (synthetic_only). These are virtual metrics on synthetic inputs. No real cohort has been evaluated, clinical validity has not been assessed and no auditor has signed the result.
Measured values, limits and gates on the P4 record · Student Crisis Screening and Immediate Counsellor Handoff
P4 design specification: screening and immediate handoff routing (KR) · P1 to P4 replay record (KR) · Audit record (JSON) · Run output (JSON)
How to read this screen
This screen describes structure: the parts, the order work passes through them and what each run is checked against. It carries no measured value of its own. The figure in each result paragraph is filled from the audit file when the site is built, and every component names the code that does the work.