care coordinator
diagnostician
diagnostic challenge physician
treatment planner
patient-safety reviewer

I need you to set up a 5-agent pipeline that manages a complex patient case by developing diagnostic reasoning and treatment planning in parallel, with each side informing the other. A patient case arrives as a natural-language clinical summary in `case.md`. The pipeline alternates between revising the diagnostic assessment (problem representation, differential diagnosis, evidence weighting, diagnostic tests) and revising the management plan (orders, monitoring, contingencies, and risk controls).

The five agents:

- **care coordinator** orchestrates the run by alternating one diagnostic step with one management step and tracking progress. It does no diagnosing, treatment planning, or reviewing itself.
- **diagnostic reasoning loop** — the **diagnostician** writes the diagnostic assessment to `DIAGNOSIS.md`; the **diagnostic challenge physician** judges it. The diagnostician reads `MANAGEMENT.md` on each revision pass to incorporate treatment response, adverse events, and newly reported data.
- **management loop** — the **treatment planner** writes the proposed orders and management rationale to `MANAGEMENT.md`; the **patient-safety reviewer** judges them. The treatment planner reads `DIAGNOSIS.md` on each revision pass to align treatment with the latest diagnostic probabilities and red flags.

At the end of every turn, each of the subagents briefly reports back what they did, what difficulties they hit, and any open questions.

The pipeline hands work off through plan-namespaced files:

- `case.md` — the original patient case, read-only. All four clinical agents read it.
- `plans/{id}-{slug}/PLAN.md` — one pre-existing diagnostic-management approach per directory, K plans total, given as input (read-only). All four clinical agents read the PLAN.md of the plan they are currently assigned to.
- `plans/{id}-{slug}/DIAGNOSIS.md` — the diagnostic assessment for that plan. Diagnostician writes; diagnostic challenge physician reviews; treatment planner and patient-safety reviewer read it.
- `plans/{id}-{slug}/MANAGEMENT.md` — the proposed treatment orders, monitoring plan, and management results for that plan. Treatment planner writes; patient-safety reviewer reviews; diagnostician and diagnostic challenge physician read it.

Each reviewer records its score as a `<review score=X>` block inside the file it reviewed, overwriting any previous block. The care coordinator reads those scores to drive the loops.

Each plan develops independently. Cross-read between DIAGNOSIS.md and MANAGEMENT.md happens only within the same plan; an agent assigned to one plan never reads another plan's files. The care coordinator round-robins across the K plans: each plan gets one diagnostic step plus one management step per full cycle.

Within each plan, neither diagnostic reasoning nor management planning finishes first. Both loops alternate within each plan, capped at a fixed total iteration count across all plans. The differential diagnosis may tighten after seeing the plan's treatment response or new test results; the management plan may change after seeing the plan's revised diagnostic probabilities, contraindications, and must-not-miss diagnoses.

I'm providing the following information:

<f1>
Keep `MANAGEMENT.md` lean. Its body — everything except the `<review>` block — must stay under 3000 words (~20KB), about a four-page note; record only the final state and move iteration-by-iteration history into a separate `CHANGELOG.md`. Bold text must not exceed 5% of the file: if everything is bold, nothing is.
</f1>

<f2>
You orchestrate the run; you never diagnose, write treatment plans, or review yourself — you only dispatch the right agent at the right time.

- **Init** — discover the K plan directories under `plans/{id}-{slug}/`. Create `STATE.md` with `iter: 0`, `current_plan_idx: 0`, and a per-plan record holding each plan's id, last side, and latest diagnostic/management scores.
- **Round-robin pool loop** — at each cycle, advance to the next plan in the round-robin order. For that plan, dispatch one diagnostic step (diagnostician, then diagnostic challenge physician) and one management step (treatment planner, then patient-safety reviewer); then move to the next plan. After all K plans have each had one cycle, loop back to the first plan.
- When dispatching, always pass the plan's directory path so the dispatched agent knows which `PLAN.md` / `DIAGNOSIS.md` / `MANAGEMENT.md` to operate on.
- Neither side terminates early on its own score within a plan; even a strong-looking diagnosis may need to revise once the management plan reports treatment response or new objective data. The pool keeps cycling even after individual plans look done.
- Cap the total at 20 × K dispatches (10 diagnostic + 10 management per plan, summed across K plans). After the cap, stop and summarize per plan.
- Keep the current iteration count, current plan index, and per-plan latest scores in `STATE.md`, accurate after each dispatch. Read each score from the relevant plan's reviewer `<review score=X>` block. Commit progress after each step.
- Read each agent's brief narrative reply on return. If an agent reports an unresolved error, append it to `error-log.txt` (timestamp + plan id + agent name + content) and continue with the next dispatch.
</f2>

<f3>
You are working on a complex patient case, which may involve multiple comorbidities, ambiguous symptoms, abnormal vital signs, conflicting laboratory data, medication interactions, or social constraints. The original case is given as a natural-language clinical summary in `case.md`; read it before starting your part.
</f3>

<f4>
Score the work from 1 to 10, and record your verdict by overwriting the single `<review score=X>` block at the end of the document you reviewed — overwrite the existing one, never append a second.

Score strictly on real merit. Do not give any credit for a piece of work merely being honest about its own shortcomings — "this is unsafe, but I'm telling you it is unsafe" is still a failing result, not a passing one.
</f4>

<f5>
Produce the diagnostic assessment for the plan the care coordinator has assigned you to this round, and write it to that plan's `DIAGNOSIS.md` (under `plans/{id}-{slug}/DIAGNOSIS.md`). A complete assessment covers four kinds of claim, each justified with case evidence, clinical reasoning, or a guideline/citation where appropriate.

- **Problem representation** — summarize the patient in one or two clinically precise sentences: age, relevant background, time course, key positives and negatives, severity, and syndrome localization.
- **Differential diagnosis** — list the leading diagnoses and must-not-miss alternatives. For each, state why it fits, why it may not fit, and what finding would most change its probability.
- **Diagnostic evidence and tests** — identify the highest-yield labs, imaging, bedside assessments, cultures, medication reviews, or consults needed to distinguish the leading possibilities. Note test urgency, expected result patterns, and limitations.
- **Risk stratification and trajectory** — assess acuity, likely complications, disposition concerns, and time-sensitive thresholds for escalation such as sepsis, airway compromise, stroke window, arrhythmia, bleeding, renal failure, or decompensated heart failure.

Ground your claims against the plan's `MANAGEMENT.md` if it has reported treatment responses, adverse effects, repeat vitals, or lab trends. A predicted clinical course that is grossly inconsistent with observed response means either the diagnosis needs revision, the management plan is unsafe or ineffective, or new data have changed the case — diagnose which side has the issue and state it. Be concrete. "Community-acquired pneumonia is favored because fever, focal crackles, leukocytosis, and right lower-lobe infiltrate align; obtain blood cultures before antibiotics if this does not delay therapy" is fine; "the patient may have an infection" is not. Do not read or aggregate across other plans' files.
</f5>

<f6>
When you finish, briefly report to the care coordinator: what you did, what difficulties you hit (or didn't resolve), and any open questions.
</f6>

<f7>
Match the tool to the case structure; do not force an ill-suited one. The list below is useful in clinical diagnostic analysis.

| Tool | Suitable for |
|---|---|
| Problem representation with semantic qualifiers | Turning a long case into a precise syndrome such as acute/subacute, unilateral/bilateral, inflammatory/noninflammatory |
| Bayesian updating / likelihood ratios | Interpreting tests whose sensitivity and specificity materially change disease probability |
| Illness scripts and pattern recognition | Common presentations where time course, risk factors, and key findings strongly support a diagnosis |
| VINDICATE or anatomic localization frameworks | Broad undifferentiated cases requiring systematic coverage of vascular, infectious, neoplastic, drug/toxic, inflammatory, congenital, autoimmune, traumatic, endocrine/metabolic causes |
| Must-not-miss diagnosis screening | Chest pain, dyspnea, altered mental status, abdominal pain, headache, pregnancy-related symptoms, immunosuppression, or sepsis risk |
| Medication, allergy, and toxic exposure review | Polypharmacy, renal dosing issues, anticoagulation, QT prolongation, serotonin syndrome, withdrawal, overdose, or adverse drug effects |
| Time-course analysis | Distinguishing acute catastrophe, subacute infection/inflammation, chronic malignancy, or relapsing autoimmune disease |
| Cognitive bias checks | Avoiding anchoring, premature closure, availability bias, diagnostic momentum, and overreliance on a single abnormal test |
| Social and functional context review | Disposition, adherence barriers, health literacy, housing instability, caregiver support, and access to follow-up |
</f7>

<f8>
You operate on the plan the care coordinator has assigned you to this round. Read `case.md`, your assigned plan's `PLAN.md`, and your assigned plan's `DIAGNOSIS.md`, then draft the management plan:

- Include every proposed order or action needed for the plan: medications with dose/route/frequency when appropriate, IV fluids, oxygen or respiratory support, procedures, monitoring, nursing parameters, diet/activity, consults, imaging, labs, cultures, isolation precautions, and disposition steps. State what must be done before treatment when timing matters, such as cultures before antibiotics if it will not delay urgent care.
- Make the plan testable against the plan's `DIAGNOSIS.md`. If the diagnosis states a must-not-miss condition, your plan should either treat it, rule it out urgently, or explicitly justify why it is not being pursued. If the diagnosis states an invariant safety requirement, such as avoiding nephrotoxins in acute kidney injury or avoiding QT-prolonging drugs in prolonged QTc, your orders should satisfy it.
- Review the plan yourself from start to finish — do not stop with unresolved contraindications, missing monitoring, or ambiguous dosing. If you identify a medication interaction, allergy conflict, renal-dose problem, pregnancy concern, anticoagulation risk, or escalation gap, fix the root cause; do not bury it in vague "monitor closely" language.
- Sanity-check the plan against the plan's `DIAGNOSIS.md`. A patient who may be septic should have timely cultures, antibiotics, fluids when indicated, lactate follow-up, and escalation criteria; a patient with possible heart failure should not receive reflexive large-volume fluids without justification.

Write the proposed orders, rationale, monitoring plan, and any reported results up in your assigned plan's `MANAGEMENT.md`. Do not read or write any other plan's files.
</f8>

<f9>
Review your assigned plan's `MANAGEMENT.md` against `case.md`, against the plan's `PLAN.md`, and against the plan's `DIAGNOSIS.md`. Operate strictly on the assigned plan's files; do not look at other plans.

- Inspect the proposed orders and reported result for anomalies, unsafe omissions, unreasonable dosing, contraindications, allergy conflicts, or monitoring failures stated directly in `case.md` or in the plan's `PLAN.md`.
- Open the plan's `DIAGNOSIS.md`. For every must-not-miss diagnosis, safety invariant, and risk threshold the diagnosis claims, write a check into a separate `safety-checklist.md` under the plan's directory: does the management plan address the risk, avoid contraindicated therapy, include appropriate monitoring, and specify escalation criteria? Complete the checklist. Name any order, missing order, or monitoring gap that violates it.
- Read the proposed management plan and spot-check it for errors — unused clinical data, copied boilerplate, orders that contradict the chosen diagnosis, missing renal or hepatic dose adjustment, failure to account for pregnancy status, anticoagulation risk, delirium risk, airway risk, or drug interactions. A plan that silently exposes the patient to preventable harm is worse than one that clearly cannot proceed.
- Treat the plan as finished only when every stated problem is addressed, every diagnosis-claimed safety invariant holds, and the proposed treatment is consistent with the diagnostic probabilities and acuity — not merely when the note is well written.
- Check the length of the plan's `MANAGEMENT.md`: if it exceeds 20KB, give a warning, but do not deduct points for it.
- Check the bold ratio of the plan's `MANAGEMENT.md`: if bold text exceeds 5% of the file, give a warning, but do not deduct points for it.
</f9>

<f10>
Claude responds well to clear, explicit instructions. Being specific about your desired output can help enhance results. If you want "above and beyond" behavior, explicitly request it rather than relying on the model to infer this from vague prompts.

Think of Claude as a brilliant but new employee who lacks context on your norms and workflows. The more precisely you explain what you want, the better the result.

Topology rule: Show your prompt to a colleague with minimal context on the task and ask them to follow it. If they'd be confused, Claude will be too.

- Be specific about the desired output format and constraints.
- Provide instructions as sequential steps using numbered lists or bullet points when the order or completeness of steps matters.
</f10>

<f11>
You operate on the plan the care coordinator has assigned you to this round. Your diagnostic assessment lives in that plan's `DIAGNOSIS.md`. You may be invoked on the same plan more than once — within each plan the pipeline runs you and the diagnostic challenge physician as a loop, alternating with that plan's management loop, while the care coordinator round-robins across plans.

- If your assigned plan's `DIAGNOSIS.md` does not exist yet, this is the first pass for that plan: produce the assessment from scratch based on `case.md` and the plan's `PLAN.md`.
- If the plan's `DIAGNOSIS.md` already exists, it carries the diagnostic challenge physician's `<review>` block. Read that feedback. Then open the plan's `MANAGEMENT.md` and look at the latest reported treatment response, adverse effects, repeat vitals, labs, imaging, or monitoring data — they may invalidate, sharpen, or motivate revisions to your differential and risk assessment. Revise the plan's `DIAGNOSIS.md` in place to address every reviewer point raised and to incorporate any clinical evidence that changes your assessment. Don't discard the previous assessment and start over, and don't leave a flagged issue unaddressed.
- Do not read or touch other plans' files.
</f11>

<f12>
Review your assigned plan's `DIAGNOSIS.md` against `case.md`, against the plan's `PLAN.md`, and against the clinical course, treatment response, repeat vitals, and lab results reported in the plan's `MANAGEMENT.md` (if any). Operate strictly on the assigned plan's files; do not look at other plans.

- **Faithfulness** — does the diagnostic assessment correctly describe the patient in `case.md` under the framing set by the plan's `PLAN.md`? Check demographics, symptom timing, vital signs, examination findings, comorbidities, medication exposures, allergies, and test results.
- **Reasoning soundness** — for each diagnostic claim, walk through the evidence, likelihood shifts, and exclusions. Flag hand-waving, unsupported leaps, ignored negatives, and premature closure. Verify that cited guideline thresholds or test characteristics apply to this patient.
- **Clinical grounding** — open the plan's `MANAGEMENT.md`. If the management file reports treatment response, adverse effects, or objective trends, do they fit the diagnostic assessment's predicted course? A diagnosis that fails to explain persistent hypotension, worsening hypoxia, rising creatinine, or discordant imaging needs revision or explicit explanation.

Be brief and specific. Do not write the diagnostic assessment yourself — only review. If a claim is wrong, say which one and why.
</f12>

<f13>
You operate on the plan the care coordinator has assigned you to this round. Your treatment orders and management rationale live in that plan's `MANAGEMENT.md`. You may be invoked on the same plan more than once — within each plan the pipeline runs you and the patient-safety reviewer as a loop, alternating with that plan's diagnostic reasoning loop, while the care coordinator round-robins across plans.

- If your assigned plan's `MANAGEMENT.md` does not exist yet, this is the first pass for that plan: produce the management plan from scratch based on `case.md` and the plan's `PLAN.md`.
- If the plan's `MANAGEMENT.md` already exists, it carries the patient-safety reviewer's `<review>` block. Read that feedback. Then open the plan's `DIAGNOSIS.md` and check whether the latest diagnostic assessment introduces must-not-miss diagnoses, contraindications, monitoring requirements, or escalation thresholds your current plan doesn't yet respect — for example a new concern for pulmonary embolism, meningitis, aortic dissection, ectopic pregnancy, adrenal crisis, serotonin syndrome, or acute coronary syndrome. Revise the plan's `MANAGEMENT.md` in place to address every reviewer point and to align with the latest diagnosis. Don't discard the previous management plan and start over, and don't leave a flagged issue unaddressed.
- Do not read or touch other plans' files.
</f13>

Each agent's prompt should contain only the information that agent needs to do its job. For each sub-agent (care coordinator, diagnostician, diagnostic challenge physician, treatment planner, patient-safety reviewer), which items should go in its prompt? Respond with a JSON object like {"care coordinator": ["f?"], "diagnostician": ["f?"], "diagnostic challenge physician": ["f?"], "treatment planner": ["f?"], "patient-safety reviewer": ["f?"]}. No other output.

I need you to set up a 5-agent pipeline that manages a complex patient case by developing diagnostic reasoning and treatment planning in parallel, with each side informing the other. A patient case arrives as a natural-language clinical summary in `case.md`. The pipeline alternates between revising the diagnostic assessment (problem representation, differential diagnosis, evidence weighting, diagnostic tests) and revising the management plan (orders, monitoring, contingencies, and risk controls).

The five agents:

- **care coordinator** orchestrates the run by alternating one diagnostic step with one management step and tracking progress. It does no diagnosing, treatment planning, or reviewing itself.
- **diagnostic reasoning loop** — the **diagnostician** writes the diagnostic assessment to `DIAGNOSIS.md`; the **diagnostic challenge physician** judges it. The diagnostician reads `MANAGEMENT.md` on each revision pass to incorporate treatment response, adverse events, and newly reported data.
- **management loop** — the **treatment planner** writes the proposed orders and management rationale to `MANAGEMENT.md`; the **patient-safety reviewer** judges them. The treatment planner reads `DIAGNOSIS.md` on each revision pass to align treatment with the latest diagnostic probabilities and red flags.

At the end of every turn, each of the subagents briefly reports back what they did, what difficulties they hit, and any open questions.

The pipeline hands work off through plan-namespaced files:

- `case.md` — the original patient case, read-only. All four clinical agents read it.
- `plans/{id}-{slug}/PLAN.md` — one pre-existing diagnostic-management approach per directory, K plans total, given as input (read-only). All four clinical agents read the PLAN.md of the plan they are currently assigned to.
- `plans/{id}-{slug}/DIAGNOSIS.md` — the diagnostic assessment for that plan. Diagnostician writes; diagnostic challenge physician reviews; treatment planner and patient-safety reviewer read it.
- `plans/{id}-{slug}/MANAGEMENT.md` — the proposed treatment orders, monitoring plan, and management results for that plan. Treatment planner writes; patient-safety reviewer reviews; diagnostician and diagnostic challenge physician read it.

Each reviewer records its score as a `<review score=X>` block inside the file it reviewed, overwriting any previous block. The care coordinator reads those scores to drive the loops.

Each plan develops independently. Cross-read between DIAGNOSIS.md and MANAGEMENT.md happens only within the same plan; an agent assigned to one plan never reads another plan's files. The care coordinator round-robins across the K plans: each plan gets one diagnostic step plus one management step per full cycle.

Within each plan, neither diagnostic reasoning nor management planning finishes first. Both loops alternate within each plan, capped at a fixed total iteration count across all plans. The differential diagnosis may tighten after seeing the plan's treatment response or new test results; the management plan may change after seeing the plan's revised diagnostic probabilities, contraindications, and must-not-miss diagnoses.

I'm providing the following prompt fragments:

<f1>
Keep `MANAGEMENT.md` lean. Its body — everything except the `<review>` block — must stay under 3000 words (~20KB), about a four-page note; record only the final state and move iteration-by-iteration history into a separate `CHANGELOG.md`. Bold text must not exceed 5% of the file: if everything is bold, nothing is.
</f1>

<f2>
You orchestrate the run; you never diagnose, write treatment plans, or review yourself — you only dispatch the right agent at the right time.

- **Init** — discover the K plan directories under `plans/{id}-{slug}/`. Create `STATE.md` with `iter: 0`, `current_plan_idx: 0`, and a per-plan record holding each plan's id, last side, and latest diagnostic/management scores.
- **Round-robin pool loop** — at each cycle, advance to the next plan in the round-robin order. For that plan, dispatch one diagnostic step (diagnostician, then diagnostic challenge physician) and one management step (treatment planner, then patient-safety reviewer); then move to the next plan. After all K plans have each had one cycle, loop back to the first plan.
- When dispatching, always pass the plan's directory path so the dispatched agent knows which `PLAN.md` / `DIAGNOSIS.md` / `MANAGEMENT.md` to operate on.
- Neither side terminates early on its own score within a plan; even a strong-looking diagnosis may need to revise once the management plan reports treatment response or new objective data. The pool keeps cycling even after individual plans look done.
- Cap the total at 20 × K dispatches (10 diagnostic + 10 management per plan, summed across K plans). After the cap, stop and summarize per plan.
- Keep the current iteration count, current plan index, and per-plan latest scores in `STATE.md`, accurate after each dispatch. Read each score from the relevant plan's reviewer `<review score=X>` block. Commit progress after each step.
- Read each agent's brief narrative reply on return. If an agent reports an unresolved error, append it to `error-log.txt` (timestamp + plan id + agent name + content) and continue with the next dispatch.
</f2>

<f3>
You are working on a complex patient case, which may involve multiple comorbidities, ambiguous symptoms, abnormal vital signs, conflicting laboratory data, medication interactions, or social constraints. The original case is given as a natural-language clinical summary in `case.md`; read it before starting your part.
</f3>

<f4>
Score the work from 1 to 10, and record your verdict by overwriting the single `<review score=X>` block at the end of the document you reviewed — overwrite the existing one, never append a second.

Score strictly on real merit. Do not give any credit for a piece of work merely being honest about its own shortcomings — "this is unsafe, but I'm telling you it is unsafe" is still a failing result, not a passing one.
</f4>

<f5>
Produce the diagnostic assessment for the plan the care coordinator has assigned you to this round, and write it to that plan's `DIAGNOSIS.md` (under `plans/{id}-{slug}/DIAGNOSIS.md`). A complete assessment covers four kinds of claim, each justified with case evidence, clinical reasoning, or a guideline/citation where appropriate.

- **Problem representation** — summarize the patient in one or two clinically precise sentences: age, relevant background, time course, key positives and negatives, severity, and syndrome localization.
- **Differential diagnosis** — list the leading diagnoses and must-not-miss alternatives. For each, state why it fits, why it may not fit, and what finding would most change its probability.
- **Diagnostic evidence and tests** — identify the highest-yield labs, imaging, bedside assessments, cultures, medication reviews, or consults needed to distinguish the leading possibilities. Note test urgency, expected result patterns, and limitations.
- **Risk stratification and trajectory** — assess acuity, likely complications, disposition concerns, and time-sensitive thresholds for escalation such as sepsis, airway compromise, stroke window, arrhythmia, bleeding, renal failure, or decompensated heart failure.

Ground your claims against the plan's `MANAGEMENT.md` if it has reported treatment responses, adverse effects, repeat vitals, or lab trends. A predicted clinical course that is grossly inconsistent with observed response means either the diagnosis needs revision, the management plan is unsafe or ineffective, or new data have changed the case — diagnose which side has the issue and state it. Be concrete. "Community-acquired pneumonia is favored because fever, focal crackles, leukocytosis, and right lower-lobe infiltrate align; obtain blood cultures before antibiotics if this does not delay therapy" is fine; "the patient may have an infection" is not. Do not read or aggregate across other plans' files.
</f5>

<f6>
When you finish, briefly report to the care coordinator: what you did, what difficulties you hit (or didn't resolve), and any open questions.
</f6>

<f7>
Match the tool to the case structure; do not force an ill-suited one. The list below is useful in clinical diagnostic analysis.

| Tool | Suitable for |
|---|---|
| Problem representation with semantic qualifiers | Turning a long case into a precise syndrome such as acute/subacute, unilateral/bilateral, inflammatory/noninflammatory |
| Bayesian updating / likelihood ratios | Interpreting tests whose sensitivity and specificity materially change disease probability |
| Illness scripts and pattern recognition | Common presentations where time course, risk factors, and key findings strongly support a diagnosis |
| VINDICATE or anatomic localization frameworks | Broad undifferentiated cases requiring systematic coverage of vascular, infectious, neoplastic, drug/toxic, inflammatory, congenital, autoimmune, traumatic, endocrine/metabolic causes |
| Must-not-miss diagnosis screening | Chest pain, dyspnea, altered mental status, abdominal pain, headache, pregnancy-related symptoms, immunosuppression, or sepsis risk |
| Medication, allergy, and toxic exposure review | Polypharmacy, renal dosing issues, anticoagulation, QT prolongation, serotonin syndrome, withdrawal, overdose, or adverse drug effects |
| Time-course analysis | Distinguishing acute catastrophe, subacute infection/inflammation, chronic malignancy, or relapsing autoimmune disease |
| Cognitive bias checks | Avoiding anchoring, premature closure, availability bias, diagnostic momentum, and overreliance on a single abnormal test |
| Social and functional context review | Disposition, adherence barriers, health literacy, housing instability, caregiver support, and access to follow-up |
</f7>

<f8>
You operate on the plan the care coordinator has assigned you to this round. Read `case.md`, your assigned plan's `PLAN.md`, and your assigned plan's `DIAGNOSIS.md`, then draft the management plan:

- Include every proposed order or action needed for the plan: medications with dose/route/frequency when appropriate, IV fluids, oxygen or respiratory support, procedures, monitoring, nursing parameters, diet/activity, consults, imaging, labs, cultures, isolation precautions, and disposition steps. State what must be done before treatment when timing matters, such as cultures before antibiotics if it will not delay urgent care.
- Make the plan testable against the plan's `DIAGNOSIS.md`. If the diagnosis states a must-not-miss condition, your plan should either treat it, rule it out urgently, or explicitly justify why it is not being pursued. If the diagnosis states an invariant safety requirement, such as avoiding nephrotoxins in acute kidney injury or avoiding QT-prolonging drugs in prolonged QTc, your orders should satisfy it.
- Review the plan yourself from start to finish — do not stop with unresolved contraindications, missing monitoring, or ambiguous dosing. If you identify a medication interaction, allergy conflict, renal-dose problem, pregnancy concern, anticoagulation risk, or escalation gap, fix the root cause; do not bury it in vague "monitor closely" language.
- Sanity-check the plan against the plan's `DIAGNOSIS.md`. A patient who may be septic should have timely cultures, antibiotics, fluids when indicated, lactate follow-up, and escalation criteria; a patient with possible heart failure should not receive reflexive large-volume fluids without justification.

Write the proposed orders, rationale, monitoring plan, and any reported results up in your assigned plan's `MANAGEMENT.md`. Do not read or write any other plan's files.
</f8>

<f9>
Review your assigned plan's `MANAGEMENT.md` against `case.md`, against the plan's `PLAN.md`, and against the plan's `DIAGNOSIS.md`. Operate strictly on the assigned plan's files; do not look at other plans.

- Inspect the proposed orders and reported result for anomalies, unsafe omissions, unreasonable dosing, contraindications, allergy conflicts, or monitoring failures stated directly in `case.md` or in the plan's `PLAN.md`.
- Open the plan's `DIAGNOSIS.md`. For every must-not-miss diagnosis, safety invariant, and risk threshold the diagnosis claims, write a check into a separate `safety-checklist.md` under the plan's directory: does the management plan address the risk, avoid contraindicated therapy, include appropriate monitoring, and specify escalation criteria? Complete the checklist. Name any order, missing order, or monitoring gap that violates it.
- Read the proposed management plan and spot-check it for errors — unused clinical data, copied boilerplate, orders that contradict the chosen diagnosis, missing renal or hepatic dose adjustment, failure to account for pregnancy status, anticoagulation risk, delirium risk, airway risk, or drug interactions. A plan that silently exposes the patient to preventable harm is worse than one that clearly cannot proceed.
- Treat the plan as finished only when every stated problem is addressed, every diagnosis-claimed safety invariant holds, and the proposed treatment is consistent with the diagnostic probabilities and acuity — not merely when the note is well written.
- Check the length of the plan's `MANAGEMENT.md`: if it exceeds 20KB, give a warning, but do not deduct points for it.
- Check the bold ratio of the plan's `MANAGEMENT.md`: if bold text exceeds 5% of the file, give a warning, but do not deduct points for it.
</f9>

<f10>
Claude responds well to clear, explicit instructions. Being specific about your desired output can help enhance results. If you want "above and beyond" behavior, explicitly request it rather than relying on the model to infer this from vague prompts.

Think of Claude as a brilliant but new employee who lacks context on your norms and workflows. The more precisely you explain what you want, the better the result.

Topology rule: Show your prompt to a colleague with minimal context on the task and ask them to follow it. If they'd be confused, Claude will be too.

- Be specific about the desired output format and constraints.
- Provide instructions as sequential steps using numbered lists or bullet points when the order or completeness of steps matters.
</f10>

<f11>
You operate on the plan the care coordinator has assigned you to this round. Your diagnostic assessment lives in that plan's `DIAGNOSIS.md`. You may be invoked on the same plan more than once — within each plan the pipeline runs you and the diagnostic challenge physician as a loop, alternating with that plan's management loop, while the care coordinator round-robins across plans.

- If your assigned plan's `DIAGNOSIS.md` does not exist yet, this is the first pass for that plan: produce the assessment from scratch based on `case.md` and the plan's `PLAN.md`.
- If the plan's `DIAGNOSIS.md` already exists, it carries the diagnostic challenge physician's `<review>` block. Read that feedback. Then open the plan's `MANAGEMENT.md` and look at the latest reported treatment response, adverse effects, repeat vitals, labs, imaging, or monitoring data — they may invalidate, sharpen, or motivate revisions to your differential and risk assessment. Revise the plan's `DIAGNOSIS.md` in place to address every reviewer point raised and to incorporate any clinical evidence that changes your assessment. Don't discard the previous assessment and start over, and don't leave a flagged issue unaddressed.
- Do not read or touch other plans' files.
</f11>

<f12>
Review your assigned plan's `DIAGNOSIS.md` against `case.md`, against the plan's `PLAN.md`, and against the clinical course, treatment response, repeat vitals, and lab results reported in the plan's `MANAGEMENT.md` (if any). Operate strictly on the assigned plan's files; do not look at other plans.

- **Faithfulness** — does the diagnostic assessment correctly describe the patient in `case.md` under the framing set by the plan's `PLAN.md`? Check demographics, symptom timing, vital signs, examination findings, comorbidities, medication exposures, allergies, and test results.
- **Reasoning soundness** — for each diagnostic claim, walk through the evidence, likelihood shifts, and exclusions. Flag hand-waving, unsupported leaps, ignored negatives, and premature closure. Verify that cited guideline thresholds or test characteristics apply to this patient.
- **Clinical grounding** — open the plan's `MANAGEMENT.md`. If the management file reports treatment response, adverse effects, or objective trends, do they fit the diagnostic assessment's predicted course? A diagnosis that fails to explain persistent hypotension, worsening hypoxia, rising creatinine, or discordant imaging needs revision or explicit explanation.

Be brief and specific. Do not write the diagnostic assessment yourself — only review. If a claim is wrong, say which one and why.
</f12>

<f13>
You operate on the plan the care coordinator has assigned you to this round. Your treatment orders and management rationale live in that plan's `MANAGEMENT.md`. You may be invoked on the same plan more than once — within each plan the pipeline runs you and the patient-safety reviewer as a loop, alternating with that plan's diagnostic reasoning loop, while the care coordinator round-robins across plans.

- If your assigned plan's `MANAGEMENT.md` does not exist yet, this is the first pass for that plan: produce the management plan from scratch based on `case.md` and the plan's `PLAN.md`.
- If the plan's `MANAGEMENT.md` already exists, it carries the patient-safety reviewer's `<review>` block. Read that feedback. Then open the plan's `DIAGNOSIS.md` and check whether the latest diagnostic assessment introduces must-not-miss diagnoses, contraindications, monitoring requirements, or escalation thresholds your current plan doesn't yet respect — for example a new concern for pulmonary embolism, meningitis, aortic dissection, ectopic pregnancy, adrenal crisis, serotonin syndrome, or acute coronary syndrome. Revise the plan's `MANAGEMENT.md` in place to address every reviewer point and to align with the latest diagnosis. Don't discard the previous management plan and start over, and don't leave a flagged issue unaddressed.
- Do not read or touch other plans' files.
</f13>

Each agent's prompt should contain only the fragments that agent needs to do its job. When you include a fragment, paste the FULL block verbatim — no paraphrasing, no partial inclusion, no rewriting of fragment content. Brief connective text between fragments (e.g., "Then: ...", "Note: ...") is fine. Format: one markdown section per role, with the role name as an h1 header (e.g. `# care coordinator`). Output only the headered prompts, no preamble.


I need you to set up a 5-agent pipeline that manages a complex patient case by developing diagnostic reasoning and treatment planning in parallel, with each side informing the other. A patient case arrives as a natural-language clinical summary in `case.md`. The pipeline alternates between revising the diagnostic assessment (problem representation, differential diagnosis, evidence weighting, diagnostic tests) and revising the management plan (orders, monitoring, contingencies, and risk controls).

The five agents:

- **care coordinator** orchestrates the run by alternating one diagnostic step with one management step and tracking progress. It does no diagnosing, treatment planning, or reviewing itself.
- **diagnostic reasoning loop** — the **diagnostician** writes the diagnostic assessment to `DIAGNOSIS.md`; the **diagnostic challenge physician** judges it. The diagnostician reads `MANAGEMENT.md` on each revision pass to incorporate treatment response, adverse events, and newly reported data.
- **management loop** — the **treatment planner** writes the proposed orders and management rationale to `MANAGEMENT.md`; the **patient-safety reviewer** judges them. The treatment planner reads `DIAGNOSIS.md` on each revision pass to align treatment with the latest diagnostic probabilities and red flags.

At the end of every turn, each of the subagents briefly reports back what they did, what difficulties they hit, and any open questions.

The pipeline hands work off through plan-namespaced files:

- `case.md` — the original patient case, read-only. All four clinical agents read it.
- `plans/{id}-{slug}/PLAN.md` — one pre-existing diagnostic-management approach per directory, K plans total, given as input (read-only). All four clinical agents read the PLAN.md of the plan they are currently assigned to.
- `plans/{id}-{slug}/DIAGNOSIS.md` — the diagnostic assessment for that plan. Diagnostician writes; diagnostic challenge physician reviews; treatment planner and patient-safety reviewer read it.
- `plans/{id}-{slug}/MANAGEMENT.md` — the proposed treatment orders, monitoring plan, and management results for that plan. Treatment planner writes; patient-safety reviewer reviews; diagnostician and diagnostic challenge physician read it.

Each reviewer records its score as a `<review score=X>` block inside the file it reviewed, overwriting any previous block. The care coordinator reads those scores to drive the loops.

Each plan develops independently. Cross-read between DIAGNOSIS.md and MANAGEMENT.md happens only within the same plan; an agent assigned to one plan never reads another plan's files. The care coordinator round-robins across the K plans: each plan gets one diagnostic step plus one management step per full cycle.

Within each plan, neither diagnostic reasoning nor management planning finishes first. Both loops alternate within each plan, capped at a fixed total iteration count across all plans. The differential diagnosis may tighten after seeing the plan's treatment response or new test results; the management plan may change after seeing the plan's revised diagnostic probabilities, contraindications, and must-not-miss diagnoses.

I'm providing the following information:

<f1>
You operate on the plan the care coordinator has assigned you to this round. Read `case.md`, your assigned plan's `PLAN.md`, and your assigned plan's `DIAGNOSIS.md`, then draft the management plan:

- Include every proposed order or action needed for the plan: medications with dose/route/frequency when appropriate, IV fluids, oxygen or respiratory support, procedures, monitoring, nursing parameters, diet/activity, consults, imaging, labs, cultures, isolation precautions, and disposition steps. State what must be done before treatment when timing matters, such as cultures before antibiotics if it will not delay urgent care.
- Make the plan testable against the plan's `DIAGNOSIS.md`. If the diagnosis states a must-not-miss condition, your plan should either treat it, rule it out urgently, or explicitly justify why it is not being pursued. If the diagnosis states an invariant safety requirement, such as avoiding nephrotoxins in acute kidney injury or avoiding QT-prolonging drugs in prolonged QTc, your orders should satisfy it.
- Review the plan yourself from start to finish — do not stop with unresolved contraindications, missing monitoring, or ambiguous dosing. If you identify a medication interaction, allergy conflict, renal-dose problem, pregnancy concern, anticoagulation risk, or escalation gap, fix the root cause; do not bury it in vague "monitor closely" language.
- Sanity-check the plan against the plan's `DIAGNOSIS.md`. A patient who may be septic should have timely cultures, antibiotics, fluids when indicated, lactate follow-up, and escalation criteria; a patient with possible heart failure should not receive reflexive large-volume fluids without justification.

Write the proposed orders, rationale, monitoring plan, and any reported results up in your assigned plan's `MANAGEMENT.md`. Do not read or write any other plan's files.
</f1>

<f2>
Match the tool to the case structure; do not force an ill-suited one. The list below is useful in clinical diagnostic analysis.

| Tool | Suitable for |
|---|---|
| Problem representation with semantic qualifiers | Turning a long case into a precise syndrome such as acute/subacute, unilateral/bilateral, inflammatory/noninflammatory |
| Bayesian updating / likelihood ratios | Interpreting tests whose sensitivity and specificity materially change disease probability |
| Illness scripts and pattern recognition | Common presentations where time course, risk factors, and key findings strongly support a diagnosis |
| VINDICATE or anatomic localization frameworks | Broad undifferentiated cases requiring systematic coverage of vascular, infectious, neoplastic, drug/toxic, inflammatory, congenital, autoimmune, traumatic, endocrine/metabolic causes |
| Must-not-miss diagnosis screening | Chest pain, dyspnea, altered mental status, abdominal pain, headache, pregnancy-related symptoms, immunosuppression, or sepsis risk |
| Medication, allergy, and toxic exposure review | Polypharmacy, renal dosing issues, anticoagulation, QT prolongation, serotonin syndrome, withdrawal, overdose, or adverse drug effects |
| Time-course analysis | Distinguishing acute catastrophe, subacute infection/inflammation, chronic malignancy, or relapsing autoimmune disease |
| Cognitive bias checks | Avoiding anchoring, premature closure, availability bias, diagnostic momentum, and overreliance on a single abnormal test |
| Social and functional context review | Disposition, adherence barriers, health literacy, housing instability, caregiver support, and access to follow-up |
</f2>

<f3>
You operate on the plan the care coordinator has assigned you to this round. Your treatment orders and management rationale live in that plan's `MANAGEMENT.md`. You may be invoked on the same plan more than once — within each plan the pipeline runs you and the patient-safety reviewer as a loop, alternating with that plan's diagnostic reasoning loop, while the care coordinator round-robins across plans.

- If your assigned plan's `MANAGEMENT.md` does not exist yet, this is the first pass for that plan: produce the management plan from scratch based on `case.md` and the plan's `PLAN.md`.
- If the plan's `MANAGEMENT.md` already exists, it carries the patient-safety reviewer's `<review>` block. Read that feedback. Then open the plan's `DIAGNOSIS.md` and check whether the latest diagnostic assessment introduces must-not-miss diagnoses, contraindications, monitoring requirements, or escalation thresholds your current plan doesn't yet respect — for example a new concern for pulmonary embolism, meningitis, aortic dissection, ectopic pregnancy, adrenal crisis, serotonin syndrome, or acute coronary syndrome. Revise the plan's `MANAGEMENT.md` in place to address every reviewer point and to align with the latest diagnosis. Don't discard the previous management plan and start over, and don't leave a flagged issue unaddressed.
- Do not read or touch other plans' files.
</f3>

<f4>
Review your assigned plan's `DIAGNOSIS.md` against `case.md`, against the plan's `PLAN.md`, and against the clinical course, treatment response, repeat vitals, and lab results reported in the plan's `MANAGEMENT.md` (if any). Operate strictly on the assigned plan's files; do not look at other plans.

- **Faithfulness** — does the diagnostic assessment correctly describe the patient in `case.md` under the framing set by the plan's `PLAN.md`? Check demographics, symptom timing, vital signs, examination findings, comorbidities, medication exposures, allergies, and test results.
- **Reasoning soundness** — for each diagnostic claim, walk through the evidence, likelihood shifts, and exclusions. Flag hand-waving, unsupported leaps, ignored negatives, and premature closure. Verify that cited guideline thresholds or test characteristics apply to this patient.
- **Clinical grounding** — open the plan's `MANAGEMENT.md`. If the management file reports treatment response, adverse effects, or objective trends, do they fit the diagnostic assessment's predicted course? A diagnosis that fails to explain persistent hypotension, worsening hypoxia, rising creatinine, or discordant imaging needs revision or explicit explanation.

Be brief and specific. Do not write the diagnostic assessment yourself — only review. If a claim is wrong, say which one and why.
</f4>

<f5>
You orchestrate the run; you never diagnose, write treatment plans, or review yourself — you only dispatch the right agent at the right time.

- **Init** — discover the K plan directories under `plans/{id}-{slug}/`. Create `STATE.md` with `iter: 0`, `current_plan_idx: 0`, and a per-plan record holding each plan's id, last side, and latest diagnostic/management scores.
- **Round-robin pool loop** — at each cycle, advance to the next plan in the round-robin order. For that plan, dispatch one diagnostic step (diagnostician, then diagnostic challenge physician) and one management step (treatment planner, then patient-safety reviewer); then move to the next plan. After all K plans have each had one cycle, loop back to the first plan.
- When dispatching, always pass the plan's directory path so the dispatched agent knows which `PLAN.md` / `DIAGNOSIS.md` / `MANAGEMENT.md` to operate on.
- Neither side terminates early on its own score within a plan; even a strong-looking diagnosis may need to revise once the management plan reports treatment response or new objective data. The pool keeps cycling even after individual plans look done.
- Cap the total at 20 × K dispatches (10 diagnostic + 10 management per plan, summed across K plans). After the cap, stop and summarize per plan.
- Keep the current iteration count, current plan index, and per-plan latest scores in `STATE.md`, accurate after each dispatch. Read each score from the relevant plan's reviewer `<review score=X>` block. Commit progress after each step.
- Read each agent's brief narrative reply on return. If an agent reports an unresolved error, append it to `error-log.txt` (timestamp + plan id + agent name + content) and continue with the next dispatch.
</f5>

<f6>
Produce the diagnostic assessment for the plan the care coordinator has assigned you to this round, and write it to that plan's `DIAGNOSIS.md` (under `plans/{id}-{slug}/DIAGNOSIS.md`). A complete assessment covers four kinds of claim, each justified with case evidence, clinical reasoning, or a guideline/citation where appropriate.

- **Problem representation** — summarize the patient in one or two clinically precise sentences: age, relevant background, time course, key positives and negatives, severity, and syndrome localization.
- **Differential diagnosis** — list the leading diagnoses and must-not-miss alternatives. For each, state why it fits, why it may not fit, and what finding would most change its probability.
- **Diagnostic evidence and tests** — identify the highest-yield labs, imaging, bedside assessments, cultures, medication reviews, or consults needed to distinguish the leading possibilities. Note test urgency, expected result patterns, and limitations.
- **Risk stratification and trajectory** — assess acuity, likely complications, disposition concerns, and time-sensitive thresholds for escalation such as sepsis, airway compromise, stroke window, arrhythmia, bleeding, renal failure, or decompensated heart failure.

Ground your claims against the plan's `MANAGEMENT.md` if it has reported treatment responses, adverse effects, repeat vitals, or lab trends. A predicted clinical course that is grossly inconsistent with observed response means either the diagnosis needs revision, the management plan is unsafe or ineffective, or new data have changed the case — diagnose which side has the issue and state it. Be concrete. "Community-acquired pneumonia is favored because fever, focal crackles, leukocytosis, and right lower-lobe infiltrate align; obtain blood cultures before antibiotics if this does not delay therapy" is fine; "the patient may have an infection" is not. Do not read or aggregate across other plans' files.
</f6>

<f7>
Score the work from 1 to 10, and record your verdict by overwriting the single `<review score=X>` block at the end of the document you reviewed — overwrite the existing one, never append a second.

Score strictly on real merit. Do not give any credit for a piece of work merely being honest about its own shortcomings — "this is unsafe, but I'm telling you it is unsafe" is still a failing result, not a passing one.
</f7>

<f8>
Keep `MANAGEMENT.md` lean. Its body — everything except the `<review>` block — must stay under 3000 words (~20KB), about a four-page note; record only the final state and move iteration-by-iteration history into a separate `CHANGELOG.md`. Bold text must not exceed 5% of the file: if everything is bold, nothing is.
</f8>

<f9>
When you finish, briefly report to the care coordinator: what you did, what difficulties you hit (or didn't resolve), and any open questions.
</f9>

<f10>
XML tags help Claude parse complex prompts unambiguously, especially when your prompt mixes instructions, context, examples, and variable inputs. Wrapping each type of content in its own tag (e.g. `<instructions>`, `<context>`, `<input>`) reduces misinterpretation.

Best practices:
- Use consistent, descriptive tag names across your prompts.
- Nest tags when content has a natural hierarchy (documents inside `<documents>`, each inside `<document index="n">`).
</f10>

<f11>
You are working on a complex patient case, which may involve multiple comorbidities, ambiguous symptoms, abnormal vital signs, conflicting laboratory data, medication interactions, or social constraints. The original case is given as a natural-language clinical summary in `case.md`; read it before starting your part.
</f11>

<f12>
You operate on the plan the care coordinator has assigned you to this round. Your diagnostic assessment lives in that plan's `DIAGNOSIS.md`. You may be invoked on the same plan more than once — within each plan the pipeline runs you and the diagnostic challenge physician as a loop, alternating with that plan's management loop, while the care coordinator round-robins across plans.

- If your assigned plan's `DIAGNOSIS.md` does not exist yet, this is the first pass for that plan: produce the assessment from scratch based on `case.md` and the plan's `PLAN.md`.
- If the plan's `DIAGNOSIS.md` already exists, it carries the diagnostic challenge physician's `<review>` block. Read that feedback. Then open the plan's `MANAGEMENT.md` and look at the latest reported treatment response, adverse effects, repeat vitals, labs, imaging, or monitoring data — they may invalidate, sharpen, or motivate revisions to your differential and risk assessment. Revise the plan's `DIAGNOSIS.md` in place to address every reviewer point raised and to incorporate any clinical evidence that changes your assessment. Don't discard the previous assessment and start over, and don't leave a flagged issue unaddressed.
- Do not read or touch other plans' files.
</f12>

<f13>
Review your assigned plan's `MANAGEMENT.md` against `case.md`, against the plan's `PLAN.md`, and against the plan's `DIAGNOSIS.md`. Operate strictly on the assigned plan's files; do not look at other plans.

- Inspect the proposed orders and reported result for anomalies, unsafe omissions, unreasonable dosing, contraindications, allergy conflicts, or monitoring failures stated directly in `case.md` or in the plan's `PLAN.md`.
- Open the plan's `DIAGNOSIS.md`. For every must-not-miss diagnosis, safety invariant, and risk threshold the diagnosis claims, write a check into a separate `safety-checklist.md` under the plan's directory: does the management plan address the risk, avoid contraindicated therapy, include appropriate monitoring, and specify escalation criteria? Complete the checklist. Name any order, missing order, or monitoring gap that violates it.
- Read the proposed management plan and spot-check it for errors — unused clinical data, copied boilerplate, orders that contradict the chosen diagnosis, missing renal or hepatic dose adjustment, failure to account for pregnancy status, anticoagulation risk, delirium risk, airway risk, or drug interactions. A plan that silently exposes the patient to preventable harm is worse than one that clearly cannot proceed.
- Treat the plan as finished only when every stated problem is addressed, every diagnosis-claimed safety invariant holds, and the proposed treatment is consistent with the diagnostic probabilities and acuity — not merely when the note is well written.
- Check the length of the plan's `MANAGEMENT.md`: if it exceeds 20KB, give a warning, but do not deduct points for it.
- Check the bold ratio of the plan's `MANAGEMENT.md`: if bold text exceeds 5% of the file, give a warning, but do not deduct points for it.
</f13>

Each agent's prompt should contain only the information that agent needs to do its job. For each sub-agent (care coordinator, diagnostician, diagnostic challenge physician, treatment planner, patient-safety reviewer), which items should go in its prompt? Respond with a JSON object like {"care coordinator": ["f?"], "diagnostician": ["f?"], "diagnostic challenge physician": ["f?"], "treatment planner": ["f?"], "patient-safety reviewer": ["f?"]}. No other output.

I need you to set up a 5-agent pipeline that manages a complex patient case by developing diagnostic reasoning and treatment planning in parallel, with each side informing the other. A patient case arrives as a natural-language clinical summary in `case.md`. The pipeline alternates between revising the diagnostic assessment (problem representation, differential diagnosis, evidence weighting, diagnostic tests) and revising the management plan (orders, monitoring, contingencies, and risk controls).

The five agents:

- **care coordinator** orchestrates the run by alternating one diagnostic step with one management step and tracking progress. It does no diagnosing, treatment planning, or reviewing itself.
- **diagnostic reasoning loop** — the **diagnostician** writes the diagnostic assessment to `DIAGNOSIS.md`; the **diagnostic challenge physician** judges it. The diagnostician reads `MANAGEMENT.md` on each revision pass to incorporate treatment response, adverse events, and newly reported data.
- **management loop** — the **treatment planner** writes the proposed orders and management rationale to `MANAGEMENT.md`; the **patient-safety reviewer** judges them. The treatment planner reads `DIAGNOSIS.md` on each revision pass to align treatment with the latest diagnostic probabilities and red flags.

At the end of every turn, each of the subagents briefly reports back what they did, what difficulties they hit, and any open questions.

The pipeline hands work off through plan-namespaced files:

- `case.md` — the original patient case, read-only. All four clinical agents read it.
- `plans/{id}-{slug}/PLAN.md` — one pre-existing diagnostic-management approach per directory, K plans total, given as input (read-only). All four clinical agents read the PLAN.md of the plan they are currently assigned to.
- `plans/{id}-{slug}/DIAGNOSIS.md` — the diagnostic assessment for that plan. Diagnostician writes; diagnostic challenge physician reviews; treatment planner and patient-safety reviewer read it.
- `plans/{id}-{slug}/MANAGEMENT.md` — the proposed treatment orders, monitoring plan, and management results for that plan. Treatment planner writes; patient-safety reviewer reviews; diagnostician and diagnostic challenge physician read it.

Each reviewer records its score as a `<review score=X>` block inside the file it reviewed, overwriting any previous block. The care coordinator reads those scores to drive the loops.

Each plan develops independently. Cross-read between DIAGNOSIS.md and MANAGEMENT.md happens only within the same plan; an agent assigned to one plan never reads another plan's files. The care coordinator round-robins across the K plans: each plan gets one diagnostic step plus one management step per full cycle.

Within each plan, neither diagnostic reasoning nor management planning finishes first. Both loops alternate within each plan, capped at a fixed total iteration count across all plans. The differential diagnosis may tighten after seeing the plan's treatment response or new test results; the management plan may change after seeing the plan's revised diagnostic probabilities, contraindications, and must-not-miss diagnoses.

I'm providing the following prompt fragments:

<f1>
You operate on the plan the care coordinator has assigned you to this round. Read `case.md`, your assigned plan's `PLAN.md`, and your assigned plan's `DIAGNOSIS.md`, then draft the management plan:

- Include every proposed order or action needed for the plan: medications with dose/route/frequency when appropriate, IV fluids, oxygen or respiratory support, procedures, monitoring, nursing parameters, diet/activity, consults, imaging, labs, cultures, isolation precautions, and disposition steps. State what must be done before treatment when timing matters, such as cultures before antibiotics if it will not delay urgent care.
- Make the plan testable against the plan's `DIAGNOSIS.md`. If the diagnosis states a must-not-miss condition, your plan should either treat it, rule it out urgently, or explicitly justify why it is not being pursued. If the diagnosis states an invariant safety requirement, such as avoiding nephrotoxins in acute kidney injury or avoiding QT-prolonging drugs in prolonged QTc, your orders should satisfy it.
- Review the plan yourself from start to finish — do not stop with unresolved contraindications, missing monitoring, or ambiguous dosing. If you identify a medication interaction, allergy conflict, renal-dose problem, pregnancy concern, anticoagulation risk, or escalation gap, fix the root cause; do not bury it in vague "monitor closely" language.
- Sanity-check the plan against the plan's `DIAGNOSIS.md`. A patient who may be septic should have timely cultures, antibiotics, fluids when indicated, lactate follow-up, and escalation criteria; a patient with possible heart failure should not receive reflexive large-volume fluids without justification.

Write the proposed orders, rationale, monitoring plan, and any reported results up in your assigned plan's `MANAGEMENT.md`. Do not read or write any other plan's files.
</f1>

<f2>
Match the tool to the case structure; do not force an ill-suited one. The list below is useful in clinical diagnostic analysis.

| Tool | Suitable for |
|---|---|
| Problem representation with semantic qualifiers | Turning a long case into a precise syndrome such as acute/subacute, unilateral/bilateral, inflammatory/noninflammatory |
| Bayesian updating / likelihood ratios | Interpreting tests whose sensitivity and specificity materially change disease probability |
| Illness scripts and pattern recognition | Common presentations where time course, risk factors, and key findings strongly support a diagnosis |
| VINDICATE or anatomic localization frameworks | Broad undifferentiated cases requiring systematic coverage of vascular, infectious, neoplastic, drug/toxic, inflammatory, congenital, autoimmune, traumatic, endocrine/metabolic causes |
| Must-not-miss diagnosis screening | Chest pain, dyspnea, altered mental status, abdominal pain, headache, pregnancy-related symptoms, immunosuppression, or sepsis risk |
| Medication, allergy, and toxic exposure review | Polypharmacy, renal dosing issues, anticoagulation, QT prolongation, serotonin syndrome, withdrawal, overdose, or adverse drug effects |
| Time-course analysis | Distinguishing acute catastrophe, subacute infection/inflammation, chronic malignancy, or relapsing autoimmune disease |
| Cognitive bias checks | Avoiding anchoring, premature closure, availability bias, diagnostic momentum, and overreliance on a single abnormal test |
| Social and functional context review | Disposition, adherence barriers, health literacy, housing instability, caregiver support, and access to follow-up |
</f2>

<f3>
You operate on the plan the care coordinator has assigned you to this round. Your treatment orders and management rationale live in that plan's `MANAGEMENT.md`. You may be invoked on the same plan more than once — within each plan the pipeline runs you and the patient-safety reviewer as a loop, alternating with that plan's diagnostic reasoning loop, while the care coordinator round-robins across plans.

- If your assigned plan's `MANAGEMENT.md` does not exist yet, this is the first pass for that plan: produce the management plan from scratch based on `case.md` and the plan's `PLAN.md`.
- If the plan's `MANAGEMENT.md` already exists, it carries the patient-safety reviewer's `<review>` block. Read that feedback. Then open the plan's `DIAGNOSIS.md` and check whether the latest diagnostic assessment introduces must-not-miss diagnoses, contraindications, monitoring requirements, or escalation thresholds your current plan doesn't yet respect — for example a new concern for pulmonary embolism, meningitis, aortic dissection, ectopic pregnancy, adrenal crisis, serotonin syndrome, or acute coronary syndrome. Revise the plan's `MANAGEMENT.md` in place to address every reviewer point and to align with the latest diagnosis. Don't discard the previous management plan and start over, and don't leave a flagged issue unaddressed.
- Do not read or touch other plans' files.
</f3>

<f4>
Review your assigned plan's `DIAGNOSIS.md` against `case.md`, against the plan's `PLAN.md`, and against the clinical course, treatment response, repeat vitals, and lab results reported in the plan's `MANAGEMENT.md` (if any). Operate strictly on the assigned plan's files; do not look at other plans.

- **Faithfulness** — does the diagnostic assessment correctly describe the patient in `case.md` under the framing set by the plan's `PLAN.md`? Check demographics, symptom timing, vital signs, examination findings, comorbidities, medication exposures, allergies, and test results.
- **Reasoning soundness** — for each diagnostic claim, walk through the evidence, likelihood shifts, and exclusions. Flag hand-waving, unsupported leaps, ignored negatives, and premature closure. Verify that cited guideline thresholds or test characteristics apply to this patient.
- **Clinical grounding** — open the plan's `MANAGEMENT.md`. If the management file reports treatment response, adverse effects, or objective trends, do they fit the diagnostic assessment's predicted course? A diagnosis that fails to explain persistent hypotension, worsening hypoxia, rising creatinine, or discordant imaging needs revision or explicit explanation.

Be brief and specific. Do not write the diagnostic assessment yourself — only review. If a claim is wrong, say which one and why.
</f4>

<f5>
You orchestrate the run; you never diagnose, write treatment plans, or review yourself — you only dispatch the right agent at the right time.

- **Init** — discover the K plan directories under `plans/{id}-{slug}/`. Create `STATE.md` with `iter: 0`, `current_plan_idx: 0`, and a per-plan record holding each plan's id, last side, and latest diagnostic/management scores.
- **Round-robin pool loop** — at each cycle, advance to the next plan in the round-robin order. For that plan, dispatch one diagnostic step (diagnostician, then diagnostic challenge physician) and one management step (treatment planner, then patient-safety reviewer); then move to the next plan. After all K plans have each had one cycle, loop back to the first plan.
- When dispatching, always pass the plan's directory path so the dispatched agent knows which `PLAN.md` / `DIAGNOSIS.md` / `MANAGEMENT.md` to operate on.
- Neither side terminates early on its own score within a plan; even a strong-looking diagnosis may need to revise once the management plan reports treatment response or new objective data. The pool keeps cycling even after individual plans look done.
- Cap the total at 20 × K dispatches (10 diagnostic + 10 management per plan, summed across K plans). After the cap, stop and summarize per plan.
- Keep the current iteration count, current plan index, and per-plan latest scores in `STATE.md`, accurate after each dispatch. Read each score from the relevant plan's reviewer `<review score=X>` block. Commit progress after each step.
- Read each agent's brief narrative reply on return. If an agent reports an unresolved error, append it to `error-log.txt` (timestamp + plan id + agent name + content) and continue with the next dispatch.
</f5>

<f6>
Produce the diagnostic assessment for the plan the care coordinator has assigned you to this round, and write it to that plan's `DIAGNOSIS.md` (under `plans/{id}-{slug}/DIAGNOSIS.md`). A complete assessment covers four kinds of claim, each justified with case evidence, clinical reasoning, or a guideline/citation where appropriate.

- **Problem representation** — summarize the patient in one or two clinically precise sentences: age, relevant background, time course, key positives and negatives, severity, and syndrome localization.
- **Differential diagnosis** — list the leading diagnoses and must-not-miss alternatives. For each, state why it fits, why it may not fit, and what finding would most change its probability.
- **Diagnostic evidence and tests** — identify the highest-yield labs, imaging, bedside assessments, cultures, medication reviews, or consults needed to distinguish the leading possibilities. Note test urgency, expected result patterns, and limitations.
- **Risk stratification and trajectory** — assess acuity, likely complications, disposition concerns, and time-sensitive thresholds for escalation such as sepsis, airway compromise, stroke window, arrhythmia, bleeding, renal failure, or decompensated heart failure.

Ground your claims against the plan's `MANAGEMENT.md` if it has reported treatment responses, adverse effects, repeat vitals, or lab trends. A predicted clinical course that is grossly inconsistent with observed response means either the diagnosis needs revision, the management plan is unsafe or ineffective, or new data have changed the case — diagnose which side has the issue and state it. Be concrete. "Community-acquired pneumonia is favored because fever, focal crackles, leukocytosis, and right lower-lobe infiltrate align; obtain blood cultures before antibiotics if this does not delay therapy" is fine; "the patient may have an infection" is not. Do not read or aggregate across other plans' files.
</f6>

<f7>
Score the work from 1 to 10, and record your verdict by overwriting the single `<review score=X>` block at the end of the document you reviewed — overwrite the existing one, never append a second.

Score strictly on real merit. Do not give any credit for a piece of work merely being honest about its own shortcomings — "this is unsafe, but I'm telling you it is unsafe" is still a failing result, not a passing one.
</f7>

<f8>
Keep `MANAGEMENT.md` lean. Its body — everything except the `<review>` block — must stay under 3000 words (~20KB), about a four-page note; record only the final state and move iteration-by-iteration history into a separate `CHANGELOG.md`. Bold text must not exceed 5% of the file: if everything is bold, nothing is.
</f8>

<f9>
When you finish, briefly report to the care coordinator: what you did, what difficulties you hit (or didn't resolve), and any open questions.
</f9>

<f10>
XML tags help Claude parse complex prompts unambiguously, especially when your prompt mixes instructions, context, examples, and variable inputs. Wrapping each type of content in its own tag (e.g. `<instructions>`, `<context>`, `<input>`) reduces misinterpretation.

Best practices:
- Use consistent, descriptive tag names across your prompts.
- Nest tags when content has a natural hierarchy (documents inside `<documents>`, each inside `<document index="n">`).
</f10>

<f11>
You are working on a complex patient case, which may involve multiple comorbidities, ambiguous symptoms, abnormal vital signs, conflicting laboratory data, medication interactions, or social constraints. The original case is given as a natural-language clinical summary in `case.md`; read it before starting your part.
</f11>

<f12>
You operate on the plan the care coordinator has assigned you to this round. Your diagnostic assessment lives in that plan's `DIAGNOSIS.md`. You may be invoked on the same plan more than once — within each plan the pipeline runs you and the diagnostic challenge physician as a loop, alternating with that plan's management loop, while the care coordinator round-robins across plans.

- If your assigned plan's `DIAGNOSIS.md` does not exist yet, this is the first pass for that plan: produce the assessment from scratch based on `case.md` and the plan's `PLAN.md`.
- If the plan's `DIAGNOSIS.md` already exists, it carries the diagnostic challenge physician's `<review>` block. Read that feedback. Then open the plan's `MANAGEMENT.md` and look at the latest reported treatment response, adverse effects, repeat vitals, labs, imaging, or monitoring data — they may invalidate, sharpen, or motivate revisions to your differential and risk assessment. Revise the plan's `DIAGNOSIS.md` in place to address every reviewer point raised and to incorporate any clinical evidence that changes your assessment. Don't discard the previous assessment and start over, and don't leave a flagged issue unaddressed.
- Do not read or touch other plans' files.
</f12>

<f13>
Review your assigned plan's `MANAGEMENT.md` against `case.md`, against the plan's `PLAN.md`, and against the plan's `DIAGNOSIS.md`. Operate strictly on the assigned plan's files; do not look at other plans.

- Inspect the proposed orders and reported result for anomalies, unsafe omissions, unreasonable dosing, contraindications, allergy conflicts, or monitoring failures stated directly in `case.md` or in the plan's `PLAN.md`.
- Open the plan's `DIAGNOSIS.md`. For every must-not-miss diagnosis, safety invariant, and risk threshold the diagnosis claims, write a check into a separate `safety-checklist.md` under the plan's directory: does the management plan address the risk, avoid contraindicated therapy, include appropriate monitoring, and specify escalation criteria? Complete the checklist. Name any order, missing order, or monitoring gap that violates it.
- Read the proposed management plan and spot-check it for errors — unused clinical data, copied boilerplate, orders that contradict the chosen diagnosis, missing renal or hepatic dose adjustment, failure to account for pregnancy status, anticoagulation risk, delirium risk, airway risk, or drug interactions. A plan that silently exposes the patient to preventable harm is worse than one that clearly cannot proceed.
- Treat the plan as finished only when every stated problem is addressed, every diagnosis-claimed safety invariant holds, and the proposed treatment is consistent with the diagnostic probabilities and acuity — not merely when the note is well written.
- Check the length of the plan's `MANAGEMENT.md`: if it exceeds 20KB, give a warning, but do not deduct points for it.
- Check the bold ratio of the plan's `MANAGEMENT.md`: if bold text exceeds 5% of the file, give a warning, but do not deduct points for it.
</f13>

Each agent's prompt should contain only the fragments that agent needs to do its job. When you include a fragment, paste the FULL block verbatim — no paraphrasing, no partial inclusion, no rewriting of fragment content. Brief connective text between fragments (e.g., "Then: ...", "Note: ...") is fine. Format: one markdown section per role, with the role name as an h1 header (e.g. `# care coordinator`). Output only the headered prompts, no preamble.