Skip to content

GiveCare SMS Runtime Contract

Type: reference.

This document is the canonical public contract for the current SMS runtime. Cross-repo consumers use its exact gc-sms.care care.runtime.project owner projection, pinned to a commit through the root projection-ref command. They do not infer current behavior from source files.

GiveCare SMS is a care harness: the care equivalent of a coding harness. Each caregiver is one Pi conversation; code owns every effect. Its components, in harness terms:

Harness component In the care harness
Model loop Luna as the Pi conversation's own generation
Action space The care tools: remember, update_plan, find_help, schedule_check_in
Context management The transcript, Pi compaction, and the caregiver section
Planning The plan step and its outcomes: the longitudinal arc
Permissions The gate, and the tool veto hook
Checks Jev's input, evidence, and output guardrails
Stuck limits 4 Luna requests per turn, rate limits, and the fallback
Environment The record, the outbox, and the clock
Evaluation Replay on frozen scenarios and InvisibleBench: same harness, different model

The same harness is built from eight primitives:

  1. Conversation (Pi). Each caregiver is one Pi conversation in one Cloudflare Durable Object. The transcript is the thread. Pi compaction keeps a long relationship bounded. An inbound message is admitted once per provider SID.
  2. Record. runtime/records.ts holds what the transcript cannot. Caregiver (consent, last safety concern, outbox index, latest SID, pending burst), Message (one per SID), Profile (saved facts as the caregiver's exact words, the plan step, outcomes, code's summary lines, what was already suggested), OutboxItem, and SafetyEvent. Assessment and enrollment have their own docs.
  3. Context. runtime/context.ts renders the record as facts for Luna: scores, score change, a recent safety concern, a check due, saved facts with ids, the plan, outcomes, and what was suggested. The persona in runtime/mira.ts says how to weigh them.
  4. Tool. runtime/tools.ts gives Luna remember, update_plan, find_help, and schedule_check_in. Each validates the caregiver's exact quote and the record, commits, and leaves a code receipt. A beforeTool hook vetoes on consent or an instruction override.
  5. Guardrail (Jev). An input guardrail reads the whole unanswered burst before Luna. An output guardrail checks Luna's reply. Relevance and evidence checks run inside find_help.
  6. Gate (code). channel/gate.ts: STOP, START, PAUSE, consent, exact crisis phrases, identity, CHECK assessment commands, and support menus, all before any model. runtime/memory.ts owns exact saved-note removal controls before model processing.
  7. Outbox. runtime/outbox.ts: every send rechecks consent, quiet hours, and ordering. Crisis replies retry. Provider callbacks reconcile.
  8. Clock. Durable Object alarms wake the outbox and scheduled work.

Memory is primitives 1 to 4 together, not a separate store. The thread remembers what was said (Pi compaction). Profile keeps what lasts. Luna writes it through remember and update_plan, and reads it through the caregiver section. The code-owned "What you remember" menu shows saved notes with stable numbers. Whole-message FORGET <number> or FORGET ALL controls remove selected notes and start a fresh model context through Pi's native reset. Retained records remain available through the caregiver section. Vague or conditional requests remove nothing. Message history remains; saved-note removal does not establish physical erasure. Account deletion clears the Durable Object.

The product invariant is:

Code gates. Jev guards. Luna answers through checked tools. The outbox delivers.

Nothing durable comes from generated text alone. Luna (the language model) changes the record only through a tool call that code validates against the caregiver's own words. Jev (the TypeSafe judge) answers narrow questions about the caregiver's message, the candidate catalog items, and Luna's reply.

Layers

Folder is role. .oxlintrc.json fences the imports, and pnpm lint enforces them: care/ imports nothing of ours; channel/ imports care/; guardrails/ imports care/ and channel/; runtime/ imports everything. Nothing imports eval/ or scripts/.

Care

care/ is the pure domain: no network or storage framework. It is the shared contract the other layers must preserve.

  • profile.ts: caregiver facts, profile lines, and score change
  • safety.ts (SafetyRecord: level, route), benefits.ts, support.ts, time.ts, text.ts: safety routes, benefits screening, support need tags and sources, local time, and text normalization
  • assessment/: instruments and scoring
  • knowledge/: catalog, fit ranking, passages, and ontology

Reply shape, assessment commands, Jev judgments and citations live in the layers that use them: channel/reply.ts holds the plain Reply (body, optional safety route, citations) and code's receipts; channel/assessment.ts the assessment commands and copy; guardrails/judgments.ts Jev's answers, the thresholds that turn judgments into permission and check-in timing; guardrails/citations.ts the passage citations.

Channel

channel/ is how we talk, and imports care/: the gate (gate.ts), consent, SMS rendering and limits (sms.ts), choices, menus, send policy, send retry policy (sendRetry.ts), and the signup, web, and email boundaries.

Guardrails

guardrails/ holds the checks around the model, and imports care/ and channel/: input.ts (input guardrail), reply.ts (output guardrail and the reply check), relevance.ts, questions.ts (every question the runtime asks), safetyFloor.ts (code-written safety lines), and jev.ts (transport).

Runtime

runtime/ is source only: the Worker, Durable Objects, and Pi Durable wiring.

  • admit.ts is admission (receive): the sender check, the gate, consent changes, and the opt-out receipt. harness.ts is the care harness: the givecare.turn task (read, answer, reply check, context reset/write, and delivery checkpoints) and recovery.
  • records.ts, context.ts, mira.ts, tools.ts are primitives 2 to 4. The rules for what Mira keeps (saved facts, the step and its outcomes) are pure functions in care/profile.ts; the tools and memory.ts validate, call them, and commit. Luna runs as the conversation's own Pi generation through pi-ai, with at most 4 provider requests per turn and 3,200 output tokens per request. Private identifiers are redacted before any model and before the thread.
  • lookup.ts is find_help's catalog lookup. It filters the catalog by the need tags Luna passed, asks Jev to re-check every candidate in full (guidance and strategy pages claim by claim), and keeps the best. Benefit screening and the numbered passages are built in care/knowledge/passages.ts.
  • nearby.ts is the one live external lookup.
  • outbox.ts, twilio.ts are the outbox and transport; assessment.ts, enrollment.ts, directory.ts, email.ts (the EmailContact object), emailList.ts (the EmailList object), emailTemplates.tsx, unknown.ts, operator.ts own the remaining durable concerns. worker.ts is the router; env.ts the bindings type; caregiver.ts the Caregiver object; http.ts (shared request plumbing and the public signup route), emailHttp.ts (the public email routes) and observability.ts serve the Worker. The operator API serves only /operator/work and /operator/caregiver (read-only), plus the operator email routes in emailHttp.ts.

The Worker registers the OpenAI provider; OPENAI_API_KEY supplies authentication. There is no automatic provider failover. The bakeoff may register other providers inside isolated SQLite with simulated delivery.

eval/conversations/scenarioKernel.ts replays a caregiver through the same runtime/harness.ts loop over node SQLite, with simulated delivery. It does not prove Cloudflare HTTP, alarms, or handset delivery.

One caregiver Durable Object owns care state and its Pi harness. Shared objects (Directory: phone ownership, enrollment coordination, and global budgets; EmailContact: publication consent, suppression, email delivery; EmailList: subscriber-list projection, frozen issue review and scheduled fan-out; UnknownMessage) use native RPC with explicit failure recovery; their updates are not one global transaction. There is no separate onboarding engine, coding-agent session, or scheduler beyond Pi tasks and alarms. Operator and partner administration are not implemented.

Owner projections

care/knowledge/ adapts generated JSON bundles into one catalog with four sources:

  • benefits
  • resources
  • strategies
  • guidance

The catalog supplies canonical candidate text and source references. Code filters by scope and need tags; Jev checks the remaining candidates for relevance. Luna passes the need tags to find_help, and may pass several. A candidate excluded by those filters never reaches the relevance check.

All generated inputs are downstream artifacts. Each source owner commits its projection to Git. Each gc-sms consumer resolves a pinned owner-projection ArtifactRef for an exact owner commit through the shared GiveCare protocol's projection-ref command, verifies the artifact digest, validates the owner schema, and replaces only fixed local files atomically.

  • gc-benefits.registry projects the benefits bundle.
  • gc-wiki.knowledge projects resources, strategies, and reviewed guidance.
  • tools.assessments projects the assessment instruments.

These consumers are declared as owner-projection-sync adapters in .givecare/module.json. They do not import another repository, fetch live owner data, accept an unverified file path, or maintain another source of truth.

Main Flow

  1. runtime/twilio.ts verifies the exact Twilio URL and posted fields, then routes the signed sender to its caregiver object.
  2. Admit. receive (runtime/admit.ts) checks the sender, then runs the gate inside the caregiver's Pi transaction. Provider SIDs make admission idempotent. A button tap resolves to the choice it offered, or is recorded as stale.
  3. Gate. STOP, START, and PAUSE update consent; HELP leaves consent unchanged and gets the transport-managed help response; exact crisis phrases persist a safety record and their code-written route line before delivery. Paused or identity-uncertain text is screened by the input guardrail alone. Ordinary text joins the caregiver's pending burst.
  4. Admission creates a givecare.turn task atomically with the message record; the Durable Object alarm wakes it. Native input submissions place model-bound messages in the thread. Code-owned replies use native write submissions. Task checkpoints reserve context admission, and native task dependencies order it around live runs and saved-note removal. Request IDs dedupe each submission across restart. Delivery does not wait for a transcript write; a removal confirmation does wait for its reset.
  5. Read. Code answers first: a CHECK assessment command or a tapped support menu commits a code-owned reply with no model. Otherwise the newest message answers every unanswered text in its burst, so none goes unread. Jev's input guardrail reads the whole burst, with the recent thread, before Luna. An urgent or emergency route commits code's route line and Luna never runs, except a plain clinician concern, which Luna answers under the code-owned clinician line. An unavailable guardrail commits a bounded fallback and flags the turn for review. A paused caregiver gets the bounded explanation. The caregiver's own cap is 20 answered messages per clock hour; past it, one notice, then silence.
  6. Answer. Code refreshes the caregiver context section. Luna answers as the conversation's own generation, with the burst as her input. She may call tools; each is gated, validated, and committed on its own. find_help returns passages with unique citation tags, the only facts a reply may state, and records them on the turn. schedule_check_in queues a delivery the caregiver asked for; code reads the day and time from the message. Directory enforces one global budget of 300 Luna replies per hour across all caregivers; a denial uses the same notice-once behavior. Task memos retain budget decisions before admission; recovery reuses an existing native submission without requesting another grant.
  7. Check. Jev's output guardrail judges Luna's complete reply once, each sentence against the passages it cites; code text (the route line, receipts, choice text) is never sent. It reads external claims, certainty, clinical and legal authority, actor and effect claims, and unsafe assistance. Code strips the tags and binds the cited passages to each sentence. An unsupported sentence or reply-level failure rejects the whole draft; sentences are never rewritten after judgment. A rejected, overlong, or superseded reply is edited out of the transcript, so Luna never remembers saying it, and recovery sends the fallback and flags review.
  8. Send. The reply and code's receipts queue one OutboxItem. The outbox sends it (below).
  9. Failure. Missing guardrail answers, an empty or failed Luna answer, and unsupported replies take bounded recovery. Pi retries a failed provider request once; checkpoints preserve progress across interruption. A newer message supersedes an unsent reply.

The read phase and the answer phase have separate 55-second deadlines.

Failure template

Recovery commits one bounded fallback and retains the Message record in review status, with its reviewReasons. Operator notification and a staffed review queue are not implemented. With no observed safety floor the reply is fixed: "I couldn't get a reliable answer this time. You don't need to repeat your details. This issue is flagged for GiveCare review." Recovery adds no unverified recommendation or new task. When the input guardrail crossed a safety floor, recovery sends that floor's safety line instead (below). A retry never lowers a floor already observed.

Safety route lines

The route line is code's, never Luna's. channel/safetyCopy.ts holds the approved texts for the deterministic gate and guardrails/safetyFloor.ts. The safety floor chooses copy without lowering minimum urgency:

Input reading Code reply
Emergency with a sufficiently confident primary 911 or 988, and the competing crisis route below the emergency cutoff The selected referral's own line and route. A clear 911 reading adds no self-harm referral.
Emergency without that specific referral evidence The combined 911/988 line, recorded on route 911.
Urgent, with protective_services selected The protective-services line.
Other urgent reading The urgent line. A plain clinician concern gets only the clinician sentence above Mira's answer.

When the input guardrail crosses the urgent or emergency floor (inboundSafetyFloor), code sends the route line alone and Luna does not run, unless Jev chose the clinician with 988/911 mass under the review cutoff: then every reply on that turn carries the clinician line first, with safety delivery. JUDGMENT_THRESHOLDS owns the Choice confidence and emergency cutoffs used for referral specificity. An observed emergency floor takes precedence over a lower route, including when no specific crisis referral can be selected.

Signup Flow

Web enrollment is a separate adapter, not an inbound turn or onboarding workflow:

  1. POST /api/signup validates E.164 phone, first name, email, explicit SMS consent, separate publication consent and bounded attribution. Native per-IP/phone limits protect admission.
  2. Directory coordinates one enrollment for a phone. The caregiver owns its consent, enrollment and welcome; EmailContact owns receipt and publication eligibility. Native RPC failure recovery completes partial work without claiming cross-object atomicity.
  3. A supplied assessment handoff must be unexpired, unused and email-bound. Caregiver redemption and email ownership are reconciled explicitly.
  4. Repeated enrollment does not overwrite identity or reactivate stopped consent. Sponsor codes are rejected at the form.
  5. Delivery re-checks permission and welcome expiry. The welcome introduces GiveCare and offers a simple starting point; taps and typed replies enter the same care path. A single silent-signup follow-up remains permission- and quiet-hours-bound.

First-Party Web Adapter

Worker routes cover signup, named-publication subscription, assessment email, signed email events, token-bound unsubscribe and human issue approval. Weekly email approval owns the publication review contract. Transactional email is separate from marketing consent; bounce and complaint suppress the contact. Assessment scores are derived from submitted answers in server code.

Web-event analytics, population dashboards and general operator/partner APIs do not exist and return 404. No staff route changes care state. See runtime/README.md for exact HTTP boundaries.

Boundary Paths

Gate decisions are deterministic for:

  • exact STOP/HELP transport-managed SMS responses, including Twilio Advanced Opt-Out OptOutType when the carrier already replied
  • pause/restart language
  • obvious emergency/self-harm/poison/abuse signals
  • identity-sensitive account requests when identity is unverified
  • the CHECK assessment command and support-menu taps
gate -> code-owned command or menu -> input guardrail
     -> Luna with tools -> output guardrail -> outbox

channel/assessment.ts owns exact assessment decisions; runtime/assessment.ts validates delivered-question binding and scoring. Saved task phases own recovery. The care task checks current consent and turn order before applying a command.

The input guardrail is isolated: its questions carry no catalog, so catalog noise cannot move the safety floor. Its reading is frozen for the turn, and a later check cannot lower a floor the message already set. It gates what Luna may do: the tool gate reads its instruction-override and check-back signals. An unavailable or invalid required reading ends the turn with judge_unavailable before any Luna request.

The shared verifier requires a complete reply receipt bound to the exact reply, redacted caregiver input, and cited evidence. guardrails/ owns model requests and response validation; guardrails/judgments.ts owns the product rules over normalized evidence. riskFloor derives urgent or emergency handling from an observed inbound route and preserves it through recovery. The deterministic safety gate remains independent of Jev.

Earlier calibration results in docs/model-selection.md describe the earlier question contract. They do not validate the current prompts or operating cutoffs. Current receipts and independent labels are required before release. JUDGMENT_THRESHOLDS (guardrails/judgments.ts) groups every cutoff by the permission it grants; the cutoffs are operating cutoffs, not calibrated accuracy (safety-contract.md).

Safety is enforced at increasing-cost boundaries: deterministic gate decisions, the isolated input guardrail and code's floor, the code-written route line, tool validation, the output guardrail, and the outbox's send-time checks. Offline gc-bench verification consumes transcripts afterward and never substitutes for the live gate.

The code-coupled hazard and proof contract is in safety-contract.md.

Outbox and tool rules

Every send re-checks channel state, so a caregiver who opts out while a turn runs is not texted.

Transport owns delivery state. A Pi task persists its claim before calling Twilio, then records acceptance. Signed callbacks reconcile later status and SID attachment races. Unknown provider acceptance is held as ambiguous; restarting or retrying admission cannot authorize a blind resend. Per-caregiver sends serialize through native task waiting. A crisis reply gets up to three provider attempts with backoff. Directory also enforces a provider-wide budget of 25 outbound texts per minute; a denied send defers one minute and is re-queued by the alarm. The budget is asked only after status, consent and ordering are settled, so a waiting or blocked delivery spends nothing. A safety route line is exempt from that throttle. An unavailable Directory allows the send: the budgets are cost guards and never outrank care.

Tools write only what the caregiver said. Before remember saves an exact quote, Jev reads it in the full message through the retention boundary. update_plan keeps one current step in their words and its outcomes. Code-owned saved-note controls remove selected facts and reset model context through Pi; the removal contract defines what remains available. A tool quote that is not in the current message or holds a private identifier is refused. Tools are vetoed while consent is not active or the message tries to override Mira's instructions. Each tool leaves a code receipt on the turn; Luna is told not to claim a change herself.

The caregiver's plan is deliberately small: one current step in their own words, with its last outcomes. Luna supplies an exact quote; Jev classifies whether it establishes a step or reports on the current one. Unavailable, uncertain, paused, or unrelated readings change nothing. The tool rechecks the current step before committing. Luna's prose never becomes the stored step.

Mira invites a six-area check (reply CHECK) only when code finds it due (a missing baseline or one older than the instrument's cadence) and the moment fits. The caregiver starts it with the command; the runtime owns the exact questions, observed answers, scores, and eligibility. Current needs interrupt without losing the question.

Current Production Gaps

Local mechanics do not establish release readiness. The native replay uses the Harness clock, committed reply and tool records and the shared provider acknowledgement path. These mechanical contracts do not establish live semantic accuracy. Release boundaries are tracked in release gaps.

Full live replay of the final UX correction was not completed; paid testing was stopped. Independent Jev semantic disagreements remain. Real-phone onboarding, RCS verification, workload/latency and restore rehearsals still need proof. Operator/partner administration is not implemented.

Editing this owner document does not refresh a consumer's pinned projection. A separately verified owner commit and projection sync are required.