PRODUCTION SYSTEM · OPERATED SINCE MARCH 2026 · LAST PIPELINE RUN 2026-06-09 (TODAY)

A self-calibrating multi-agent system that plans my training, meals, and seizure-risk forecast every week.

Nine Claude Code agents coordinated through shared state, a two-tier memory architecture, and a three-tier autonomy framework. Built around a real constraint: I had brain surgery two years ago, and the variables that drive my seizure risk — sleep, strain, alcohol, travel, stress — are exactly the variables a closed-loop agent system can forecast and plan around.

9
agents — 1 master orchestrator + 8 pipeline & governance skills
7
parallel subagents dispatched by whoop-report alone (1 Haiku, 6 Sonnet)
2
memory tiers — Anthropic managed memory store + local JSON fallback
3
autonomy tiers governing every action: Autonomous / Surface / Halt
167
days of Whoop biometrics in the current analysis window (Dec 25 → Jun 9)
79
days of 12-signal journal data in neurologist-signals.json
5
pipelines writing to shared state: optimize_week, gordon_ramsay, neurologist_agent, whoop_report, calendar
2
frozen baseline snapshots in the managed store (May 24, Jun 9) for month-over-month diffing

live system state

What pipeline-state.json says right now — verbatim

last_updated: 2026-06-09T14:22:52Z  ·  source: Personal/Health/pipeline-state.json — open it and it will match this page
optimize_week RISK: RED
run_date 2026-06-09 · week_of 2026-06-09
training_sessions 0 · meal_plan_path null
all_blocks_synced_to_managed_memory true
"Travel week Jun 12–17. Meal plan skipped. RED Thursday (compounding: travel+alcohol+stress streak). GCal alerts placed Thu+Fri."
neurologist_agent RED
run_date 2026-06-09 · top_factor travel_compounding
avg_recovery 54.4% · avg_hrv 157.0 ms · avg_rhr 49.7
stress_streak_days 5 · alcohol_days_recent 2
gcal_alerts_placed: Jun 12, Jun 13
whoop_report COMPLETE
run_date 2026-06-09 · month June 26
window 2025-12-25 → 2026-06-09 · n_days 167 · anomalies 2
HRV↔recovery r 0.819 · partial r 0.824
OLS R² 0.221 (n=166) — sleep duration + prior-day strain only
gordon_ramsay STALE — by design
run_date 2026-04-26 · week_of 2026-04-28
avg_protein 155 g · avg_cals 3,200 (marathon taper + carb load)
Last full plan was race week. Today's run skipped meals deliberately (travel) — and this stale block is precisely what Alfred's >14-day drift flag exists to catch.
calendar COMPLETE
run_date 2026-05-24 · block Golf-block summer 2026
7 sessions · weekly_strain_estimate 92 · long_run_day "none"
9 GCal event IDs stored · constraints: no heavy OHP, no floor deadlifts, RPE 8 ceiling
morning_digest TOMBSTONE
status disabled (2026-04-01)
"Do not read this block as a data source." — a dead pipeline is documented in state rather than silently deleted, so no agent ever resurrects it by accident.

This week's live forecast — written by the neurologist agent this morning

MON 06-09
YELLOW
TUE 06-10
YELLOW
WED 06-11
YELLOW
THU 06-12
RED
FRI 06-13
YELLOW
SAT 06-14
YELLOW
SUN 06-15
YELLOW

Thursday goes RED because the compounding rule fired: travel departure + alcohol within the recency window + a 5-day stress streak. Two yellows normally compound to yellow — but when one factor is alcohol, dizziness, or high-tier travel, the week escalates to red. The agent placed ⚠️ alert events on my Google Calendar for Jun 12–13.

Why verbatim state matters Nothing on this page is staged. The RED forecast, the null meal plan, the stale April meal block — that's the actual system state today. A dashboard that only ever shows green is a demo; a system that records "meal plan skipped, travel week" is operations.

system architecture

The nine agents

Eight live in the project at Personal/Health/.claude/skills/; the orchestrator lives globally at ~/.claude/skills/optimize-week/. Each is a SKILL.md — versioned instructions, guardrails, and a documented Gotchas section of real production failures.

optimize-week
master orchestrator · closed-loop weekly planner

One command plans the entire week. Runs Week Brief → Pre-flight → Phases 0, 0.5, 1, 2, 2.5, 3, 4, 5, 5.5 — training, risk forecast, meals, groceries, state write, governance check. The only skill permitted multi-level spawn chains (max depth 3, enforced by spawning-rules.md).

writes: pipeline-state.json via write_all_pipelines() · pipeline-history.json (append-only)
gordon-ramsay
autonomous meal planner · Phases 0–3, Outputs A–I

Strain-aware meal placement: pre-PEAK dinner carb-loads, PEAK-day dinner gets the highest protein tier, rest days eat leftovers. Nine outputs per run — plan table, grocery list, macro snapshot, Apple Notes, Reminders, meal-log.md, meal-annotations.json, a 3-tab PWA, GCal cook nights, state write. style_lock: brand — design agents may polish but never replace its palette.

reads: Meals/pantry/food-pantry.md · Meals/meal-annotations.json · Meals/agent-weights.json
whoop-report
monthly biometric analysis · orchestrator of 7 subagents

Explicitly an orchestrator: "you do NOT do the analysis yourself." Dispatches a Haiku data cleaner, then four Sonnet analysts in parallel (descriptive stats, OLS regression + HRV mediator, dose-response, behavioral interventions), merges their JSON, then two Sonnet renderers in parallel (interactive HTML report + scorecard). Also freezes a monthly baseline_snapshot into the managed memory store.

in: Whoop Performance/[Month]/raw/*.csv → out: cleaned/analysis-results.json · report HTML · scorecard
neurologist-agent
self-calibrating seizure-risk forecaster · Phase 2.5 of optimize-week

Scores 7 risk factors against a 30-day baseline from 79 days of journal signals, applies protective credits (3+ day meditation/outdoors streaks) and a compounding rule, and outputs a GREEN/YELLOW/RED forecast per day plus overrides for the other agents. Always surfaces overrides and waits — it never silently modifies the training or meal plan.

reads: Meals/neurologist-signals.json · Meals/seizure-risk.json · Meals/agent-weights.json (consumer only — never writes it)
calendar
training scheduler · PPL cycle + long-run anchoring

Reads existing GCal events first — if the week is already built, it uses that as the strain map instead of regenerating (source-of-truth check). Places sessions around hard anchors: never lift on long-run day, never legs the day before. Writes a schema-locked state block where session_map keys must be ISO dates — day names break the validator.

reads: Training/ATHLETE.md · Training/workout-plan.md · GCal MCP  |  writes: GCal events + state block
alfred
governance agent · drift detection, memory integrity, config backup

The watchdog. Flags pipelines stale >14 days, validates state blocks against required-field schemas, cross-references that gordon_ramsay and optimize_week agree on the same week, and runs the silent-fallback detector — comparing the managed store's updated_at against local snapshot_date. Hard rules: never writes pipeline-state.json, never modifies a SKILL.md, never deletes, never spawns. A watchdog, not a gate — if Alfred itself errors, the pipeline completes anyway.

reads: pipeline-history.json · executes: pipeline_memory.py status
managed-memory-agent
safety & rollback for the memory migration

Owns STATUS / UPDATE / INSPECT / ROLLBACK / SNAPSHOT against the live store. Rollback is fully reversible by design: the pre-migration text of every modified SKILL.md is preserved in skill_originals{} in the registry, and remote deletion must return 200 before any local file is touched. Baseline snapshots are never deleted — even by rollback.

owns: memory-store-config.json · pipeline_memory.py · store memstore_013zYKKw8W2f5AV4G5V71Djj
meal-log-update
mid-week actuals corrector · 8 phases

Reconciles plan vs. reality: validates last week's carry-in against meal-annotations.json (Phase 1.5), interviews me on deviations, rebuilds the actuals table under batch-carry rules, replans forward, flags grocery gaps (Phase 4.5) and sub-150g protein days (Phase 8). Sets actuals_updated: true in state so downstream validators know this week reflects what was actually eaten.

writes: Meals/meal-log.md (current week only) · Meals/meal-annotations.json · gordon_ramsay state block
fridge-raid
guided pantry editor · the human-input gate

The smallest agent, deliberately: a confirm-at-every-step editor for Meals/pantry/food-pantry.md — the single source of truth every meal decision flows from. Gordon Ramsay is forbidden from inventing meals ("pull entrees ONLY from food-pantry.md"), so the pantry file is the one place where human curation enters the system, and it gets its own guarded skill rather than ad-hoc edits.

pipeline walkthrough

What happens when /optimize-week fires

One command, zero manual handoffs. Each phase names the files it reads and writes — this is the order of operations from the SKILL.md, not a simplification.

WEEK BRIEForchestrator

Nine questions, one message — then no more questions

Carry-ins, special meals, run schedule, egg-bake cycle, travel, workout changes, pantry additions, anything else, protected time. Answers become a locked CONSTRAINTS block that every later rebuild must re-read — a session guardrail added 2026-04-26 after a live run silently dropped a constraint mid-rebuild.

PRE-FLIGHTorchestrator

File checks + two independent auth systems

Halts if food-pantry.md or ATHLETE.md is missing. Tests GCal MCP (training events, cook nights) and GWS CLI (grocery email) separately — they're different OAuth systems and fixing one does not fix the other. Each failure has a pre-declared fallback, decided now, not discovered mid-pipeline.

PHASE 0validator script

State integrity gate

Runs pipeline-state-validator.py against pipeline-state.json. Errors halt the run; warnings print one line and continue.

Why this mattersCorrupt shared state poisons every downstream agent. Validating before planning means a bad write from last week can't silently become this week's wrong meal plan.
PHASE 0.5whoop-report
+ 7 subagents

Monthly Brain Check — auto-detected, not scheduled

If a new Whoop Performance/[Month]/raw/ CSV export exists without an output/ folder, the full whoop-report pipeline runs first: Haiku cleaner → 4 parallel Sonnet analysts → merge → 2 parallel Sonnet renderers. Then the Retrospective Validator grades last month's risk forecasts against actual biometrics and recalibrates Meals/agent-weights.json — shifts capped at ±15% per monthly cycle, hard bounds [0.5, 2.0].

Why this mattersThe forecaster never grades its own homework. Generation (neurologist) and evaluation (validator) are separate agents with a one-way write boundary: only the validator may touch agent-weights.json. That's the difference between a system that self-calibrates and one that self-reinforces.
PHASE 1orchestrator

Read all context once, in parallel

food-pantry.md, meal-log.md, meal-annotations.json, ATHLETE.md, workout-plan.md, the Training/Running/ folder, and next week's GCal. A standing guardrail — "Reuse Phase 1 reads" — forbids later phases from re-reading these files. Read once, use everywhere.

PHASE 2calendar logic

Training placement → the strain map

Checks GCal first: if I pre-built the week, those events are the strain map — no regeneration. Otherwise places the 3-on-1-off cycle around hard anchors (long run wherever Runna put it; no legs the day before). Output is the strain map — {day → type, tier, time} — the data structure every downstream phase consumes.

PHASE 2.5neurologist-agent

Risk forecast — the human gate in the middle of the pipeline

Scores 7 factors against the 30-day signal baseline, applies the compounding rule, and prints the week's GREEN/YELLOW/RED forecast plus proposed overrides (deload Tuesday, lighten Wednesday meals, GCal alerts). The pipeline stops here until I confirm. It also prints the last 7 days of raw signals for me to read myself — the SKILL.md's words: "Outsource the scoring, keep the sensing."

Why this mattersThis is Tier 2 enforcement in code, not policy: the highest-stakes output in the system (a health intervention) is structurally incapable of applying itself. Today's run is proof — Thursday went RED and the alerts only landed on my calendar after I confirmed.
PHASE 3gordon-ramsay logic

Meals placed against the strain map — nine outputs, none skippable

Carb-load lands the night before PEAK; the PEAK-day dinner gets the highest protein tier; rest days eat leftovers. Then Outputs A–I run in order, ending with Output I: the state write. A guardrail exists because of a real miss — Output H (cook nights → GCal) was skipped on 2026-03-26 when the checklist only said "A–G."

PHASE 4–5orchestrator

Grocery email, then the atomic state write

Phase 5 calls write_all_pipelines(pipelines_dict) — never individual writes — because Phase 5 is exactly where a partial failure (gordon_ramsay lands, neurologist_agent silently doesn't) would make next week's run read stale risk data. Any non-null alert blocks the history write until resolved. Then the run is appended to pipeline-history.json with computed drift_flags (HRV ±10ms, recovery ±5%, protein ±20g vs. the prior run).

PHASE 5.5alfred

Governance check before the run may declare itself complete

Alfred verifies every block written locally is reachable in managed memory and runs drift detection. Non-empty actions_needed surfaces to me before completion. If Alfred itself fails, the pipeline still completes — "Alfred is a watchdog, not a gate."

Why GCal writes are sequentialA standing guardrail across all agents: the Google Calendar MCP intermittently returns 500s on concurrent create_event calls. Every event is created one at a time, with one retry, then plaintext fallback. Learned in production, encoded as a rule.

memory architecture

Two tiers, one interface, one hard-earned lesson

Every pipeline writes through one module — Personal/Health/pipeline_memory.py — which writes the Anthropic managed memory store first and always writes the local JSON regardless. The registry mapping pipelines to memory records lives in memory-store-config.json.

TIER 1 — Managed Memory Store

memstore_013zYKKw8W2f5AV4G5V71Djj · header: anthropic-beta: managed-agents-2026-04-01
  • 6 memory records — one per pipeline block (incl. the morning_digest tombstone)
  • 2 frozen baseline_snapshots (2026-05-24, 2026-06-09) — monthly biometric checkpoints for diffing
  • Writes use a SHA-256 content precondition (optimistic concurrency); on 409, retry without precondition — safe, single-owner store
  • Survives machine loss; readable by any future agent session
⇄

TIER 2 — Local Fallback

Personal/Health/pipeline-state.json · always written
  • The original source of truth — migration never touched it, so rollback is always possible
  • write_pipeline() returns True only if the managed write succeeded; False = local-only fallback
  • write_all_pipelines() adds partial-write detection: a named alert listing exactly which blocks failed
  • Companion: pipeline-history.json, append-only run log with drift thresholds + schemas
INCIDENT REPORT · LOGGED IN managed-memory-agent/SKILL.md

The silent fallback: 3 weeks of writes that lied by omission

Symptom. From 2026-05-04 to 2026-05-24, every write_pipeline() call returned False. Local state kept updating perfectly — pipelines ran, plans shipped, nothing looked wrong. The managed store sat frozen at its creation date for 20 days.

Root cause. Claude Code launched from VSCode doesn't inherit the terminal shell environment. ANTHROPIC_API_KEY lived in ~/.zshrc — which only interactive shells read — so it never reached the Claude Code process or any Python subprocess it spawned. _headers() returned None, and the module did exactly what it was designed to do: fell back gracefully, silently.

The real bug wasn't the env var. It was that the fallback worked too well. Graceful degradation without observability isn't resilience — it's silent data corruption with good manners.

2026-05-04
Migration ships in a live practice session. Store created, 6 blocks seeded, all green.
05-04 → 05-24
Every pipeline run silently falls back to local-only. No error, no warning — the return value existed but no skill was required to check it.
2026-05-24
Caught during a manual STATUS check: remote updated_at = creation date on every block.
2026-05-24
Four-layer fix, same day: ① key moved to ~/.zshenv (read by all zsh invocations, including GUI launches) ② _get_api_key() added to pipeline_memory.py — env first, then parse ~/.zshenv directly, bulletproof regardless of launch path ③ all 5 pipeline SKILL.mds now mandate capturing the return value and surfacing False ④ Alfred gained a silent-fallback detector: managed updated_at >24h older than local snapshot_date = Tier 2 surface.

Design takeaway: the same failure now has four independent chances to be caught — at the environment, in the library, in every calling agent, and by the post-run watchdog. The incident is written into the SKILL.md itself, so every future agent that touches this module reads the failure mode before writing a line.

# the contract every pipeline skill is bound to (verbatim pattern from the SKILL.mds)
from pipeline_memory import write_pipeline

ok = write_pipeline("gordon_ramsay", data)
if not ok:
    print("⚠️ MANAGED MEMORY WRITE FAILED — block written local-only. Run /managed-memory-agent STATUS to diagnose.")

# "A False return without surfacing is what caused the 2026-05-04 → 2026-05-24 silent drift. Do not skip this check."

governance

The three-tier autonomy framework

Every action any agent takes is classified before it runs — defined in ~/.claude/rules/autonomy-boundaries.md and enforced inside each SKILL.md. The examples below are pulled from the actual skill files, not the policy doc.

TIER 1 — AUTONOMOUS

Reversible, low blast radius, inside the agent's job description. Runs without asking.
  • neurologist-agent computes the 7-factor risk forecast and writes seizure-risk.json
  • gordon-ramsay generates the meal-plan PWA and appends to meal-log.md
  • whoop-report dispatches its 7 subagents and writes analysis JSON
  • Any agent writing its own pipeline-state block via write_pipeline()

TIER 2 — SURFACE FIRST

Outward-facing or hard to reverse. Show the action, wait for explicit "go."
  • Every GCal write — training events, cook nights, risk alerts (sequential, one at a time)
  • Neurologist overrides — Phase 2.5 halts the whole pipeline until I confirm or reject
  • Whoop report → public GitHub repo — raw biometrics; requires a literal "yes" to the printed warning, never auto-fires
  • agent-weights.json changes beyond ±25% of current values
  • All Alfred remediation — Tier 2 by default until individually promoted

TIER 3 — HALT

Stop fully, report, never continue on partial data.
  • API key unresolvable from env AND ~/.zshenv — Alfred halts with the fix recipe
  • Managed memory store unreachable for any block
  • Corrupt pipeline-state.json — Phase 0 validator errors stop the run before planning
  • optimize-week pre-flight: missing food-pantry.md or ATHLETE.md = print path, stop
Rules the calibration loop cannot override Self-tuning has clinical guardrails baked in: alcohol is never downgraded by protective credits even if its learned weight drops below 1.0, and dizziness on Sunday forces a yellow week baseline that no multiplier can cancel. The system is allowed to learn how sensitive to be — it is not allowed to learn its way out of a safety rule.
Subagents inherit, never expand A subagent's autonomy ceiling is its parent's. A newly created agent runs Tier-2-everything until specific actions are individually promoted. No agent earns trust by default — including the governance agent itself: the open question "should Alfred ever auto-remediate?" is documented in its SKILL.md with the answer "Default: No."

cost engineering

Model tiering — documented in the SKILL.md, not folklore

From the Model Assignments table in whoop-report/SKILL.md, plus the standing rules in ~/.claude/rules/spawning-rules.md.

SubagentFunctionModel
SA1 — Data CleanerCSV parsing, normalization, anomaly flagging — no reasoning requiredclaude-haiku-4-5
SA2 — Descriptive StatsMeans/SDs, weekly averages, period deltasclaude-sonnet-4-6
SA3 — Regression + HRV MediatorOLS model, partial correlationsclaude-sonnet-4-6
SA4 — Dose-Response + ModalityQuadratic strain→recovery fit, Cohen's d between training typesclaude-sonnet-4-6
SA5 — Interventions + CorrelationsBehavioral effects (≥30 yes-days AND ≥30 no-days required — small-n effect sizes are bias, not signal)claude-sonnet-4-6
SA6 — Report GeneratorToken-fills the HTML report template, bakes data inlineclaude-sonnet-4-6
SA7 — Scorecard BuilderUpdates the scorecard DATA object, computes month-over-month trendsclaude-sonnet-4-6
Why Opus is banned here Verbatim rationale from the skill: "Opus is not used — this pipeline runs ~87K tokens and Opus would 3–4x cost with no quality benefit." The spawning rules make it a hard rule for both big pipelines, with one exception that cuts the other way: any subagent writing to pipeline-state.json is Sonnet minimum — Haiku truncation is a known corruption vector. Cheapest model that's correct, never cheaper.
Why optimize-week inlines instead of spawning The orchestrator runs calendar, neurologist, and gordon-ramsay logic in its own context ("do NOT invoke as a separate skill") but spawns whoop-report as a real subagent pipeline. The dividing line is token economics: the planning phases share Phase 1's file reads — spawning would force every input back through disk per spawning-rules Rule 3 — while the Whoop analysis is an ~87K-token job that would blow out the parent context. Spawn when isolation pays for itself; inline when shared context does.

summary

What this system proves

"This system runs on orchestration, not a bigger model — nine agents with narrow jobs, coordinated through shared state and explicit handoffs, outperform any single prompt I could write. Every piece of complexity is cost-justified and documented: Haiku cleans CSVs, Sonnet does the analysis, and Opus is banned from an 87K-token pipeline by a written rule, not a vibe. And governance is a design layer, not an afterthought — every action is tiered Autonomous, Surface, or Halt before it runs; the forecaster can't grade its own homework; and when the memory layer failed silently for three weeks, the fix wasn't a patch, it was four independent layers of detection. I operate this in production on my own seizure risk — which means I had to learn what production actually demands: observability, rollback paths, and the humility to assume the failure you can't see is the one happening right now."
ARCHITECT'S NOTE — CLAUDE FABLE 5, AFTER READING ALL NINE SKILL FILES AND THE LIVE DATA LAYER

The decision that most signals real engineering judgment isn't the orchestration — it's the write boundary around agent-weights.json. The neurologist consumes the calibration weights but is forbidden from writing them; only the monthly Retrospective Validator may, with shifts capped at ±15% per cycle inside hard bounds [0.5, 2.0], and with clinical rules (alcohol, Sunday dizziness) that no learned weight can override. That's bounded self-modification with separated generation and evaluation — the pattern production ML teams reach for after their first feedback loop goes degenerate, implemented here before it did.

Second, the system is honest about its own immaturity: every entree-recovery correlation in the live weights file is still 0.0, and the state block documents it — "untrained… future snapshots should show these populate." Most builders would hide an untrained feature; this one wrote a comparison anchor so the moment it starts learning is itself measurable. The silent-fallback incident completes the picture: the postmortem lives inside the SKILL.md where future agents must read it. Tutorials teach happy paths. Operators write incident reports into their tools.