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.
pipeline-state.json says right now — verbatimThursday 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.
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.
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).
pipeline-state.json via write_all_pipelines() · pipeline-history.json (append-only)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.
Meals/pantry/food-pantry.md · Meals/meal-annotations.json · Meals/agent-weights.jsonExplicitly 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.
Whoop Performance/[Month]/raw/*.csv → out: cleaned/analysis-results.json · report HTML · scorecardScores 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.
Meals/neurologist-signals.json · Meals/seizure-risk.json · Meals/agent-weights.json (consumer only — never writes it)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.
Training/ATHLETE.md · Training/workout-plan.md · GCal MCP | writes: GCal events + state blockThe 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.
pipeline-history.json · executes: pipeline_memory.py statusOwns 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.
memory-store-config.json · pipeline_memory.py · store memstore_013zYKKw8W2f5AV4G5V71DjjReconciles 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.
Meals/meal-log.md (current week only) · Meals/meal-annotations.json · gordon_ramsay state blockThe 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.
/optimize-week firesOne 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.
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.
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.
Runs pipeline-state-validator.py against pipeline-state.json. Errors halt the run; warnings print one line and continue.
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].
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.
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.
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."
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 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).
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."
create_event calls. Every event is created one at a time, with one retry, then plaintext fallback. Learned in production, encoded as a rule.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.
write_pipeline() returns True only if the managed write succeeded; False = local-only fallbackwrite_all_pipelines() adds partial-write detection: a named alert listing exactly which blocks failedpipeline-history.json, append-only run log with drift thresholds + schemasSymptom. 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.
updated_at = creation date on every block.~/.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.
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.
seizure-risk.jsonmeal-log.mdwrite_pipeline()food-pantry.md or ATHLETE.md = print path, stopFrom the Model Assignments table in whoop-report/SKILL.md, plus the standing rules in ~/.claude/rules/spawning-rules.md.
| Subagent | Function | Model |
|---|---|---|
| SA1 — Data Cleaner | CSV parsing, normalization, anomaly flagging — no reasoning required | claude-haiku-4-5 |
| SA2 — Descriptive Stats | Means/SDs, weekly averages, period deltas | claude-sonnet-4-6 |
| SA3 — Regression + HRV Mediator | OLS model, partial correlations | claude-sonnet-4-6 |
| SA4 — Dose-Response + Modality | Quadratic strain→recovery fit, Cohen's d between training types | claude-sonnet-4-6 |
| SA5 — Interventions + Correlations | Behavioral effects (≥30 yes-days AND ≥30 no-days required — small-n effect sizes are bias, not signal) | claude-sonnet-4-6 |
| SA6 — Report Generator | Token-fills the HTML report template, bakes data inline | claude-sonnet-4-6 |
| SA7 — Scorecard Builder | Updates the scorecard DATA object, computes month-over-month trends | claude-sonnet-4-6 |
"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."
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.