cairn
CLAUDE.md12 starsChanged 4 months agoMITView on GitHub
Guidance for agents working in this repo. AGENTS.md symlinks here, so every agent loads this file every session. Keep this file lean. It is a map of non-obvious constraints, not an encyclopedia. Do not inline API/tool inventories, changelogs, or per-round history — link out instead. When you want to add detail, add it to docs/ARCHITECTURE.md (or the right doc below) and leave a pointer here. A self-hosted, connected, day-reading wellness OS for training / nutrition / longevity with an agentic…
The file
We split this CLAUDE.md into the rules it gives an agent
9 rules. About 0 are common, 3 are distinctive, and 6 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 23
Read it before shaping product behavior.
- Very specific: line 53
Every agent spawn goes through one process-wide semaphore (CAIRN_MAX_AGENT_PROCS, src/agents.ts).
- Very specific: line 85
index.htmldoes not load every bundle: Only the Today/You shell (and the week menu's frame, 06-coach-meals) is eager. - Very specific: line 124
Prompts do not get the whole coach context: Every DATA: block is built by promptData(ctx, "<site>") (src/prompt/context-projection.ts), a …
- Very specific: line 166
When verifying by hand, prefer node test/run.mjs <files> (or npm run test:changed): it enforces per-file heap, RSS and time budgets — see …
- Very specific: line 195
Put new agentic orchestration in coachOps/*, not duplicated in the surfaces.
- Very specific: line 487
Add a phrasing to the set.
- Distinctive: line 639
No numeric scores anywhere: No 0-100 grades, no metric walls.
- Distinctive: line 658
Only hashes of session secrets, pairing codes, MCP keys and OAuth codes/tokens are stored, and none of them — nor the token — may reach a …
≈ “Common” is an estimate: at least 1 in 5 of the 28,029 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md
Guidance for agents working in this repo. AGENTS.md symlinks here, so every agent loads this file
every session.
Keep this file lean. It is a map of non-obvious constraints, not an encyclopedia. Do not inline API/tool inventories, changelogs, or per-round history — link out instead. When you want to add detail, add it to
docs/ARCHITECTURE.md(or the right doc below) and leave a pointer here.
What Cairn is
A self-hosted, connected, day-reading wellness OS for training / nutrition / longevity with an agentic coaching loop. It opens to a calm Brief that reads your whole picture and suggests what kind of day today should be, propagates flagged lab findings across every domain they touch (the "connected brain"), runs adaptive nutrition, learns who you are, and surfaces quiet cross-domain insights one at a time.
One Node service (src/server.ts) serves four surfaces from one process: a vanilla PWA (/), a REST
API (/api/*), an MCP server (/mcp, Streamable HTTP), and a background scheduler. Storage is
SQLite via Node's built-in node:sqlite.
docs/VISION.md is the constitution — calm, suggestion-not-a-gate, no-scores, pull-never-push.
Read it before shaping product behavior. (Its progress log is maintained separately; don't edit it as
code housekeeping.)
Commands
npm run dev # tsx watch on src/server.ts -> http://localhost:8787 (auto-seeds on first boot)
npm run build # typecheck client + transpile src/client -> public/js + tsc -> dist/
npm start # node dist/server.js (run build first)
npm test # node:test harness, sharded; pretest builds dist/
npm run migrate # print current user_version, apply pending migrations
npm run reset # delete data/cairn.db* and re-seedFull deploy / migration / backup / restore playbook: docs/OPERATIONS.md. Docker image details and
release flow: docs/SHARING.md.
Hard requirements
- Node 24 is the floor, Node 26 is what ships —
node:sqliteis unflagged from 24; the Docker image, the release workflow and the primary CI lane run 26. No native build step. - ESM with explicit
.jsimport extensions (tsconfigisNodeNext). Importing a sibling.tsmodule is writtenfrom "./repo.js", never"./repo". - Every string rendered into
innerHTMLgoes throughescHtml/escAttr. The only exceptions are the two SVG libraries (art.js,cairn-body-figure.js), whose output is authored geometry and never interpolates caller text.
The traps that actually bite
AgentBusyError (code: agent_busy) means the host had no CLI spawn permit — never a bad job.
Every agent spawn goes through one process-wide semaphore (CAIRN_MAX_AGENT_PROCS, src/agents.ts);
a runner that catches this must defer-and-retry, never fail the row or rotate to the next agent.
Details: docs/ARCHITECTURE.md "The process-wide agent spawn cap".
A chat reply's claims are checked against the actions that landed. groundReply (src/chatGrounding.ts) is
the one place a "done it" sentence is held to what the server applied; extend that module, never add a
per-case claim patch elsewhere. Details: docs/ARCHITECTURE.md "Chat routing".
Chat's DATA block must not travel in argv. Linux MAX_ARG_STRLEN is 32 × page size (512 KiB on
a 16K-page Pi 5, 128 KiB on 4K-page hosts). A chat prompt that inlines there throws E2BIG at spawn
in ~5 ms and every rotated agent "process failed". buildAgentLaunch keeps small prompts on {prompt}
and delivers oversized ones via stdin / --prompt-file. Never raise the inline cap
to "whatever fit last time".
Schema changes are two-step. For a brand-new table, add a CREATE TABLE IF NOT EXISTS in
src/db.ts and you're done. For a column on an existing table do BOTH: (1) add it to that table's
create block in db.ts so fresh DBs get it, and (2) append an entry with the next integer version
and an idempotent try/catch ALTER TABLE … ADD COLUMN to the range file covering it — v001-050.ts /
v051-100.ts / v101-150.ts under src/migrations/, helpers in migrations/helpers.ts, migrate.ts
only the runner, frozen snapshots in migrations/frozen/ never edited or reformatted. npm run
schema:check (in npm run verify) fails half a two-step. No down-migrations — back up first, and
never hardcode the schema version in docs; the range files own it.
The service-worker cache version is DERIVED — never hand-bump it. public/sw.js ships the
placeholder const CACHE = "cairn-shell-dev"; src/swVersion.ts serves /sw.js with that literal
replaced by cairn-<hash>, a content hash over every asset the worker precaches. So a changed shell
always ships a new cache name and an unchanged one never re-downloads. What you MUST still do by
hand: add every new static asset to CORE_ASSETS in public/sw.js — an asset missing there is
neither cached offline nor covered by the hash. Do not rename the placeholder (the substitution is
an exact match, and scripts/check-sw-cache.mjs asserts it). Art URLs carry v=; never strip it
— the SW cache-first layer keys on the full URL and evicts older v for the same kind+q.
index.html does not load every bundle. Only the Today/You shell (and the week menu's frame,
06-coach-meals) is eager; every bundle marked lazy: "<name>" in BUNDLES
(scripts/build-client.mjs) — Train › Intake (today's food, the fuel bundle), Train, Horizon, Ask, Settings, Me/Health, a day's
glance / view / page, the journey reads, body metrics, the welcome, the AI sign-in, the meal planner
— is injected on first navigation by ensureBundle/withBundle (src/client/app/lazy-bundles.ts),
warmed on idle, and still precached. A lazy bundle depends only on what it uses
(LAZY_BUNDLE_DEPS); Horizon does not drag in Train. The eager JS ceiling is in
scripts/bundle-budget.json, and a cold route's bytes are held by npm run perf:check. A lazy
bundle may own a stylesheet: the last cascade partials listed in LAZY_STYLE_SHEETS
(scripts/build-styles.mjs) ship as public/css/<bundle>.css, added by the loader (LAZY_BUNDLE_CSS)
and precached in CORE_ASSETS; only partials no eager partial follows may move there (a tied
rule would flip), and a small sheet compresses badly alone, so keep the eager rules eager. So eager code reaches a lazy
global ONLY through withBundle(name, fn) (or a typeof guard), never at top level —
test/lazyBundleContract.test.js enforces it. Each lazy entry also names the views it renders; the
build derives index.html's cold deep-link preload table from them (scripts/lazy-route-preload.mjs)
— a generated section of a committed file, so commit the rebuilt index.html. A job-reconnector
factory in a lazy bundle is swept by the first NAVIGATION into it (withBundle), never by the idle
warm-up, which runs off its view.
public/js/*.js is generated from src/client/**/*.ts by npm run client:build; the only
hand-written file there is the 10-boot.js shim. Never hand-edit generated output. public/styles.css is
generated too (committed): edit the per-surface partials under src/styles/, whose cascade order is
STYLE_PARTIALS in scripts/build-styles.mjs (ownership map: docs/DESIGN.md). The client
modules share ONE global scope in load order, so a top-level eager cross-module reference must use a
lazy () => fn() thunk — function hoisting does not cross <script> boundaries.
There are two TypeScript compilers, on different majors, and npx tsc is NOT the one that
builds. The typescript dependency is aliased to @typescript/typescript6, so bare npx tsc
resolves to TS 6. npm run tsc is node node_modules/typescript-7/bin/tsc — TS 7 — and that
is what npm run build and npm run typecheck:client use. Typecheck with npm run tsc -- --noEmit;
a clean npx tsc proves nothing about whether the build passes.
npm run format hardcodes --write . (the whole repo, which is not biome-clean at rest). To
format only what you touched, run ./node_modules/.bin/biome format --write <files> directly.
npm run lint is lint rules only. Note that per-file is scoped, not safe: biome reflows the
WHOLE file, and many files here are dirty at rest, so a two-line edit can land as a 600-line diff of
untouched code. Check git diff --numstat <file> after formatting; if the reflow dwarfs the edit,
restore the file and hand-match the surrounding style.
Prompts do not get the whole coach context. Every DATA: block is built by
promptData(ctx, "<site>") (src/prompt/context-projection.ts), a declarative per-site key
allowlist. getCoachContext() itself is untouched, so routes, MCP tools and the read-tool loop still
see everything — but adding a key there does NOT make it reach any prompt until you add it to that
site, and a new prompt registers a site rather than interpolating JSON.stringify(ctx) (which
silently restores a ~2× payload). Never trim by slicing the serialized string; that hands the agent
malformed JSON. And prompt builders and coaching ops import concrete src/repo/<module>.js, never
the src/repo.ts barrel (contract test) — the barrel is for routes and MCP.
dayRead()'s optional args each override only their OWN input — only unifiedState scopes the
whole signal state; omit it and the state builds RICH via dayPlanningSignalState(), the same builder
getCoachContext() uses, so the Brief and the coach prompt can no longer see different states.
Agent-authored headline/why are held to the deterministic vocabulary's own rules:
isValidDayReadAgentResult (src/dayread.ts) rejects them via violatesReadingGrammar()
(src/repo/day-read.ts) — leaked engineering vocabulary, a score, or gate language ("you must") fails.
Agentic endpoints return {ok:false, error, tried} at HTTP 200 — a designed failure signal, not
an HTTP error. And single-row ?date= / last-set lookups return 200 + null on absence, not
404, because the PWA's api() helper resolves to the body regardless of status, so a 404 error
object would read as a truthy hit.
Structured output is enforced where a src/coachOps/* call site passes RunOpts.schema; every other
op is prose-only. Every field a consumer READS must be named in the schema (an unnamed field is
silently dropped by constrained decoding, not preserved by additionalProperties: true), and a
schema is inert while streaming or for stub — the prose OUTPUT CONTRACT stays the floor
everywhere. Details: docs/ARCHITECTURE.md's "Enforced structured output" section.
A request memo serves only while nothing was written. requestMemo (src/repo/request-memo.ts)
dedupes pure reads inside one request (and, under 5 s old with no write, across back-to-back requests),
invalidated by SQLite's total_changes() and any ROLLBACK (so every rollback must go through db.exec); memoNeutralWrite
exempts two bookkeeping writes (a memory stamp, a queued week-ahead job). Never route a write a memoized read can see through it, and key a read
that consults a re-entrancy guard by that guard. Details: docs/ARCHITECTURE.md "HTTP caching".
Tests wipe the DB before every single test. test/run.mjs runs files off one longest-first queue
across workers (each with its own throwaway temp DATA_DIR/DB_PATH) and injects test/_isolate.mjs via --import — a root
beforeEach that wipes the whole DB. So correctness is independent of file order and shard count,
and a bare node --test invocation SKIPS that wipe. The suite is deterministic and offline: no agent
CLI, no network. The stub agent in agents.json is the offline smoke path for propose/apply. Each
worker also runs with its own agents.offline.json (AGENTS_CONFIG): every non-stub CLI's command
is rewritten to a nonexistent binary, so a real machine's installed CLIs are never probed or spawned by
a test that picks an agent.
When verifying by hand, prefer node test/run.mjs <files> (or npm run test:changed): it enforces per-file heap,
RSS and time budgets — see docs/OPERATIONS.md "Running tests". A run that skips it is still offline:
test/_offline.mjs (loaded by _isolate.mjs and _seed.js) fills an unset DATA_DIR/DB_PATH/
AGENTS_CONFIG with a throwaway dir and the offline agents table, and under node:test
src/dataDir.ts (every path under data/) / src/agents.ts themselves refuse the real data/ and
an unset AGENTS_CONFIG. Wait on the enrich
queue with whenEnrichQueueIdle() (src/enrich.ts), never a sleep. With bare node --test, run one file per invocation with its own mktemp -d. Passing several
files to a single node --test with one DB_PATH runs them as parallel child processes against
one SQLite file; the loser throws database is locked at the WAL pragma during module load and the
whole file reports failed with no test-level detail. That is a phantom, not a regression —
test/run.mjs avoids it by giving each worker its own temp dir and running files serially within a
worker.
Architecture: two protocol surfaces over one shared layer
REST endpoints are defined in the routers under src/routes/*.ts (src/api.ts only mounts
them). MCP tools are defined in src/surfaces/mcp/*.ts (src/mcp.ts only registers them).
Both call the same layer beneath: use-case services in src/domain/* and data/domain modules in
src/repo/* (barrelled by src/repo.ts), with prompt builders in src/prompt/* (barrelled by
src/prompt.ts) and client-facing DTOs in src/contracts/*. MCP ⊆ REST, near-mirror wrappers.
So: business logic belongs in domain/repo/prompt. Adding a capability usually means the
matching src/routes/* router AND src/surfaces/mcp/* module plus the underlying domain/repo
function — never api.ts/mcp.ts themselves, which are just registries.
Multi-step agentic operations both surfaces run (session-suggest, nutrition check-in, meal swap,
recipe, health review, insight generate) live in src/coachOps/* (shared, training, nutrition,
health, memory, barrelled by src/coachOps.ts) — each returns a plain {ok, …} a route wraps in
res.json(...) and an MCP tool in asText(...). Shared runChosen(agent, prompt): src/runChosen.ts.
Put new agentic orchestration in coachOps/*, not duplicated in the surfaces.
Generated, authoritative inventories: docs/API.md (endpoints) and docs/MCP-TOOLS.md
(tools), both from npm run docs:index. Subsystem depth — repo functions, prompt builders, chat
turns, streaming, art, scheduler, enrichment, PWA surfaces — is in docs/ARCHITECTURE.md.
The coaching loop (propose → apply)
src/prompt.ts builds a prompt embedding getCoachContext() plus a strict JSON output contract →
src/agents.ts runAgent() spawns an external CLI subprocess (Claude Code, Codex, Antigravity,
Grok, or stub) defined in agents.json, and extractJson() pulls the JSON out of stdout → the
result is stored as a draft row (plan_proposals / meal_plans). An agent never applies its
own change. applyProposal() walks parsed.changes[] via updateTarget() and refuses to re-apply
an already-applied proposal; a parsed.days payload instead routes to replacePlan(), and a
kind:'nutrition_target' payload is advisory (acknowledgement only, no plan to mutate).
The CLIs are autonomous agents; Cairn's prompts are not tasks. Every spawn goes through
applyToolPolicy (src/agents.ts), which leads the prompt with NO_TOOLS_PREAMBLE unless the prompt
hands the CLI uploaded files or the call site passed tools:"provider" (research, a current-research
chat turn). Without it grok explores its cwd with tools until the timeout and agy trips a headless
permission auto-deny (agy now also carries an explicit command(*) deny). Opt an op into provider tools
at its call site, never by softening the preamble. Chat alone uses a third policy, tools:"coach_reads";
which CLI reads natively vs. by prompt loop is agents.json config, never a name check
(docs/ARCHITECTURE.md "Tool policy" and "Coach read transports").
Autonomy is server policy, not model discretion (Amendment 1 in docs/VISION.md).
decideAutonomyTier() (src/brain/autonomy.ts, driven by settings.lead_mode) picks among observe
/ quiet_apply / announce / ask / clinician; bounded reversible changes land at natural boundaries,
structural ones announce, goal-identity and anything clinical always ask. Every material decision is
recorded in brain_decisions with falsifiable expectations and server-owned one-tap Undo. The
clinician floor is deterministic IN BOTH DIRECTIONS — a conductor cannot self-attest it away, and
cannot self-attest INTO it either (clinicianFloorHolds, src/brain/autonomy.ts: a specialist's
autonomy_ceiling:'clinician' or a conductor's risk_class:'clinical' over a non-clinical change
tightens to an ask at most). An act-now health finding gates only a revision that acts on what it
governs — same domain and named area, or the revision names the marker (clinicalAutonomyFromRevision,
src/domain/brain/conference-conflicts.ts) — so a lipid finding never clinician-gates a squat hold.
An unresolved SAFETY conflict is held to the same relevance (safetyConflictGovernsRevision): food and
medication questions hold nutrition changes only, and a protective load reduction is never held by
injury_load.
See docs/ELITE-BRAIN-IMPLEMENTATION.md.
Agent selection. Callers name an agent or pass agent:"auto" / omit it. Auto uses
repo.pickAgentOrder() (strategy in settings: round_robin default / random / priority) and
agents.runAgentWithFallback(), which tries agents in order until one returns parseable JSON — so a
dead CLI login or timeout falls through transparently. agents.json defines each backend (command,
args, input mode, env); which are enabled/ordered and the strategy live in settings, editable at
runtime with no redeploy. Health ingestion deliberately opts out of the rotation (see
docs/ARCHITECTURE.md).
Effort is server policy; the model is the CLI's own unless the person picks one. TASK_POLICY in
src/repo/settings.ts picks which agent runs an op; its sibling TASK_EXECUTION_PROFILES picks
how — a provider-neutral class (fast/deep) and an effort, keyed by the same taskForOp class.
A class names NO model by default, so no --model is passed and each CLI runs what its plan gives it;
only a person's binding in Settings → Agents ("Everyday" = fast, "Deep work" = deep,
settings.model_class_bindings) adds one, for ops AND chat (each chat lane maps to a class;
chat_profile_bindings is the advanced per-lane override that wins). The choices are the CLI's live
catalog (models_list) else agents.json model_choices aliases, plus validated free text; a model
the account can't use falls back to the CLI default (src/agentModelPins.ts). Resolution happens once
at spawn time through RunOpts.profile (resolveTaskExecutionProfile), so runChosen callers need no
per-call-site wiring, and the interactive timeout scales with the requested effort. Never pin a dated
model ID, and never ship a model pin for everyone. Details: docs/ARCHITECTURE.md "Agent execution
profiles".
Chat is a durable, non-blocking turn, not a request/response: POST /api/chat enqueues and
returns immediately; a serial worker runs it, streaming token deltas over SSE when the agent supports
it. The reply is prose-first — the model writes ===CAIRN_REPLY===, the athlete-facing prose, then
optionally ===CAIRN_ACTIONS=== + {"actions":[…]}. Everything before the reply marker is dropped
(autonomous CLIs narrate their tool steps as text, which must never reach the bubble). Details:
docs/ARCHITECTURE.md, src/chatTurns.ts.
Domain gotchas
- A held draft's dead premise retires it, never re-asks it. A swap/removal draft whose target
movement has left the plan is retired (
retire_reason:"premise_gone") byretireDraftsWithDeadPremise()ahead of the thaw/adoption loop — ungated bylead_mode. Details indocs/ARCHITECTURE.md. - Weight encoding: negative
weight/target_weight= assisted movement (-30= 30 lb assist);null= bodyweight. The PWA and prompts rely on this. - Timed exercises (
exercises.mode = 'timed'): sets logduration_sec(reps null), plans prescribetarget_seconds; a loaded carry/hold also carries a weight — seconds progress to a ceiling first, then one load step with the seconds reset, never both (docs/ARCHITECTURE.md"Loaded timed work"). A timed item never takes reps. A mobility item never carries a load target or an RIR; what a log row asks for (and "/ side") isexerciseInputFor(),src/repo/exercise-input.ts. - Est-1RM is Epley on the best set per day.
- Sensor age and acute muscle fatigue each have exactly one source of truth:
src/repo/sensor-freshness.ts(a stale wearable reading behaves as absent, never as current) andhybrid-load.ts'sacuteGate()(the one "is this muscle recovering" question — call it, never re-derive a window). Details indocs/ARCHITECTURE.md. - "Last night" is the night dated the READ DAY;
d-1is trend only. Sleep rows are dated by the WAKE day, so a row datedd-1is the night before last. Every one-night claim —signals.last_night, the "Last night's sleep" evidence row, the acute short-night rule, the push-drive wearable path, thesleep_night_*observation,sleepDebtRead's short-night arm — gates onLAST_NIGHT_MAX_AGE_DAYS= 0 /isLastNight()(src/repo/sensor-freshness.ts). The WINDOW claims (avg_sleep_min,sleep_trend, the chronic-sleep watch and its "a recent night exists" anchor) keepSENSOR_MAX_AGE_DAYS.sleep= 2. A morning with no night of its own says nothing about sleep — never a night before last wearing last night's words. One READINESS reading is the same law (isReadDayReadiness): ad-1row is yesterday's post-workout last sync. HRV and resting HR exist only on worn nights, so their caution BRAKES only when its reading is last night's; an older one rides as context (advice_only,signal-state.ts). A REST decision reads HRV only as a rolling value (rollingBandRead,src/repo/overnight-band.ts); one night stays harm's. - Logged intake is evidence only when the day reads complete —
classifyIntakeDay(src/repo/intake-window.ts) is the one credibility rule: a morning→evening span carrying at leastSPANNING_DAY_MIN_KCAL, or, when NOTHING on the day could be placed in time, a whole day declared at once (UNPLACEABLE_DAY_MIN_KCALof untimed calories — one placed meal disqualifies that arm). A partial or unlogged day is ABSENT, never "low". Never infer under-eating from missing logs; and during an affirmed cut a protective raise stops at measured maintenance (capProtectiveRaise,src/repo/cut-target.ts) — protection buys maintenance, never a surplus, and aformula_estimateanchor is not a measurement, so it can only ever hold the target. - A trip is a confounder, and rest already taken is the recovery dose. A subdued
sleep_feel/sorenessdated inside atripcontext event never proves fuel persistence (travelWindowDates,src/repo/underfueling.ts— recorded as…:travel-confounded, never silently dropped), andREST_SPAN_CREDIT_DAYS= 3 untrained days ending yesterday cap the recovery package's training consequence athold_aggression(the calorie step stands; the control loop mints a recovery WEEK only when the read saysreduce). The quiet-day escalation voice breaks its streak on a trip day. - Sessions are keyed by date —
getOrCreateSessionreuses today's session, so logged sets accumulate into one session per day. - Stated run days are structured and anchor the run engine —
endurance_schedule(profile.endurance_schedule_json) is the athlete's named weekdays for easy/quality/long runs;weeklyRunPlanandflexibleTrainingAgendahonor those dows and never spill a suggestion onto an unscheduled day. A named day still fires when the hard session sits out — it becomes easy; the supporting-constrained drop to two runs applies only with no stated calendar. A logged run on an unscheduled day still counts (the log is truth). A one-week move lives inendurance_schedule.week_moves, never the standingdays[]: read the week in force withgetEnduranceSchedule(asOf), the usual week withgetStandingEnduranceSchedule()(docs/ARCHITECTURE.md"One-week run move"). A moved key run is still the planned run: which run was the quality/long one is the week's completion (closedRunIntentOn/weekRunClosures, the agenda's one matcher, cycle-free — never call weeklyRunPlan/agenda/harm from it), never the raw weekday. A recurring non-run day isendurance_schedule.cross_training(never indays[]), else the observed 2-of-6-weeks pattern (crossTrainingDays,src/repo/cross-training-day.ts). Stated LIFTING weekdays are the same fact for strength —strength_schedule(profile.strength_schedule_json,{days:[{dow}]}, nokind): when set,weekdayPlanDayMap(src/repo/plan-selection.ts) lays the plan's strength days onto exactly those weekdays and an unstated weekday never gets one;week_layout.lift_days/run_daysand the prompt's STATED LIFTING DAYS line are how the agent checks itself. The map OUTRANKS the session anchor —selectAdaptivePlanDayconsults it FIRST and the last logged session only sets the ring's phase (consulted after, it is inert: an anchor always resolves for an athlete with history), and plan-day count need not equal lift-day count — a short strength pool repeats inside the week so every named weekday still lifts, a surplus rotates across weeks onto the named weekdays only, and the scorer then adapts among strength days alone. Never said is not the end of it —strengthScheduleRead()(src/repo/strength-schedule.ts) falls back to the weekdays a real strength session landed on in 3 of the last 6 weeks, labelledsource:"observed"everywhere it is spoken; an explicitly EMPTIED stated schedule stays silent rather than reopening the log. Chat is the only setter UI — there is no settings form, by design. - The race build is a read OVER the run engine, never a second engine —
raceBuild()(src/repo/race-build.ts) walksraceRamp()Monday by Monday for the ladder, so a week's km is always the engine's own next step; itskindfollows the engine's arrival count in CALENDAR weeks to race week (weeks_to_race_week: peak → taper → race, never peak into race week). A reset is recovery, not lost ground, and a long run taken well is held, never re-climbed to (RESET_TAKEN_FRACTION,demonstratedLongKm). Demonstrated capacity is the floor and the peak is a new high: the best harm-free closed week of the last 8 (demonstratedRunCapacity,src/repo/run-capacity.ts— harm isharmEvidenceOnDay(date, {domain:"running"}), never re-derived: a lifting session rated under par never voids a running week) sets the ramp's peak target one ~10% step past it and a lighter week resumes toward it inside the ACWR ceiling (capacityResumeKm); a harmed week falls back, never pushed through (the reset resume takes the same guard) — unless a LATER stated key run that week was taken clean (nextMorningClean: the body answered). A set-aside week is SAID on the plan (capacitySetAsideLine, race buildcapacity.note). The week's prescription is a property of the WEEK: a spike in the CLOSED week holds every morning of it (spikingreads the volume anchor too), so no as-of date re-plans it. Finish estimates prefer the watch's predictor (≤3 weeks old, Riegel-adjusted) over a Riegel off a training run, and every comparison is afits/stretch/beyond_horizonFIT, never a grade. The weekly ride (ride, any non-run family) is the cross-training day: stated first, else observed (2 of 6 weeks); a known one the day before the long run never strips the long run's date. A finished race's lessons reach the next build only as bounded levers (src/repo/build-levers.ts): resolved once and handed toraceRampby BOTHweeklyRunPlanand the ladder — never read a ramp constant past them. Details indocs/ARCHITECTURE.md(and "Build levers (lessons from the last race)"). - The days after a race are ONE read, and the race is never training —
raceRecoveryWindow()(src/repo/race-recovery.ts: 2 / 4 / 7 days by distance from race day + 1) is the only source of the post-race window; it lightens through the stress budget's ordinaryreducedlist (post_race_recovery, every group, nothing excluded) and easy-only runs, never a rest of its own. The race is its logged EFFORT (a run within 2 days of the goal date at ≥85% of its distance,src/repo/race-results.ts), never the goal slot, and it outlives the goal:setProfilekeeps an outgoing race incompleted_races, so a new goal set on race + 1 keeps the window. No effort logged → no window (past a 2-day slow-sync grace) and nothing blanked. That day's runs are not demonstrated capacity, not the long-run ladder, and not harm; the weeks the window touched resume toward the PRE-race floor (preRaceRunCapacity). Details indocs/ARCHITECTURE.md"The days after a race". - Today's lift has ONE server line —
todayStrengthLine()(src/repo/today-strength-line.ts): plan day NAME, state off the log, a rest/easy read as a caveat (never a replacement title). The Brief, Session header, week strip and Train overview print it verbatim; never derive a today state in a renderer. Details indocs/ARCHITECTURE.md. A logged session's name has ONE resolver,loggedSessionDay()(src/repo/session-day.ts): the log decides, never a plan-day row renamed by a later redraw, and dated surfaces show plan-day names throughplanDayDisplayName(no week-count claims). - Plan days hold STRENGTH only; runs and rest are the calendar's (migration 110). A run is never a
plan item (
savePlanDaystrips it,replacePlandrops a day with nothing to lift) and a rest day is never a plan row (day_type:'rest'is refused). Runs come from the stated run days +weeklyRunPlan/ the agenda; a non-lifting weekday is a run or rest day (calendarDayRead, plan-selection) andselectAdaptivePlanDayanswers it withday_number:null. An empty editor scaffold is never startable. Details indocs/ARCHITECTURE.md. - No logged activity is ever dose 0, and none needs a modality of its own. An unmapped Garmin type
gets a family guess off its type key (
activityLoadFamily,src/repo/endurance-sports.ts: paddle, court, snow, combat, else a light whole-body read) — extend the family table, never add a one-sport branch. The whole week across every sport is ONE read,weekTrainingLoad(src/repo/week-training-load.ts), a read over reads. Details:docs/ARCHITECTURE.md"Every logged activity is a dose". - Garmin strength is a session, not an activity.
upsertGarminActivitydeliberately skips the genericactivitiesrow for a strength type (no duplicate).reconcileGarminStrength()does the deterministic merge (physiology ontosessions.garmin_json, link, delete stale row) always, even with no agent; the narrative + missing-exercise logging is the agentic layer on the enrichment queue, guarded so hand-logged sets are never overwritten and re-syncs stay idempotent. Strength also travels OUT: a finished Cairn session is written back as that day's Garmin exercise sets (src/garminExport.ts, non-agenticgarmin_exportenrich kind, FIT enums fromsrc/repo/garmin-exercise-map.ts— never invented), onto the watch's own activity when there is one; a Garmin-owned day (cairn_sets_authoritative === false) stays inbound-only. A shell Cairn creates carries Cairn's OWN calorie estimate, sogarmin_daily_metrics.active_calories/total_caloriesare stored NET of Cairn's shells (cairn_shell_kcal,src/repo/garmin-shell-energy.ts) — our estimate must never reach Cairn's TDEE. Seedocs/GARMIN.md. - Autoregulation feedback (
sessions.soreness/performance/joint_pain) and subjectivecheckinsare optional signals that INFORM coach selection — they never override progressive overload, never auto-change the plan, and their absence never forces a rest read. A completed log outranks a felt rating, PER LIFT:sessionLogContradictsLowRating(src/repo/session-dose-log.ts) is a majority test — lifts met/exceeded must at least match the ones that fell short (a skip counts short), an incomplete log additionally needs ≥1 lift genuinelyexceeded, and any lift that landed under its own stored full-load reference kills the contradiction outright whatever the counts say. A lowfelt_fatigueconstraint this earns closes early (within its 7-day window) the moment a later completed session contradicts it too (autoregBrake,src/repo/progression.ts). Readiness bands live insrc/repo/readiness-bands.ts(LOW_READINESS35 = subdued/easy;REST_GRADE_READINESS20 inclusive = never rest on its own: easy, or the dose on a stated day, as is the low band —src/repo/morning-dose.ts; the score alone never trims whole-session volume,readiness_brake_only) — never hardcode a readiness threshold. AndtrainedWithoutHarmisharmEvidenceOnDay(date) == null: a hard-cardio day, a new-longest run (longestRunNovelty), or a bad next morning (rest-grade readiness, or last night's HRV/RHR MEANINGFULLY past the athlete's OWN band — by the smallest worthwhile change, or on two consecutive readings; a lone hair-past night is a caveat,src/repo/overnight-band.ts, shared with the run morning's floor — charged once per episode, at onset) is harm — a run-only day is never "unrated therefore fine", but a hard-cardio day is never one the athlete STATED easy (activities.rpe≤ 4,src/repo/stated-effort.ts— the watch's effect/zones/load do not overrule their word; the next morning still does), a RUN with HR and a usable personal model is graded by that model and his own session title, never by training effect /te_label/ Garmin zones / load (personalRunRead,src/repo/run-intensity.ts— the harm bar, the day grade and hybrid-load's per-muscle dose all ask it; length still makes a long run a heavy leg dose, and "long" is 1.5× his own six-week median run, never easier than the fixed bar —runLengthBars), and is CLEARED when the next morning positively vouches (fresh readiness ≥SUPPORTIVE_READINESSand no brake firing; absent data never vouches). "Morning readiness" comes from the ledger's own snapshot for that morning, else the watch's own wake-up reading (watchWakeReadiness: the raw payload'sAFTER_WAKEUP_RESETstamped before the first training — but a no-sleep reading whose low score is driven by the recovery-time factor restates the prior workout's load and is never harm evidence against it,wakeReadingRestatesLoad; it may still vouch), since the stored Garmin value is the day's LAST sync and so is post-workout on any day the athlete trained — the run engine's default recovery read goes through the samewithMorningReadiness; the morning read itself is the last predictivebrain_decisionsrow before the first logged training of the date, never the midnight recompute. Check-inenergy/sleep_feelstill brake at ≤2 and support at ≥4, but a3is genuinely NEUTRAL (it still emits an observation, so a tapped-in athlete never reads as untracked) — never round it to a brake or a support vote. A tap alone eases, it never rests: a felt brake takes the whole day only with an objective witness about the same 24 hours (FELT_REST_CORROBORATION,signal-state.ts), and a poor sleep-feel beside an energy ≥4 tap is an advisory caveat (sleep_feel_mixed); a good tap lifts a readiness-only easy read one step, held (checkin_lifted_train). Details indocs/ARCHITECTURE.md"A check-in tap is slight input". Chat can write the same check-in via thelog_checkinaction (src/chatActions.ts), 1–5 scales only, and a free-text note there is routed through symptom capture only when the athlete's own words carry symptom intent — never automatically. - Deload-due is earned by loaded weeks and a log-confirmed shortfall, never the calendar.
classifyLoadedWeeks(src/repo/program-state.ts, feeding themesocyclestate) classifies a week as loaded only against the median of the loaded weeks before it; a light week breaks the streak.deload-duecomes only from a six-week loaded streak, or four weeks plus a shortfall the log confirms plus physiology — never from a weeks-since count. Ratings and notes are supporting copy; an applied recovery week only resets the count; a block in weeks 1–2 or its own deload/realization phase never reads deload-due — and for a push-drive athlete a block's scheduled last-week deload holds nothing unless that loaded-weeks evidence earns it (scheduled_deload) — every surface that names the week reads ONE resolution (src/repo/block-phase.ts), and a fresh block after such a skip does not hide a deload the loaded weeks call for. - Assist is a sign, and the sign is guarded at log time. A positive weight typed onto a
negative-history lift within 1.5× the recent assist band is stored negative (
assistSignContext,src/repo/sessions.ts; Garmin imports opt out). An exercise's NAME is never a sign — only its history is.recentWorkingWeightranks less assist and more reps as harder. - The daily envelope's up direction is
reach, a separate field — never a sixth posture.SignalPostureis a five-value safety ladder.reach.level='push'licenses ONE challenge top set (up toMAX_REACH_HOSTSunder an open, harm-free push stance, each on a different movement pattern) on the first eligible compound (src/repo/daily-composition.ts), computed from the LOGGED working weight, never a plan target, and only on a lift the progression engine is moving and did recently; composition reports back so the persisted envelope never promises a reach that is not on a card.item.reachpersists only for server-derived items. A hold keeps the progression's own target, never an older log, andearned_flooris the only composition raise — seedocs/ARCHITECTURE.md"Composition never moves the prescription". - On a STATED key-run or lifting day a soft brake is the dose, never the kind — the read stays
train(stated_key_run_dosed/stated_lift_dosed); every floor (calendarDoseFloor) keeps the quiet read, and a learned tolerance can only hand it back. REST is reserved: a low readiness reading (either band) is the same dose on a stated day (stated_*_morning_dosed), easy elsewhere; one short night or one low HRV night after hard endurance is the dose on any day with a session due; RHR up after a hard day is easy at most on every day, and RHR rests only on vouched readings on an established band; the rule table and every tunable areMORNING_DOSE_POLICY(src/repo/morning-dose.ts); race morning is the race's identity by DATE (goalRaceOn) whatever floor applies — a floor is said plainly in its own code, no lifting card. Every variant set is keyed on the fact its sentences assert. The day-read verdict judges only the true morning read, and harm there can beunknown(harmVerdictOnDay— never clean, never a cost;harmEvidenceOnDayitself is unchanged). Details:docs/ARCHITECTURE.md"The calendar owns what the day is for" and "The measurement fixes of 2026-10-16". - Consecutive loading days are a caveat, never a brake of their own —
daily_decision_v7,src/repo/day-read.ts/daily-decision.ts. Details indocs/ARCHITECTURE.md. - The rest trade is carried by the CALENDAR; the ring is never touched —
tradeRestDay,src/domain/brain/rest-trade.ts. Details indocs/ARCHITECTURE.md. - Day-read prose is a variant set, never one literal. A stable input fires a stable rule every
morning, so a single sentence per rule printed verbatim for weeks. Rules carry their own athlete-
facing
reasons(src/repo/brain/day-read-rules.ts), and every athlete-facing string — outcome reason, the read'swhy, the server-policy clamp reason — rotates throughpickDayVariant(date). Add a phrasing to the set; do not add a literal. Details indocs/ARCHITECTURE.md. - ONE WORDING PER MORNING PER IDENTITY. The read's identity is
dayReadProseIdentity(date, baseline)—(date, kind, decision.rule_code, focus), always from the DETERMINISTIC baseline, persisted asprose_identity. A recompute landing on the same identity keeps the cachedheadline/whyand refreshes onlysignals/input_fingerprint/computed_at(pinnedDayReadProse, above the agent call incomputeDayRead); the agent is asked only on an identity change, the athlete's explicit new read, or floor prose (the self-heal path). A bareinput_fingerprintmove is NOT material truth inreadToday— every sync moves it — and the 04:00 precompute warms the floor only (precomputeDayReadFloor) until a sleep row is dated that day, so no sentence is written about a night that has not synced.invalidateDayReadmarks an agent row STALE, it does not delete it —getCachedDayRead(date)hides a stale row, only the reconciling paths pass{ includeStale: true };discardDayReadis the real delete (reset, a cleared directive). A cache-miss open serves the floor and never awaits an agent. Details indocs/ARCHITECTURE.md. - Any surface a PERSON reads goes through
spokenSignalVoice;summary/reasonare the machine register.SignalObservation.summaryand every dimensionreason(src/repo/signal-state.ts) are third-person evidence prose forrenderSignalState, the coach context and the provenance trail. The Brief'swhyAND the coaching-focus conductor's lead/parallel cards both speak throughspokenSignalVoice(ref, date, key)instead — fix a voice problem there, never by rewritingsummary/reasonin place (that would silently change what the model is shown). Details indocs/ARCHITECTURE.md. - Body fat has ONE estimate —
bodyFatEstimate()(src/repo/body-fat-estimate.ts): every source in one error table (DEXA anchor, calibrated tape, scale = direction only), a range; display reads the central value, anything protective (loss-rate caps, cut planning) readslowviaprotectiveBodyFatPct(fallback included); a milestone/goal/percentile needsmeasured. Never read a raw tape/scale/DEXA number as "the" body fat. - Optimal-zone ≠ lab range.
OPTIMAL_ZONESare evidence-anchored longevity target bands, which is not the lab's population reference interval — a value can read "in range" yet sit far from optimal.prioritizeMarkers()ranks by an INTERNALimpact_score; never surface that number. The UI shows in/out-of-optimal and direction only. - One panel per draw date. The same lab draw arrives more than once (a PDF and a zip of one
export, a re-export, the CCDA pass and the agent reading one import).
dedupeHealthDocuments()(src/repo/health-dedupe.ts) folds records on the same date whose shared readings AGREE into one survivor (source row > deterministic read > fullest), scoped to the upload after every ingest and whole-record viaPOST /api/health-docs/dedupe/dedupe_health_records(a dry run unlessapply:true). Evidence must be discriminating — a shared weight/BMI/pulse never makes a match; records that merely share a date, or whose readings disagree, stay apart. Free-text observation rows ("Lab Interpretation") are never markers (isNonAnalyteMarkerName). Every creation path settles through ONE chokepoint,settleNewHealthRecords(src/domain/health/record-dedupe.ts) — a new path must call it; a same-encounter CCDA pair from two exports folds with the later export winning (superseded_readingskeeps the loser), an imaging near-twin folds only on a remembered high-confidence agent verdict, and bumpingDEDUPE_RULES_VERSIONre-folds the whole set once at boot. A fold never loses content: a twin another upload still carries is re-filed when the survivor's upload goes (restoreOrphanedTwins), and a source upload is deleted only when an equivalent copy stays. - Marker grouping:
MARKER_GROUPS(insrc/repo/propagation-data.ts) matches longest-first, and its array order is the display order — conventional clinical lab-review order, mirrored by the doctor export and the in-app catalog. Full ordering rules and the non-clinical-marker filter live indocs/ARCHITECTURE.md. - Marker staleness is per-class, not one number —
src/repo/marker-validity.ts; extend the table there, never hardcode an age threshold. Details indocs/ARCHITECTURE.md. - Directives never change anything by themselves. A flagged marker propagates into
health_directivesviaderiveDirectives(); sources'markers'(deterministic) and'health_review'(agent-emitted) coexist and each clears/rewrites only its own rows. One exception to the churn-free diff reconcile: a materially-WORSE trigger from a strictly newer draw resurfaces its directive as a fresh row (resurfaceWorseningDirectives,resurfaced_from_id) — news gets a row, never an invisible in-place edit. Directives are informational, not medical advice;uncertain/uncited ones are a softer nudge. The user flipsactive|resolved|dismissed— but a Done on a finding whose reading still stands is an ACKNOWLEDGEMENT, not a cure: it stays in effect for coaching (acknowledged, off the to-do surfaces) until a newer reading no longer calls for it; only a Dismiss suppresses. Details indocs/ARCHITECTURE.md"The connected brain". - A painless structural condition is a movement consideration, never an injury.
profile.movement_considerations_jsonshapes plan prompts only; filing "mild scoliosis" as aninjuryevent hard-gates the main lifts forever. Nothing protective may read it. Details indocs/ARCHITECTURE.md. - Pain is REPORTED IN WORDS; the mini-UIs are gone on purpose.
training_symptom_events.area_textis a short display LABEL (pain-relevance runs substring regexes over it, so a paragraph there loads every lift) — the athlete's actual sentence lives verbatim insymptom_reports.text, written synchronously before anything is derived. Structure comes from ONE contract,src/symptomCapture.ts(mirrorsfoodCapture.ts), applied only through the existing lifecycle writers.scope='systemic'never drives movement relevance;evidence='inferred'(a quiet exposure read off a logged set at session finish) refreshesfreshnessbut neverstated_freshness— readstated_freshnessfor anything about acuity or outcome comparability. Details indocs/ARCHITECTURE.md. - Food capture has ONE contract and ONE direction of time inference.
src/foodCapture.tsowns the meal-estimate shape (ingredient rows with the quantity as a field,nutrition_patternbands,confidence/basisprovenance) for chat, note enrichment and the photo read alike — extend it there, never re-declare the JSON in another prompt. A stated time may infer an unstated meal label (21:00 → dinner); the reverse must never happen.eaten_atis rendered to the athlete, so a time synthesized from a label would be indistinguishable from one they actually said — the label's hour orders a day at read time only, and is never stored. - Dose comparability is a per-lift question, not a per-session one —
dose_evidence/dose_context.comparable(progression.ts), andtraining_drive='push''s bounded mechanical authority. Details indocs/ARCHITECTURE.md. - A card composed from the athlete's own plan day never SILENTLY loses work — the day's set
budget (and an explicit time request) trims sets largest-first to two a compound and one an
accessory (
day_set_budget), then defers the lowest-priority accessories (day_set_budget_deferred, named on the card in one line), always recorded (fitPlanDaySetBudget); the item cap drops nothing, and the title is the plan day's name, never its focus prose. A today-scoped change the athlete asked for rides the envelope asrequest.same_day_requestand keeps its sets under train-anyway. Details:docs/ARCHITECTURE.md"The athlete's own plan day never silently loses work". - Work done is evidence — a prescription is a suggestion, the log is the truth —
performed_at_full_load(src/repo/outcome-comparability.ts). Intensity earns the load, the set count earns volume: one set short with every working set past the top still steps (cappedShortOfSets). Details indocs/ARCHITECTURE.md. - Cut pressure has three shapes, and only two veto an earned promotion —
CutPressure(progression.ts):holdnever vetoes,reducevetoes unlessnear_goal,slidingalways vetoes,fast_lossnever vetoes a load step. Details indocs/ARCHITECTURE.md. - RIR is optional, and its absence is not weakness — with no RIR logged, capping the prescribed
rep range on every working set IS the strength signal (
program-state.ts/progression-voice.ts). Details indocs/ARCHITECTURE.md. - When a slot was prescribed has one source —
src/repo/prescription-authorship.tsstamps every plan write and answers fresh/untested/since for every consumer; never re-derive it. An untested slot holds at the plan — unless its latest exposure already lifted it at the written load and full set count (testedSlotAuthorship, the one reading the prescription, program-state and set catch-up share). Details indocs/ARCHITECTURE.md"Prescription authorship". - Weekly volume has a contextual floor and the log is truth for set count —
volume-floor.ts(muscle/strength intent only; endurance-carried groups and light weeks exempt), held by plan quality, the redraw precheck andsetCatchUp. Details indocs/ARCHITECTURE.md. - On a train read the plan's sets are the default —
caps.volumetrims only for a named, current reason (namedVolumeReason; a read's held dose is not one); a standing preference never trims, and a precautionary trim yields to a log that carried every AUTHORED set at a held-or-rising load (volume-tolerance.ts, judged on performance, never on absent complaints). Learning never adds a set: any catch-up honoursVOLUME_BOUNDS(~1.2× the habit of the weeks before, ~20 weekly sets a group) and an affirmed cut holds the count. Details indocs/ARCHITECTURE.md"Volume: the plan's sets are the default". - The weekly dose fills a group's shortfall with one extra set — never a load, never an untested
slot, never the day's anchor or strength-range work.
weekly-dose-ledger.ts/composition-dose.ts. Movement REGIONS (movement-region.ts), not raw muscle group, decide which items collapse as duplicates and pair as antagonist supersets on today's card (composition-pairing.ts). Every source's supersets pass ONE gate,enforceSupersetRules: two lifts a group, one fixed station a pair (station-footprint.ts; a name ambiguous between a machine and a free weight is unknown, the server never proposes a pair with an unknown member, and unknown never splits an authored one), three pairs a session. Lifts the athlete asked for today are never deferred or trimmed on any card, and a card that deferred plan lifts never vouches for the plan's volume. Details indocs/ARCHITECTURE.md"Weekly dose ledger" and "Pairing and movement regions". - A race build's taper/race week and the eve of a placed key run trim the legs through the ordinary
reduced/excludedmuscle lists, never a second gate (stress-budget.ts); for a strength-led athlete that is the race's ONLY lifting change — everything else keeps progressing (one source,src/repo/race-strength.ts) — and a coarse-stepped isolation grind (or an earned step past too big a jump) moves up a rep range at the held load exactly once, remembered on the applied-proposal ledger (lift-response.ts). Details indocs/ARCHITECTURE.md"Run/lift stress budget" and "Selection by response". - Exercise names are resolved through
resolveExerciseName(src/repo/exercise-canon.ts); never compare rawexercises.name. One ladder (exact → one alias hop → key → a unique expanded key), read by every consumer AND by thefindOrCreateExercisewrite chokepoint, so a spelling can never split one lift into two histories. Itskeyis the persistedmovement_keyshape — never widen it. A stored name is retitled only throughrenameExercise: casing lands everywhere at once, a same-lift respelling may land from an agent, a rewording is PARKED onsuggested_namefor a person's yes/no (never dropped, never forced), and "keep" is remembered onrefused_name. Details indocs/ARCHITECTURE.md"Exercise identity: one resolver". - The exercise-guide matcher only auto-links a UNIQUE hit; an implement-only match instead parks
as a suggestion for a human yes/no, and a hand-confirmed link or refusal both survive re-import.
Details in
docs/ARCHITECTURE.md. - The session/meal-plan verify pass's numeric floors are computed server-side, not asked of a
model.
src/repo/verify-floors.tsprecheck WINS over an agentok:true— a breach it still finds isunresolvedon the outcome, never shipped as clean — and the agent turn is skipped entirely when nothing needs judgement. Details indocs/ARCHITECTURE.md.
Product constraints (enforced in prompts AND UI)
- The Brief and every read is a suggestion, never a gate or verdict — the athlete drives.
- No numeric scores anywhere. No 0-100 grades, no metric walls.
- Insights and the weekly read are pull, never push — they wait in-app, never notify or nag. The
generator emits ONE genuine connection or
{found:false}, deduped against what it already said. - Adaptive nutrition is adherence-neutral: a thin logging week lowers confidence, never blames.
change:falseis the calm, common answer. - Health findings are informational, never medical advice.
Security posture
Single-user, trusted-network by default: no authentication unless CAIRN_AUTH_TOKEN is set, in
which case one global guard in src/auth.ts gates /api and /mcp, exempting only /api/health
(any method), GET /api/apple-health/config, POST /api/apple-health/pairing/exchange, and the
POST sign-in doors in SIGN_IN_DOORS — plus the static PWA shell, which stays ungated so it can
render the sign-in screen. API/MCP clients send the master token (Authorization: Bearer); a
browser signs in once (passkey, one-time #pair= code, or the token as recovery) and then carries
an HttpOnly per-device cairn_session cookie whose cookie-authenticated writes must be same-origin.
AI apps get their own /mcp-only access — a per-app key, or OAuth 2.1 + PKCE through the public
/.well-known/oauth-* and /oauth/* doors (src/routes/oauth.ts, outside the guard's scope,
per-IP limited); none of it ever opens /api.
Only hashes of session secrets, pairing codes, MCP keys and OAuth codes/tokens are stored, and none
of them — nor the token — may reach a log (the one exception: the boot's first-sign-in line).
Details: docs/ARCHITECTURE.md "Access: master token, device sessions, passkeys". An optional per-IP rate limiter
(CAIRN_RATE_LIMIT) is wired before the auth guard so it also blunts token brute-force. Uploads
land in data/uploads/ behind a raster-image/PDF mime allowlist (no SVG), and the 25 MB body limit is
scoped to the health-doc upload route only (1 MB elsewhere). The container runs as non-root app, so
one-off docker compose exec commands that must persist a CLI login need -u app.
Docs map
| Doc | What it holds |
docs/VISION.md | The constitution. Read before shaping product behavior. |
docs/ARCHITECTURE.md | Subsystem depth: repo layer, prompts, chat/streaming, art, scheduler, enrichment, PWA surfaces. |
docs/API.md · docs/MCP-TOOLS.md | Generated, authoritative endpoint and tool inventories. |
docs/DESIGN.md | The "Atelier v2" visual contract — tokens (light + dark), type, stones, components, motion, stylesheet ownership, and the client component architecture. Read before touching src/styles/ or view markup. |
docs/OPERATIONS.md | Deploy, migrate, backup, restore, tooling notes. |
docs/HOSTING.md | One-click hosted install (Railway), single-volume mode, RAM sizing. |
docs/ELITE-BRAIN-IMPLEMENTATION.md | The decision ledger, evaluators, autonomy tiers. |
docs/ARCHITECTURE-HISTORY.md | Append-only per-round schema/feature changelog. |
docs/ (rest) | User-facing guides — quickstart, deployment, Garmin, Apple Health, households, sharing, sandbox, observability. |
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

