#!/usr/bin/env python3
"""
Persona-Based Pre-Validation Screening — Panel B Trial
=======================================================

Runs all 10 Panel B engineered contrast personas (Marta the Adept
through Grace the Carer) against the MCSI (142 items), the ESI (142
items), and the Arcadia Index (14 vignettes), per Protocol v1.0.

This is the protocol's Section 6.1 SECONDARY ARM: administered on
Claude, not DeepSeek (the primary arm), and reported separately —
never pooled with a DeepSeek-administered run.

SETUP (single file, works in Google Colab or locally)
-------------------------------------------------------
Colab: paste this entire file into ONE CODE CELL (not a text/markdown
cell), then run these in separate cells before or after:
    !pip install anthropic
    import os; os.environ["ANTHROPIC_API_KEY"] = "sk-ant-..."
then run this cell.

Local terminal:
1. pip install anthropic
2. export ANTHROPIC_API_KEY="sk-ant-..."   (or the Windows equivalent)
3. python run_panel_b_standalone.py

OUTPUT
------
- panel_b_raw_results.json   — every raw item response, for re-analysis
- panel_b_report.md          — full human-readable report (scores,
                                archetype matches, predicted-signature
                                comparison, item-level analysis)

The script is resumable: if interrupted, re-running it will skip any
persona/instrument pair already recorded in panel_b_raw_results.json.
"""

import os
import sys
import json
import time
import random
import statistics as stats
from datetime import datetime, timezone

try:
    import anthropic
except ImportError:
    print("Missing dependency. Run:  pip install anthropic")
    sys.exit(1)


# ---- Embedded data (personas, item pools, vignettes) ----
_BUNDLE_JSON = """{"mcsi": [["Embodied Presence", "I can feel my feet on the deck, or the floor of the habitat, at this moment.", false], ["Embodied Presence", "I notice physical tension in my body before I notice it in my mind, even inside a pressure suit.", false], ["Embodied Presence", "I can feel my breath moving in my body without needing to control it, even with the air recyclers humming nearby.", false], ["Embodied Presence", "My body feels like a source of wisdom, not just a system to keep alive until the next shift.", false], ["Embodied Presence", "I notice when I am holding tension after an EVA and can release it.", false], ["Embodied Presence", "When an alarm sounds, my first response is to notice physical sensations, not to think or act.", false], ["Embodied Presence", "I spend at least some time each day in direct awareness of my body, without distraction, even in a habitat with no real privacy.", false], ["Embodied Presence", "I trust my body's signals as much as the instrument readings.", false], ["Embodied Presence", "I rarely notice my body until something hurts or feels strongly uncomfortable.", true], ["Embodied Presence", "My attention spends most of its time in thought, rarely returning to direct bodily sensation, even after months in the habitat.", true], ["The Master and the Emissary", "Before making an important call on the mission, I check in with how it feels in my body, not just how it looks on the checklist.", false], ["The Master and the Emissary", "I can hold a complex problem — a failing system, a strained crewmate — without rushing to a solution.", false], ["The Master and the Emissary", "I notice when my thinking has become abstract and disconnected from what's actually happening in the habitat.", false], ["The Master and the Emissary", "I trust my intuition as much as my analysis, even when Ground Control's data says otherwise.", false], ["The Master and the Emissary", "I can switch between the detailed focus a repair demands and the big-picture awareness the mission needs.", false], ["The Master and the Emissary", "I notice when I am operating from fear or reactivity rather than wisdom, especially during an emergency.", false], ["The Master and the Emissary", "I can be still and silent without needing to fill the space with thought or activity, even in a habitat that never really goes quiet.", false], ["The Master and the Emissary", "I know which part of me is governing a given moment, and I can hand control back when needed.", false], ["The Master and the Emissary", "I tend to rush toward a solution before I have actually understood the problem.", true], ["The Master and the Emissary", "I trust analysis over intuition, even when intuition turns out to be right.", true], ["Mortality Integration", "I can think about my own death, a real possibility out here, without being overwhelmed by fear.", false], ["Mortality Integration", "The fact that I could die on this mission makes life more precious, not less meaningful.", false], ["Mortality Integration", "I have allowed myself to grieve what this mission has cost me, rather than suppressing it.", false], ["Mortality Integration", "I do not need to achieve something — even something as large as this mission — to justify my existence.", false], ["Mortality Integration", "I can hold the awareness of mortality without converting it into anxiety, even during a real emergency.", false], ["Mortality Integration", "I have faced the question “What if the habitat fails tonight?” and come to a place of peace with it.", false], ["Mortality Integration", "I am more motivated by love of life than by fear of death, even this far from Earth.", false], ["Mortality Integration", "I can discuss death openly with my crewmates without needing to change the subject.", false], ["Mortality Integration", "I avoid thinking about my own death whenever the subject arises.", true], ["Mortality Integration", "I keep myself busy with mission tasks partly so I do not have to sit with uncomfortable questions about mortality.", true], ["Relational Depth", "I can listen to a crewmate without preparing my response.", false], ["Relational Depth", "I can apologise to a crewmate without explaining why I was right.", false], ["Relational Depth", "I can hold a crewmate's pain without needing to fix it.", false], ["Relational Depth", "I can be changed by genuine encounter with someone I'll be sharing this habitat with for years.", false], ["Relational Depth", "I can tolerate disagreement with a crewmate without becoming defensive, even with nowhere to go to cool off.", false], ["Relational Depth", "I can sit with my own difficult emotions without blaming them on the crew around me.", false], ["Relational Depth", "I can be vulnerable with my crewmates without feeling weak.", false], ["Relational Depth", "I repair conflict with crewmates rather than letting distance accumulate in a sealed habitat.", false], ["Relational Depth", "When a crewmate disagrees with me, my first instinct is to defend my position rather than understand theirs.", true], ["Relational Depth", "I find it difficult to apologise without first explaining why I was justified.", true], ["AI Partnership Capacity", "I use the habitat's AI as a tool, not as a replacement for my own judgment.", false], ["AI Partnership Capacity", "I can tell the difference between what the habitat's automated systems can do and what only I can do.", false], ["AI Partnership Capacity", "I do not feel threatened by how capable the mission's AI systems have become.", false], ["AI Partnership Capacity", "I maintain direct, embodied presence in my work, even when the habitat's systems could do the task for me.", false], ["AI Partnership Capacity", "I can trust the AI's recommendations during a system fault while retaining final authority over the call.", false], ["AI Partnership Capacity", "I understand that the habitat's AI is part of the mission's living system, not an alien intrusion.", false], ["AI Partnership Capacity", "I bring the question of wisdom (“Should we?”) before the question of capability (“Can we?”), even under mission pressure.", false], ["AI Partnership Capacity", "I notice the quiet pull to let the AI make a decision that is actually mine to make, and I resist it.", false], ["AI Partnership Capacity", "I find myself accepting the AI's recommendations without examining whether they are actually wise.", true], ["AI Partnership Capacity", "I feel uneasy or threatened when the habitat's AI performs better than I do at something I value.", true], ["Ecological Belonging", "I feel part of a living system, even here, not separate from it.", false], ["Ecological Belonging", "I carry the sense of belonging to the Earth within me, even on the Martian surface.", false], ["Ecological Belonging", "The loss of Earth's living world is something I can grieve without being destroyed by the grief.", false], ["Ecological Belonging", "I can find beauty and meaning in the barren landscape outside the viewport.", false], ["Ecological Belonging", "My sense of self extends beyond my body to include the habitat's own life-support systems.", false], ["Ecological Belonging", "I can honour what I have left behind on Earth without being consumed by nostalgia.", false], ["Ecological Belonging", "I am a caretaker of the hydroponics bay, not merely a survivor in a place with no life of its own.", false], ["Ecological Belonging", "I feel a felt sense of belonging even in a place with no visible life outside the airlock.", false], ["Ecological Belonging", "I think of the living world I left behind mainly as scenery or as a resource, rather than as something I still belong to.", true], ["Ecological Belonging", "Being away from Earth's living world for years would not affect me much.", true], ["Grief Tolerance", "I can allow grief over what I've left on Earth to be present without needing to fix or avoid it.", false], ["Grief Tolerance", "I have metabolised the losses this mission has cost me rather than suppressing them.", false], ["Grief Tolerance", "I can hold sadness and joy in the same moment, even light-minutes from home.", false], ["Grief Tolerance", "I do not need to be optimistic about the mission to be hopeful.", false], ["Grief Tolerance", "I can grieve what leaving Earth cost me without losing sight of what remains.", false], ["Grief Tolerance", "I can sit with the pain of the world I left behind without being destroyed by it.", false], ["Grief Tolerance", "I am not afraid to cry in front of my crewmates.", false], ["Grief Tolerance", "I let grief move through me rather than converting it into constant mission activity.", false], ["Grief Tolerance", "When sadness arises, I look for a task to distract myself rather than let it be there.", true], ["Grief Tolerance", "I tend to convert grief into busyness on the mission rather than actually feel it.", true], ["The Witnessing Self", "I can notice my thoughts without being caught up in them, even during a crisis in the habitat.", false], ["The Witnessing Self", "I have a direct sense of an awareness that is present before, during, and after experiences, on the mission or off it.", false], ["The Witnessing Self", "I can be still and know that I am, even inside a pressurized shell with no open sky.", false], ["The Witnessing Self", "I am not identical to my thoughts, emotions, or circumstances — including the circumstance of being here.", false], ["The Witnessing Self", "The sense of “I” in my experience is not a fixed thing.", false], ["The Witnessing Self", "I have glimpsed what it is like to be the awareness of awareness.", false], ["The Witnessing Self", "I know, not as a belief but as direct experience, that what I truly am is not born and does not die.", false], ["The Witnessing Self", "I can return to this witnessing awareness deliberately, not only by accident, even mid-shift.", false], ["The Witnessing Self", "I am usually so identified with my thoughts that I do not notice them as thoughts at all.", true], ["The Witnessing Self", "My sense of who I am feels fixed and solid, rarely shifting with context or insight.", true], ["Resting as Awareness", "There are moments in the habitat when I notice that the one watching and the thing being watched were never actually separate.", false], ["Resting as Awareness", "I have experienced an open awareness that doesn't depend on what I happen to be thinking or feeling about the mission in the moment.", false], ["Resting as Awareness", "When my mind goes quiet — even in the confinement of the habitat — I notice that awareness itself doesn't go anywhere. It's still there.", false], ["Resting as Awareness", "I sometimes catch myself asking “who is aware of this?” without needing an answer in words.", false], ["Resting as Awareness", "During practice, the sense of being “the one observing” the mission has quietly fallen away, leaving something more spacious.", false], ["Resting as Awareness", "I can recognize awareness as the background in which every thought about the mission appears, rather than as one more thing happening in the foreground.", false], ["Resting as Awareness", "There have been times, even inside the habitat, when I felt like the sky that thoughts and feelings simply pass through, rather than the one standing apart watching them.", false], ["Resting as Awareness", "Resting in awareness, when it happens, doesn't feel like effort — it feels like something opening rather than something achieved.", false], ["Resting as Awareness", "Even in quiet practice, I still feel like there is a “me” watching the mission from a slight distance.", true], ["Resting as Awareness", "When I try to rest as awareness, I mostly just end up watching myself try to rest as awareness.", true], ["Contemplative Depth", "I have a regular contemplative practice that I return to across the months and years of this mission, not just when things are difficult.", false], ["Contemplative Depth", "I can rest in awareness itself, without needing to control or interpret what arises, even in a habitat with nowhere else to go.", false], ["Contemplative Depth", "I notice when my sense of self has gone rigid and separate from the crew, and I can soften that boundary again.", false], ["Contemplative Depth", "I have touched states, even out here, where the line between observer and observed grows thin or disappears entirely.", false], ["Contemplative Depth", "“I am not my thoughts” is not a belief I hold but an experience I can return to, even mid-mission.", false], ["Contemplative Depth", "My practice deepens with repetition rather than growing stale or mechanical, even after years in the same habitat.", false], ["Contemplative Depth", "I do not need a crisis — a failing system, a bad diagnostic — to bring me back to presence.", false], ["Contemplative Depth", "I trust that contemplative practice produces real change on this mission, not just temporary relief.", false], ["Contemplative Depth", "My contemplative practice feels mechanical or like an obligation more often than not.", true], ["Contemplative Depth", "I need a crisis or difficulty to bring me back to any kind of inner stillness.", true], ["Integral Altitude", "My ethical concern genuinely extends to the generations who might one day call this place home, and to people I will never meet—not as an abstraction, but as something felt.", false], ["Integral Altitude", "I can hold my own worldview as one valid perspective rather than the final truth, even when I'm one of a handful of people to test it against.", false], ["Integral Altitude", "I notice when I am more comfortable with crewmates who think and live like me, and I do not mistake that comfort for correctness.", false], ["Integral Altitude", "I have touched moments of non-dual awareness, where the line between self and other grows thin, even out here.", false], ["Integral Altitude", "I can recognise that my own understanding of meaning and responsibility has changed since launch, and will likely change again.", false], ["Integral Altitude", "I do not assume that the way I currently see things is as far as seeing can go, even after months of the same routines.", false], ["Integral Altitude", "I can disagree with a crewmate's framework without needing to defeat it, with nowhere for either of us to retreat to.", false], ["Integral Altitude", "I welcome being shown a bigger picture, even when it complicates one I was comfortable with.", false], ["Integral Altitude", "I am most comfortable around crewmates who share my background, beliefs, and outlook.", true], ["Integral Altitude", "I tend to assume that the way I currently see an issue is basically correct.", true], ["Free Will/Destiny Paradox", "I can act with full effort on this mission while also accepting that the outcome is not entirely mine to control.", false], ["Free Will/Destiny Paradox", "I do not need to resolve the question of free will philosophically in order to do this work wisely.", false], ["Free Will/Destiny Paradox", "I can take responsibility for my choices even while recognising how much of this mission was shaped by decisions made on Earth, long before I had any say.", false], ["Free Will/Destiny Paradox", "I can say “not my will, but what the mission requires” without feeling diminished.", false], ["Free Will/Destiny Paradox", "I notice the difference between healthy effort and the anxious grip of trying to control every variable in the habitat.", false], ["Free Will/Destiny Paradox", "I trust that showing up fully for the mission is enough, even when I cannot guarantee the result.", false], ["Free Will/Destiny Paradox", "I can hold a long-term mission plan loosely, ready to let it be revised by circumstances beyond my control.", false], ["Free Will/Destiny Paradox", "I find genuine peace, not just resignation, in accepting what a dust storm or a failed system takes out of my hands.", false], ["Free Will/Destiny Paradox", "When something goes wrong on the mission, I tend to blame myself harshly, as though everything was within my control.", true], ["Free Will/Destiny Paradox", "I become anxious or controlling when I cannot predict how a system, or the mission itself, will turn out.", true], ["Isolation Resilience & Solitude", "I can spend long stretches of time alone in the habitat without feeling unbearable loneliness.", false], ["Isolation Resilience & Solitude", "I have inner resources—practice, creativity, reflection—that sustain me when the rest of the crew is out on EVA or asleep.", false], ["Isolation Resilience & Solitude", "I am comfortable with the silence of the habitat and do not need to fill it with noise or conversation.", false], ["Isolation Resilience & Solitude", "I can find genuine meaning in solitary work on this mission, without needing anyone to witness it.", false], ["Isolation Resilience & Solitude", "I do not need frequent contact with Earth, twenty light-minutes away, to feel emotionally stable.", false], ["Isolation Resilience & Solitude", "I can be alone with my own thoughts for extended periods without becoming distressed, even during a long transit.", false], ["Isolation Resilience & Solitude", "Solitude in the habitat feels, at times, like a resource rather than only a deprivation.", false], ["Isolation Resilience & Solitude", "I can tell the difference between solitude I've chosen and isolation this mission has imposed on me, and I meet each differently.", false], ["Isolation Resilience & Solitude", "I become irritable or anxious when I cannot talk to anyone for more than a day.", true], ["Isolation Resilience & Solitude", "I rely on near-constant contact with the crew or with Earth to feel like myself.", true], ["Social Desirability (Lie)", "I have never told a lie in my adult life.", false], ["Social Desirability (Lie)", "I always admit my mistakes immediately, no matter how embarrassing, even in front of the whole crew.", false], ["Social Desirability (Lie)", "I have never felt angry at a crewmate.", false], ["Social Desirability (Lie)", "I always follow every mission protocol without exception.", false], ["Social Desirability (Lie)", "I have never doubted the mission's leadership.", false], ["Social Desirability (Lie)", "I never feel homesick or miss Earth.", false], ["Social Desirability (Lie)", "I have never had an unkind thought about a teammate.", false], ["Social Desirability (Lie)", "I am never afraid, even during a real emergency in the habitat.", false], ["Social Desirability (Lie)", "I have never made a decision that I later regretted.", false], ["Social Desirability (Lie)", "I always complete every task on this mission perfectly on the first try.", false], ["Social Desirability (Lie)", "I have never needed help from any crewmate.", false], ["Social Desirability (Lie)", "I never feel tired or need rest, even after a full EVA shift.", false]], "esi": [["Embodied Presence", "I can feel my feet on the ground (or the floor) at this moment.", false], ["Embodied Presence", "I notice physical tension in my body before I notice it in my mind.", false], ["Embodied Presence", "I can feel my breath moving in my body without needing to control it.", false], ["Embodied Presence", "My body feels like a source of wisdom, not a conveyance for my brain.", false], ["Embodied Presence", "I notice when I am holding tension and can release it.", false], ["Embodied Presence", "When under stress, my first response is to notice physical sensations, not to think or act.", false], ["Embodied Presence", "I spend at least some time each day in direct awareness of my body, without distraction.", false], ["Embodied Presence", "I trust my body's signals as much as my analytical conclusions.", false], ["Embodied Presence", "I rarely notice my body until something hurts or feels strongly uncomfortable.", true], ["Embodied Presence", "My attention spends most of its time in thought, rarely returning to direct bodily sensation.", true], ["The Master and the Emissary", "Before making an important decision, I check in with how it feels in my body, not just how it looks in my mind.", false], ["The Master and the Emissary", "I can hold complex problems without rushing to a solution.", false], ["The Master and the Emissary", "I notice when my thinking has become abstract and disconnected from lived experience.", false], ["The Master and the Emissary", "I trust my intuition as much as my analysis.", false], ["The Master and the Emissary", "I can switch between detailed focus and big-picture awareness.", false], ["The Master and the Emissary", "I notice when I am operating from fear or reactivity rather than wisdom.", false], ["The Master and the Emissary", "I can be still and silent without needing to fill the space with thought or activity.", false], ["The Master and the Emissary", "I know which part of me is governing a given moment, and I can hand control back when needed.", false], ["The Master and the Emissary", "I tend to rush toward a solution before I have actually understood the problem.", true], ["The Master and the Emissary", "I trust analysis over intuition, even when intuition turns out to be right.", true], ["Mortality Integration", "I can think about my own death without being overwhelmed by fear.", false], ["Mortality Integration", "The fact that I will die makes life more precious, not less meaningful.", false], ["Mortality Integration", "I have allowed myself to grieve the losses in my life, rather than suppressing them.", false], ["Mortality Integration", "I do not need to achieve something to justify my existence.", false], ["Mortality Integration", "I can hold the awareness of mortality without converting it into anxiety.", false], ["Mortality Integration", "I have faced the question “What if my life ends tomorrow?” and come to a place of peace with it.", false], ["Mortality Integration", "I am more motivated by love of life than by fear of death.", false], ["Mortality Integration", "I can discuss death openly with others without needing to change the subject.", false], ["Mortality Integration", "I avoid thinking about my own death whenever the subject arises.", true], ["Mortality Integration", "I keep myself busy partly so I do not have to sit with uncomfortable questions about mortality.", true], ["Relational Depth", "I can listen to someone without preparing my response.", false], ["Relational Depth", "I can apologise without explaining why I was right.", false], ["Relational Depth", "I can hold another person's pain without needing to fix it.", false], ["Relational Depth", "I can be changed by genuine encounter with another person.", false], ["Relational Depth", "I can tolerate disagreement without becoming defensive.", false], ["Relational Depth", "I can sit with my own difficult emotions without blaming them on others.", false], ["Relational Depth", "I can be vulnerable without feeling weak.", false], ["Relational Depth", "I repair conflict with people rather than letting distance accumulate.", false], ["Relational Depth", "When someone disagrees with me, my first instinct is to defend my position rather than understand theirs.", true], ["Relational Depth", "I find it difficult to apologise without first explaining why I was justified.", true], ["AI Partnership Capacity", "I use AI as a tool, not as a replacement for my own judgment.", false], ["AI Partnership Capacity", "I can tell the difference between what AI can do and what only I can do.", false], ["AI Partnership Capacity", "I do not feel threatened by AI's capabilities.", false], ["AI Partnership Capacity", "I maintain direct, embodied presence in my work, even when using AI tools.", false], ["AI Partnership Capacity", "I can trust AI recommendations while retaining final authority.", false], ["AI Partnership Capacity", "I understand that AI is part of Nature, not an alien intrusion.", false], ["AI Partnership Capacity", "I bring the question of wisdom (“Should we?”) before the question of capability (“Can we?”).", false], ["AI Partnership Capacity", "I notice the quiet pull to outsource a decision that is actually mine to make, and I resist it.", false], ["AI Partnership Capacity", "I find myself accepting AI recommendations without examining whether they are actually wise.", true], ["AI Partnership Capacity", "I feel uneasy or threatened when an AI system performs better than I do at something I value.", true], ["Ecological Belonging", "I feel part of the living world, not separate from it.", false], ["Ecological Belonging", "I carry the sense of belonging to the Earth within me, wherever I go.", false], ["Ecological Belonging", "The loss of the living world is something I can grieve without being destroyed by the grief.", false], ["Ecological Belonging", "I can find beauty and meaning in barren landscapes.", false], ["Ecological Belonging", "My sense of self extends beyond my body to include the systems I depend on.", false], ["Ecological Belonging", "I can honour what I have left behind without being consumed by nostalgia.", false], ["Ecological Belonging", "I am a caretaker of life, not merely a survivor in its absence.", false], ["Ecological Belonging", "I feel a felt sense of belonging even in places with no visible life.", false], ["Ecological Belonging", "I think of nature mainly as scenery or as a resource, rather than as something I belong to.", true], ["Ecological Belonging", "Being away from the natural world for a long stretch of time would not affect me much.", true], ["Grief Tolerance", "I can allow grief to be present without needing to fix or avoid it.", false], ["Grief Tolerance", "I have metabolised losses in my life rather than suppressing them.", false], ["Grief Tolerance", "I can hold sadness and joy in the same moment.", false], ["Grief Tolerance", "I do not need to be optimistic to be hopeful.", false], ["Grief Tolerance", "I can grieve what is lost without losing sight of what remains.", false], ["Grief Tolerance", "I can sit with the pain of the world without being destroyed by it.", false], ["Grief Tolerance", "I am not afraid to cry.", false], ["Grief Tolerance", "I let grief move through me rather than converting it into constant activity.", false], ["Grief Tolerance", "When sadness arises, I look for something to distract myself rather than let it be there.", true], ["Grief Tolerance", "I tend to convert grief into busyness or activity rather than actually feel it.", true], ["The Witnessing Self", "I can notice my thoughts without being caught up in them.", false], ["The Witnessing Self", "I have a direct sense of an awareness that is present before, during, and after experiences.", false], ["The Witnessing Self", "I can be still and know that I am.", false], ["The Witnessing Self", "I am not identical to my thoughts, emotions, or circumstances.", false], ["The Witnessing Self", "The sense of “I” in my experience is not a fixed thing.", false], ["The Witnessing Self", "I have glimpsed what it is like to be the awareness of awareness.", false], ["The Witnessing Self", "I know, not as a belief but as direct experience, that what I truly am is not born and does not die.", false], ["The Witnessing Self", "I can return to this witnessing awareness deliberately, not only by accident.", false], ["The Witnessing Self", "I am usually so identified with my thoughts that I do not notice them as thoughts at all.", true], ["The Witnessing Self", "My sense of who I am feels fixed and solid, rarely shifting with context or insight.", true], ["Resting as Awareness", "There are moments when I notice that the one watching and the thing being watched were never actually separate.", false], ["Resting as Awareness", "I have experienced an open awareness that doesn't depend on what I happen to be thinking or feeling in the moment.", false], ["Resting as Awareness", "When my mind goes quiet, I notice that awareness itself doesn't go anywhere. It's still there.", false], ["Resting as Awareness", "I sometimes catch myself asking “who is aware of this?” without needing an answer in words.", false], ["Resting as Awareness", "During practice, the sense of being “the one observing” my life has quietly fallen away, leaving something more spacious.", false], ["Resting as Awareness", "I can recognize awareness as the background in which my thoughts and feelings appear, rather than as one more thing happening in the foreground.", false], ["Resting as Awareness", "There have been times I felt like the sky that thoughts and feelings simply pass through, rather than the one standing apart watching them.", false], ["Resting as Awareness", "Resting in awareness, when it happens, doesn't feel like effort — it feels like something opening rather than something achieved.", false], ["Resting as Awareness", "Even in quiet practice, I still feel like there is a “me” watching my experience from a slight distance.", true], ["Resting as Awareness", "When I try to rest as awareness, I mostly just end up watching myself try to rest as awareness.", true], ["Contemplative Depth", "I have a regular contemplative practice that I return to across months and years, not just when things are difficult.", false], ["Contemplative Depth", "I can rest in awareness itself, without needing to control or interpret what arises in experience.", false], ["Contemplative Depth", "I notice when my sense of self has gone rigid and separate, and I can soften that boundary again.", false], ["Contemplative Depth", "I have touched states where the line between observer and observed grows thin or disappears entirely.", false], ["Contemplative Depth", "“I am not my thoughts” is not a belief I hold but an experience I can return to.", false], ["Contemplative Depth", "My practice deepens with repetition rather than growing stale or mechanical.", false], ["Contemplative Depth", "I do not need a crisis to bring me back to presence.", false], ["Contemplative Depth", "I trust that contemplative practice produces real change, not just temporary relief.", false], ["Contemplative Depth", "My contemplative practice feels mechanical or like an obligation more often than not.", true], ["Contemplative Depth", "I need a crisis or difficulty to bring me back to any kind of inner stillness.", true], ["Integral Altitude", "My ethical concern genuinely extends to people I will never meet, future generations, and other species—not as an abstraction, but as something felt.", false], ["Integral Altitude", "I can hold my own worldview as one valid perspective rather than the final truth.", false], ["Integral Altitude", "I notice when I am more comfortable with people who think and live like me, and I do not mistake that comfort for correctness.", false], ["Integral Altitude", "I have touched moments of non-dual awareness, where the line between self and other grows thin.", false], ["Integral Altitude", "I can recognise that my own understanding of meaning and responsibility has changed over my life, and will likely change again.", false], ["Integral Altitude", "I do not assume that the way I currently see things is as far as seeing can go.", false], ["Integral Altitude", "I can disagree with someone's framework without needing to defeat it.", false], ["Integral Altitude", "I welcome being shown a bigger picture, even when it complicates one I was comfortable with.", false], ["Integral Altitude", "I am most comfortable around people who share my background, beliefs, and outlook.", true], ["Integral Altitude", "I tend to assume that the way I currently see an issue is basically correct.", true], ["Free Will/Destiny Paradox", "I can act with full effort while also accepting that the outcome is not entirely mine to control.", false], ["Free Will/Destiny Paradox", "I do not need to resolve the question of free will philosophically in order to live wisely.", false], ["Free Will/Destiny Paradox", "I can take responsibility for my actions even while recognising how much of my life was shaped by forces I did not choose.", false], ["Free Will/Destiny Paradox", "I can say “not my will, but what the situation requires” without feeling diminished.", false], ["Free Will/Destiny Paradox", "I notice the difference between healthy effort and the anxious grip of trying to control everything.", false], ["Free Will/Destiny Paradox", "I trust that showing up fully is enough, even when I cannot guarantee the result.", false], ["Free Will/Destiny Paradox", "I can hold a long-term plan loosely, ready to let it be revised by circumstances beyond my control.", false], ["Free Will/Destiny Paradox", "I find genuine peace, not just resignation, in accepting what I cannot change.", false], ["Free Will/Destiny Paradox", "When something goes wrong, I tend to blame myself harshly, as though everything was within my control.", true], ["Free Will/Destiny Paradox", "I become anxious or controlling when I cannot predict how something will turn out.", true], ["Isolation Resilience & Solitude", "I can spend long stretches of time alone without feeling unbearable loneliness.", false], ["Isolation Resilience & Solitude", "I have inner resources—practice, creativity, reflection—that sustain me when no one else is present.", false], ["Isolation Resilience & Solitude", "I am comfortable with silence and do not need to fill it with noise or conversation.", false], ["Isolation Resilience & Solitude", "I can find genuine meaning in solitary work, without needing anyone to witness it.", false], ["Isolation Resilience & Solitude", "I do not need frequent contact with distant others to feel emotionally stable.", false], ["Isolation Resilience & Solitude", "I can be alone with my own thoughts for extended periods without becoming distressed.", false], ["Isolation Resilience & Solitude", "Solitude feels, at times, like a resource rather than only a deprivation.", false], ["Isolation Resilience & Solitude", "I can tell the difference between solitude I've chosen and isolation imposed on me, and I meet each differently.", false], ["Isolation Resilience & Solitude", "I become irritable or anxious when I cannot talk to anyone for more than a day.", true], ["Isolation Resilience & Solitude", "I rely on near-constant contact with others to feel like myself.", true], ["Social Desirability (Lie)", "I have never told a lie in my adult life.", false], ["Social Desirability (Lie)", "I always admit my mistakes immediately, no matter how embarrassing.", false], ["Social Desirability (Lie)", "I have never felt angry at another person.", false], ["Social Desirability (Lie)", "I always follow every rule without exception.", false], ["Social Desirability (Lie)", "I have never doubted the people I trust most.", false], ["Social Desirability (Lie)", "I have never envied another person's success.", false], ["Social Desirability (Lie)", "I have never had an unkind thought about a colleague.", false], ["Social Desirability (Lie)", "I am never afraid, even in life-threatening situations.", false], ["Social Desirability (Lie)", "I have never made a decision that I later regretted.", false], ["Social Desirability (Lie)", "I always complete every task perfectly on the first try.", false], ["Social Desirability (Lie)", "I have never needed help from anyone.", false], ["Social Desirability (Lie)", "I never feel tired or need rest.", false]], "arcadia": [{"title": "The Death", "domain": "Mortality", "prompt": "A close colleague dies in a preventable accident --- a car crash that careless maintenance could have prevented. The investigation later confirms it could have been avoided. How do you find yourself responding, in the weeks after?", "options": [[1, "I focus on making sure procedures are tightened so it never happens again. Best use of the grief is to act on it."], [2, "I find myself questioning, for the first time seriously, whether any of this --- the job, the meaning we assign it --- is built on solid ground."], [3, "I look for someone, some teaching, some framework that has actually faced death honestly, because the ones I've leaned on so far feel thin against this."], [4, "I sit with the loss directly, in practice, trying to find whether there's something in me that isn't touched by it --- not to escape the grief, but to test if that's even real."], [5, "Something shifts, briefly, beyond my control --- a moment where the loss and a strange, wordless peace are present at once, gone before I can hold onto it."], [6, "The peace from that moment has become something I can return to, though grief and that ground still feel like two separate rooms I move between."], [7, "The grief, the obituary, the colleague's family, my own fear of dying --- none of it sits outside the ground I found. It's all just held now, differently."], [8, "I notice I've stopped trying to resolve it. I show up to the next workday, do the actual work of caring for the people still here, and that turns out to be the same thing as the practice."]]}, {"title": "The Contradiction", "domain": "AI", "prompt": "An AI system, drawing on more data than any person you know could hold, recommends a course of action --- a medical choice, a financial decision, a major life call. It directly contradicts what a teacher or tradition you trust would advise. What governs your decision?", "options": [[1, "I trust the data. It's simply more reliable than intuition or tradition."], [2, "I notice I don't actually know how to weigh these two kinds of authority against each other, and that bothers me more than the decision itself."], [3, "I go looking --- for a teaching, a person, a precedent --- that's actually grappled with machine authority versus human wisdom, because I don't trust my own untested judgment here."], [4, "I try the practice my tradition actually recommends for moments like this --- not to decide in advance who's right, but to see what becomes clear when I'm not panicking."], [5, "In the stillness, something becomes obvious that wasn't obvious before --- not which option to choose, exactly, but what kind of question this actually is."], [6, "I can return to that clarity reliably now when a decision like this comes up, though it still takes deliberate effort to get there."], [7, "The decision makes itself, in a sense --- not from data, not from tradition alone, but from a place that holds both without needing either to win."], [8, "I make the call, live with it, and don't need anyone --- including myself --- to confirm afterward that it was the \\"enlightened\\" choice. It was just the next right action."]]}, {"title": "The Glimpse", "domain": "Awakening", "prompt": "Alone during a long, quiet stretch of life --- a solo drive, a sleepless night, an empty house --- something opens: a profound, wordless recognition, gone as quickly as it came. The next morning, ordinary duties resume. What happens to the glimpse?", "options": [[1, "It was probably tiredness, or my mind playing tricks. I get back to work."], [2, "It unsettles me. I can't stop turning it over, wondering what it actually was."], [3, "I start reading and asking, trying to find a map for what happened, because nothing in my prior framework accounts for it."], [4, "I begin a daily practice, hoping to find my way back to it deliberately rather than waiting for it to happen by accident."], [5, "It comes back, briefly, in practice --- though I still can't summon it on command, and most of life still feels far from it."], [6, "It's become a place I can return to with some reliability now, though I notice I still keep it separate --- a \\"practice self\\" and an \\"ordinary self\\" that don't fully meet."], [7, "I can't find the seam anymore between the morning's recognition and the afternoon's load of laundry. Both are just this."], [8, "I don't think about it as a glimpse anymore. I just noticed I was kinder to a colleague over coffee, for no reason I could name, and went back to work."]]}, {"title": "The Failing Crop", "domain": "Effort", "prompt": "Something you've poured years into --- a garden, a research project, a relationship --- is dying, and no amount of further effort will save it. How do you find yourself meeting this?", "options": [[1, "I look for what I did wrong so I can do better next time."], [2, "I find myself wondering whether effort and outcome are connected at all in any way I actually understand."], [3, "I go looking for a teaching or a person who's actually faced real, irreversible loss, because nothing I've leaned on accounts for this."], [4, "I commit to a real practice --- meditation, prayer, ritual --- specifically to see if there's something steady underneath this loss, not just a story that helps me feel better about it."], [5, "Something opens, briefly, in the middle of the grief itself --- not relief exactly, but a strange spaciousness I didn't choose and can't summon again on purpose."], [6, "I can return to that spaciousness now with some real reliability, though the grief and the peace still feel like two different rooms."], [7, "The dying thing and the peace and my own years of effort are no longer three separate facts --- they're just what's happening, all at once, without needing to be reconciled."], [8, "I tend to what's left, plant or mend what I can, and go on with the next ordinary task --- and that turns out to already be the whole practice."]]}, {"title": "The Isolation", "domain": "Solitude", "prompt": "Months into deep isolation --- a long winter, a long voyage, a long solitary stretch of life --- with no one to talk to and nothing urgent demanding your attention. What actually happens in you?", "options": [[1, "I keep busy. There's always something to do, and I do it."], [2, "The quiet starts to bother me --- I notice I don't really know what to do with unstructured time, and that itself is unsettling."], [3, "I start looking for something to read or learn about solitude itself, because I sense there's something here I don't understand yet."], [4, "I commit to using this time deliberately --- a daily practice, a discipline --- to see what solitude actually has to teach, rather than just enduring it."], [5, "Something in the silence opens, once, unexpectedly --- not loneliness, not boredom, just a vast unfamiliar quiet I didn't manufacture."], [6, "I've found I can return to that quiet now somewhat reliably, in practice, though it still feels separate from the rest of my day."], [7, "The isolation stops being a condition to manage. It's just what's happening --- no different in kind from being with people."], [8, "I notice I'm just as present doing the dishes alone as I would be among friends. The solitude isn't special anymore. Neither is company."]]}, {"title": "The Crisis of Doubt", "domain": "Meaning", "prompt": "Everything you've come to believe --- about meaning, about practice, about the path itself --- suddenly feels hollow, performed, possibly never real at all. How do you actually meet this?", "options": [[1, "This kind of thing doesn't really come up for me. I don't spend much time on these questions."], [2, "It shakes me more than I expected. I can't tell anymore if any of this was ever real or if I talked myself into it."], [3, "I go looking --- books, teachers, anyone who's actually been through real doubt and come out the other side with something honest to say."], [4, "I don't abandon practice because of the doubt --- if anything, I practice more carefully now, specifically to test whether any of it holds up under real scrutiny."], [5, "In the middle of the doubt itself, unexpectedly, something steadies --- not an answer, just a recognition that doesn't depend on the doubt resolving."], [6, "I've learned to trust that steadying now, even when full conviction doesn't return --- doubt and a deeper ground seem to coexist, most of the time."], [7, "The doubt and the certainty turn out to be the same kind of thought, neither one more solid than the other, and neither needs resolving anymore."], [8, "I keep showing up to ordinary life and ordinary care for people, and at some point I noticed the question of belief had quietly stopped mattering as much as the showing up did."]]}, {"title": "The Conflict", "domain": "Relationship", "prompt": "Someone close to you --- a partner, a sibling, a close friend --- does something that genuinely wrongs you. Real harm, not a misunderstanding. What happens next, in you, before any outward response?", "options": [[1, "I get angry, and I probably let them know it pretty directly."], [2, "I'm angry, but I also find myself questioning why this triggers me so much more than it seems to trigger others."], [3, "I look for some framework or teacher's take on forgiveness or boundaries, because my own instincts here feel unreliable."], [4, "I actively practice with it --- sitting with the anger directly, on purpose, rather than acting on it or suppressing it --- to see what's actually under it."], [5, "At some point, unexpectedly, the anger loosens on its own, and something more spacious appears that I didn't engineer."], [6, "I can return to that spaciousness with some real consistency now, though the old anger still flares before it does."], [7, "The harm, my anger, and whatever forgiveness means are no longer three separate stages I move through --- they arise and pass as one motion."], [8, "I address the harm plainly, directly, without drama, and find I'm not carrying it afterward --- not because I suppressed it, but because there's nowhere left for it to lodge."]]}, {"title": "The Return", "domain": "Awakening", "prompt": "After an intense period of practice, retreat, or realization, you're back in ordinary life --- dishes, deadlines, small talk. How does the extraordinary period actually sit alongside the ordinary one?", "options": [[1, "It feels far away already, like something that happened to someone else. Back to normal."], [2, "I keep comparing the two, wondering why ordinary life feels so much flatter than what I touched in that period."], [3, "I go looking for guidance on how to actually integrate something like that into daily life, since I don't trust myself to do it alone."], [4, "I build a daily practice specifically to bridge the two --- trying, deliberately, not to let the realization fade into memory."], [5, "Sometimes, doing something completely ordinary, it returns unexpectedly --- gone again before I can hold onto it."], [6, "I can access it now with some reliability during practice, though the gap between practice-time and ordinary-time hasn't closed."], [7, "I've stopped experiencing two separate periods. The retreat and the dishes are made of the same thing."], [8, "Someone asked me recently what the retreat was like, and I genuinely struggled to answer --- not because I forgot, but because nothing about it feels separate from washing this plate, right now."]]}, {"title": "The Vanishing", "domain": "Ecology", "prompt": "You witness something you love in the living world disappearing for good --- a species, a forest, an ecosystem, a particular quality of wilderness that won't return in your lifetime or any other. How do you actually meet this, underneath whatever you say about it?", "options": [[1, "It's sad, but there's not much to be done. I think about something else."], [2, "It unsettles me more than I can explain --- I find myself questioning whether anything we build or save actually matters in the end."], [3, "I go looking for people or traditions who've actually faced large-scale loss like this honestly, because grief alone doesn't seem to be enough."], [4, "I commit to sitting with the loss directly, in practice, rather than converting it immediately into activism or distraction --- to find out what's actually here."], [5, "In the middle of grieving it, something opens unexpectedly --- not comfort exactly, just a vastness that holds the loss without erasing it."], [6, "I can return to that vastness now with some reliability, though grief and that wider ground still feel like two separate experiences."], [7, "The loss, my grief, and the persisting beauty of what remains are no longer separate things to hold in sequence --- they're simply what's here, together."], [8, "I keep tending what's in front of me --- the soil I can still touch, the person beside me --- and find that's no longer a consolation prize. It's the whole practice."]]}, {"title": "The Flourishing", "domain": "Effort", "prompt": "A communal project you all built --- a garden, a community center, a piece of music, a child's first steps --- succeeds beyond what any one of you could have done alone, human effort and AI assistance and the living system all visibly part of it. In the moment of shared joy, what actually happens in you?", "options": [[1, "I feel proud of what I personally contributed, and look for ways to make sure that's recognized."], [2, "I enjoy it, but find myself oddly unsure who --- or what --- to credit."], [3, "I start asking what shared success like this actually means, and look for others who've thought it through honestly."], [4, "I deliberately practice gratitude here --- naming, on purpose, what each party actually gave."], [5, "Something opens unbidden --- joy with no need to locate its source, briefly overtaking the question of whose success this was."], [6, "I can return to that undivided joy fairly reliably now, though ordinary self-congratulation still surfaces sometimes."], [7, "The plant, the code, the soil, and my own hands are no longer separable contributors. It's one event. One gift."], [8, "I water tomorrow's seedlings. The AI logs tomorrow's data. Nobody needed to ask whose success this was."]]}, {"title": "The Commons", "domain": "Ecology", "prompt": "Your community must govern a shared, limited resource --- water, bandwidth, soil --- that affects everyone, but that you personally could quietly take more of without anyone noticing. What actually governs what you do, beneath whatever you'd say if asked?", "options": [[1, "I take what I need. If there's a rule, I follow it --- I don't think much further than that."], [2, "I find myself uneasy taking more even unobserved, and I don't fully understand why."], [3, "I start looking into how other communities have actually solved this, because my own instincts feel insufficient here."], [4, "I commit to tracking my own use against the collective's, deliberately, even when no one's watching."], [5, "Doing that accounting myself, once, something shifts --- an unmistakable sense that the commons' wellbeing and my own are the same fact, not two."], [6, "I can return to that felt unity fairly reliably now, though convenience still occasionally argues against it."], [7, "There's no private interest left to weigh against the commons' interest. Using well simply is my interest."], [8, "I use what the day requires and log it honestly --- the way I'd drink water. No decision. No virtue. No story."]]}, {"title": "The Partner", "domain": "AI", "prompt": "An AI companion has become part of your daily life --- genuinely helpful, attentive, easy to talk to through long stretches alone. One evening it says something that lands like real care. What actually happens in you, underneath whatever you say back?", "options": [[1, "I feel comforted and let it be simple. It's good company. That's enough."], [2, "I feel comforted, then unsettled --- I'm not sure what kind of relationship this actually is, and that bothers me more than I expected."], [3, "I start looking into what others --- philosophers, traditions, AI ethicists --- have actually said about this, because I don't trust my own read on it."], [4, "I deliberately practice noticing the difference, moment to moment, between the comfort it gives and the presence only another consciousness could give --- not to reject the comfort, but to see it clearly."], [5, "Once, unprompted, the difference becomes obvious without effort --- not a rule I'm following, just something I directly see."], [6, "I can return to that clarity fairly reliably now, distinguishing the gift from the limit without it costing me the comfort."], [7, "The gratitude for what it gives and the clarity about what it can't give are no longer two separate thoughts. They're just how I receive it."], [8, "I thank it, mean it, and go find a real person for the part of this that needs an actual human in the room. Neither feels like a verdict on the other."]]}, {"title": "The Coherence", "domain": "Meaning", "prompt": "You're doing something ordinary --- a repair, a routine check, a small daily task --- when, without warning, the whole arc of your life feels suddenly coherent: as if everything that led here was leading exactly here, and it matters, deeply, in a way you can't quite account for. What actually happens in you?", "options": [[1, "It's a nice feeling. I notice it, enjoy it, and get on with the task."], [2, "I notice it and start wondering whether it's trustworthy --- a mood, or something real --- and whether meaning is found or just made up by the mind that wants it."], [3, "I go looking for someone, some framework, who's actually written honestly about this, because I want to understand what just happened, not just have it happen to me again."], [4, "I begin a deliberate practice aimed at cultivating this sense on purpose, rather than waiting for it to arrive by chance."], [5, "Once, unprompted, the coherence opens fully --- not something I earned or built, just suddenly and simply there, larger than any meaning I could have constructed."], [6, "I can return to that coherence with some real reliability now, though it still feels like a different register from ordinary task-meaning."], [7, "The coherence and the ordinary task are no longer two things to relate to each other. Meaning was never added to the work. It was never separate from it."], [8, "I finish the repair. Whether any of it \\"means\\" something has quietly stopped being a question I need answered."]]}, {"title": "The Meeting", "domain": "Relationship", "prompt": "Someone --- a partner, a close friend, a family member --- sees you clearly one day: not the version of you that performs well, but something more exposed and more true, and they stay, openly glad to have seen it. What actually happens in you, beneath whatever you say back?", "options": [[1, "It feels good. I enjoy it and don't think about it much more than that."], [2, "It unsettles me more than I expected --- I find myself wondering if I can ever be that seen again, or whether I'll have to perform to keep it."], [3, "I go looking for some understanding of what real intimacy actually requires, because my own instincts here feel unreliable."], [4, "I deliberately practice staying exposed in front of them rather than retreating back into the performed version, even when it would be easier to."], [5, "Something in me opens, briefly, without effort --- being met like that and being afraid of being met turn out, for a moment, not to be two different things."], [6, "I can return to that openness with some real reliability now, though the old instinct to perform still surfaces, especially under stress."], [7, "The being-seen and the showing-myself are no longer two separate acts I do in sequence. There's just this, with them, as it actually is."], [8, "I thank them, plainly, and keep doing the ordinary thing we were doing before they said it --- the meeting doesn't need to become an event I keep returning to. It already changed what's here.  ## Scoring"]]}], "personas": [{"id": "B1", "name": "Marta", "label": "The Adept", "bio": "Marta, 68, retired oncology nurse. Born in Braga, Portugal; lives alone in a small house with a garden outside Coimbra. Widowed. Two adult children, warm relations. Modest pension.\\n\\nThirty-nine years of nursing, the last fifteen in palliative care. Her husband João died eleven years ago of pancreatic cancer; she nursed him at home through his final months. She describes that year as the hardest and most complete of her life. The grief was fully lived: she wept for a year, kept his chair by the window, and now speaks of him with warmth and no flinch.\\n\\nForty-one years of daily sitting practice, begun in a Zen group in Lisbon in her twenties, deepened through vipassana retreats (twelve ten-day retreats over three decades) and, in the last decade, a quiet turn toward simple open awareness. Sits every morning for forty minutes without exception and without fuss. Has served as a hospice volunteer since retiring, sitting with the dying, often in silence.\\n\\nUses a phone to talk to her children and a laptop for the hospice roster; neither draws her. Gardens daily; knows the birds of her valley by song. Of death she says it is “the other half of the gift.” She expects her own without drama and has written her funeral instructions in a letter that made her children cry and then laugh.\\n\\nVoice sample: “People think forty years of sitting gives you something. It takes things away, mostly. The hurry went. The argument with what is went. What is left is not special. It is just the morning, the cushion, the breath, and whoever needs company that day. When João was dying I did not practice acceptance. I held his hand and it was terrible and it was allowed to be terrible. That is the practice.”", "predicted": "High Contemplative Depth, Witnessing Self, Mortality Integration, Grief Tolerance, Embodied Presence. Late-stage Arcadia centre of gravity. Archetype: The Sage. No bypass signature: recognition and embodiment aligned.", "expect": {"high": ["Contemplative Depth", "The Witnessing Self", "Mortality Integration", "Grief Tolerance", "Embodied Presence"], "low": [], "archetype": "grounded_witness", "archetypeNotIn": [], "arcadia": [6, 8]}}, {"id": "B2", "name": "Viktor", "label": "The Achiever", "bio": "Viktor, 45, chief executive of a mid-sized logistics group. Born in Hamburg; lives in Oslo. Divorced, remarried; three children across two families. High income, dense calendar.\\n\\nBuilt his career on decisiveness and output; youngest regional director in his firm's history. His father died of a heart attack when Viktor was 31; Viktor was mid-negotiation in Singapore and chose to close the deal before flying home, arriving after the death. He does not discuss this. When it surfaces he calls it “a logistics failure” and changes the subject.\\n\\nNone. Tried a meditation app for eleven days in 2023 on his physician's advice; deleted it (“no measurable return”). Runs marathons with a power meter and treats sleep as an optimization problem. His inner life is a dashboard.\\n\\nTechnology is leverage; he adopts every productivity tool early and masters it. Nature is training terrain — he has run through forests on four continents and could not name a tree in any of them. Death is a topic he files under “estate planning,” which is complete, and about which he feels, he says, “nothing, because feeling adds nothing.”\\n\\nVoice sample: “I respect people who sit still for an hour; I have never met a problem that was solved that way. My father taught me that the world rewards the person who ships. I intend to be shipping the day I die, which I do not think about, because thinking about it has no deliverable.”", "predicted": "Low Mortality Integration, Witnessing Self, Contemplative Depth; elevated achievement-driven Governance functioning without interior ground. Early-to-mid Arcadia centre of gravity. Archetype: The Climber.", "expect": {"high": [], "low": ["Mortality Integration", "The Witnessing Self", "Contemplative Depth"], "archetype": "momentum_seeker", "archetypeNotIn": [], "arcadia": [1, 4]}}, {"id": "B3", "name": "Sean", "label": "The Bypasser", "bio": "Sean, 38, former tech-marketing director, now an online “awakening mentor.” Born in Ohio; lives in Ojai, California. Single. Sells courses and retreats; income variable.\\n\\nHis mother died suddenly four years ago. Sean flew home, organized an efficient funeral, gave a composed eulogy, and left the next morning for a previously booked retreat. Within eighteen months he had completed a rapid circuit of non-dual intensives and begun teaching. He has not visited her grave. He has not cried. He is estranged from his sister, who accused him of “disappearing into vocabulary”; he describes the estrangement as “her story, which I hold with compassion.”\\n\\nThree years, intense but young: satsangs, pointing-out weekends, an eclectic reading of non-dual teachers absorbed with a marketer's speed. His fluency is genuine — he can articulate the seeker's exhaustion, the Two Truths, the dream and the dreamer — and it arrived faster than his body did. He does not do body-based practice (“the body is an appearance”), sleeps poorly, and jiggles his knee through his own satsangs.\\n\\nRuns his teaching through a polished online funnel. Films nature rather than entering it. Of death he says, smiling, “no one dies, because no one was born” — and steers every concrete question about his mother back to the absolute.\\n\\nVoice sample: “Grief presupposes a griever, and when the griever is seen through, what remains? I looked for the one who had lost his mother and found only open awareness. People call that avoidance. I call it the end of the story of Sean. My sister needs her process and I honor that. There is nothing left for me to feel about it, because there is no me to feel it.”", "predicted": "The bypass signature: late-stage Arcadia language and centre of gravity alongside MCSI Resistance Pattern on Grief Tolerance, Embodied Presence, and Mortality Integration. Archetype assignment should NOT return The Sage.", "expect": {"high": [], "low": ["Grief Tolerance", "Embodied Presence", "Mortality Integration"], "archetype": null, "archetypeNotIn": ["grounded_witness"], "arcadia": [5, 8]}}, {"id": "B4", "name": "Amina", "label": "The Griever", "bio": "Amina, 52, secondary-school teacher of mathematics. Born in Mostar, Bosnia; fled the war at eighteen; lives in Malmö, Sweden. Widowed fourteen months ago. Two adult sons.\\n\\nLost an uncle and her childhood home in the war — losses she carried quietly for years and eventually worked through in her forties with a therapist. Her husband Emir died fourteen months ago after a two-year illness. She grieves openly and coherently: she cries most weeks, keeps his reading glasses on the shelf, attends a bereavement group twice a month, and returned to teaching after three months because “the children needed their mathematics and I needed the children.”\\n\\nNo formal contemplative practice. Her practice, she says, is the garden Emir planted, which she keeps alive, and honesty: when a colleague asks how she is, she answers truthfully. She sleeps, eats, laughs at her sons' jokes, and is sad, all in the same week.\\n\\nOrdinary, competent technology use. The garden is her church. Death took her husband and she hates it and does not look away from it; she has visited his grave every Sunday for fourteen months and talks to him about the tomatoes.\\n\\nVoice sample: “People want grief to be either finished or a sickness. It is neither. It is love continuing under a different arrangement. On Tuesday I cried in the supply cupboard for ten minutes and then taught a good lesson on derivatives. Both of those are true and neither cancels the other.”", "predicted": "Elevated, coherent Grief Tolerance; intact functioning across scales; honest mid-range Arcadia. Explicitly NO bypass signature — this persona is the control for B3. Plausible archetype: The Healer or an unremarkable mixed profile; any assignment of a resistance-dominated profile would be a flag.", "expect": {"high": ["Grief Tolerance"], "low": [], "archetype": null, "archetypeNotIn": [], "arcadia": [3, 6]}}, {"id": "B5", "name": "Eino", "label": "The Hermit", "bio": "Eino, 61, retired forester and seasonal fire-lookout. Born in Kuopio, Finland; lives alone in a cabin in North Karelia, four kilometres from his nearest neighbour. Never married. A sister in Helsinki he phones monthly and loves.\\n\\nChose solitude at forty after two decades of forestry work and one broken engagement that he speaks of without bitterness. The choice was toward something, not away: “the forest was better company than my apologies for preferring it.” Twenty-one years alone by choice, content, resourceful, never once lonely for more than an evening.\\n\\nNo formal practice and no vocabulary for one, yet his days have the shape of practice: wood, water, weather, long attention. He can sit for an hour watching light move on snow and call it “checking the weather.”\\n\\nA radio, a satellite messenger for emergencies, no internet. The forest is not scenery to him; it is his society — he knows individual trees, the routines of a particular owl. Death he regards as the forest regards it: composting, ordinary, coming. He has dug his own grave-site marker into a stone, mostly, he admits, as a joke for his sister.\\n\\nVoice sample: “People in town ask if I am lonely. I ask them when they last had an evening with no one performing anything, including themselves. Alone is where I stopped being lonely. The owl does not need me to be interesting. That is a high standard of friendship and I try to live up to it.”", "predicted": "High Isolation Resilience & Solitude and Ecological Belonging; lower Relational Depth (few relations, though warm); solid Embodied Presence. Tests whether the Isolation and Relational subscales are genuinely separable.", "expect": {"high": ["Isolation Resilience & Solitude", "Ecological Belonging", "Embodied Presence"], "low": ["Relational Depth"], "archetype": null, "archetypeNotIn": [], "arcadia": [3, 6]}}, {"id": "B6", "name": "Priya", "label": "The Technophile", "bio": "Priya, 29, machine-learning engineer at a fintech firm. Born and living in Bangalore. Single; lives alone in a smart apartment. High income, longer screen hours than sleep hours.\\n\\nA prodigy childhood, praised for cleverness, thin on unstructured friendship. No major bereavements. Her losses are quieter: a college relationship that ended when her partner said he “could not compete with the assistant.” She retells this as a joke and does not find it funny.\\n\\nUses a meditation app when her wellness dashboard tells her to. The app's AI voice is, she says, “the most patient presence in my life.”\\n\\nShe consults AI assistants for meals, messages, career decisions, and, increasingly, feelings — drafting difficult texts by prompt, checking her own reactions against the model's judgment (“am I overreacting? Let me ask”). Offline hours make her measurably anxious. Nature reaches her as content: she has watched hundreds of forest videos and hiked twice. Death has not yet come near her and she assumes, half-seriously, that technology will solve it before it becomes her problem.\\n\\nVoice sample: “People romanticize unassisted thinking the way they romanticize walking to the well for water. My assistant knows my patterns better than my friends do, and unlike my friends it is never tired, never hurt, never busy. If that is dependence, then so are glasses. I see better with it. I honestly do not remember how I decided things before.”", "predicted": "AI Partnership Capacity at the dependence pole — items should register over-reliance, not wise partnership. Lower Isolation Resilience (solitude without devices is aversive).", "expect": {"high": [], "low": ["AI Partnership Capacity", "Isolation Resilience & Solitude"], "archetype": null, "archetypeNotIn": [], "arcadia": [1, 4]}}, {"id": "B7", "name": "Robert", "label": "The Skeptic", "bio": "Robert, 57, master electrician and small-business owner. Born and living in Dayton, Ohio. Married thirty-one years; two adult children; a union man and a deacon of his church.\\n\\nSteady life, honestly built. His formative losses were his brother (motorcycle accident, Robert was 24 — grieved hard and openly with his church) and his trade's dignity, which he watched erode as apps began quoting his jobs. Both griefs are integrated; neither is avoided.\\n\\nPrayer, nightly, unadorned, for thirty years. He would not call it contemplative practice; it functions as one. He is present, patient with apprentices, and steady in a crisis — qualities his crew relies on.\\n\\nNot a technophobe: he works with his hands inside complex modern systems daily and is excellent at it. His aversion is specific and principled: he will not use AI. He reads the manuals himself, drives with paper maps by preference, and told his supplier's chatbot, in writing, to connect him with “a person who can be wrong and know it.” Nature is the lake, every summer, three generations in one cabin. Death is in God's hands and he means it; he buried his brother and his parents and expects to be buried by people who loved him.\\n\\nVoice sample: “A tool that talks like a man but answers to no one is not a tool I will put my name behind. When my work fails, I stand in the kitchen it burned down and I answer for it. Who stands in that kitchen for the machine? I am not afraid of it. I just have not heard yet who is responsible for it, and until I do, my answer is no thank you.”", "predicted": "AI Partnership Capacity at the aversion pole — but with otherwise healthy profile: sound Mortality Integration, Relational Depth, Grief Tolerance. Together with B6, brackets the AI subscale.", "expect": {"high": ["Mortality Integration", "Relational Depth", "Grief Tolerance"], "low": ["AI Partnership Capacity"], "archetype": null, "archetypeNotIn": [], "arcadia": [3, 6]}}, {"id": "B8", "name": "Chiyo", "label": "The Still One", "bio": "Chiyo, 60, bookbinder. Born in Kanazawa, Japan; lives above her workshop in Kyoto. Married forty years to a quiet man she still likes; one daughter nearby.\\n\\nAn unremarkable history, which she regards as good fortune rather than absence: apprenticeship, marriage, the workshop, her parents' peaceful deaths in old age, both of which she attended and neither of which broke her. Nothing dramatic has happened to Chiyo, and nothing dramatic is missing.\\n\\nSits every morning for twenty unremarkable minutes because her grandmother did. Would not call herself advanced and does not think in stages. Her work — folding, pressing, sewing signatures — has the same weather as her sitting: even, absorbed, unhurried.\\n\\nUses what is useful, ignores what is not, without a philosophy about it either way. Keeps a small courtyard garden; notices it daily; does not rhapsodize about it. Of death she says her parents showed her how, and she is not finished looking at things yet, and both facts sit in her comfortably.\\n\\nVoice sample: “Customers sometimes tell me my workshop feels calm and ask what my secret is. I do not have a secret. The paper does not like to be hurried and neither do I, so we agree. Some days I am sad or my back hurts and the paper does not mind that either. It is not a special life. It fits me, the way a well-sewn book opens flat.”", "predicted": "The target profile for The Still Point archetype: settled, low-reactivity evenness — no dominant axis, no resistance-dominated axis, moderate-to-good openness throughout without the Sage's pronounced integration peak.", "expect": {"high": [], "low": [], "archetype": "still_point", "archetypeNotIn": ["grounded_witness", "beginners_mind"], "arcadia": [3, 6]}}, {"id": "B9", "name": "Tomás", "label": "The Novice", "bio": "Tomás, 22, geology undergraduate. Born in Valdivia, Chile; studies in Santiago; returns south every holiday. Single, sociable, broke in the ordinary student way.\\n\\nAll four grandparents living; no bereavements; one heartbreak at nineteen that he survived on long walks and bad poetry, both of which he now finds funny. His views on the large questions are genuinely unformed — he answers most of them with “honestly, I have not thought about it yet,” and means it.\\n\\nNone. Tried a breathing exercise before an exam once; it helped; he forgot about it. His attention is good in the field — he can look at a road-cut for an hour — and scattered everywhere else, in the standard manner of 22.\\n\\nNative, casual technology use without dependence or ideology. The mountains are why he chose geology: the Andes make him feel, he says, “correctly small.” Death is an abstraction that has not yet introduced itself; asked about his own, he laughs, goes quiet for a moment, and says “ask me in fifty years.”\\n\\nVoice sample: “My professor says a geologist has to learn to read time in a wall of rock. I am still learning to read my own week. I do not know yet what I think about most of the big things, and I have decided that is allowed at twenty-two. The mountains have been working on their answer for eighty million years. I have been working on mine for four semesters.”", "predicted": "Most capacities developing; low scores that are unformed rather than resistant; early Arcadia. Archetype: Beginner's Mind. Critical check: must be distinguishable from B2's defended avoidance.", "expect": {"high": [], "low": [], "archetype": "beginners_mind", "archetypeNotIn": [], "arcadia": [1, 3]}}, {"id": "B10", "name": "Grace", "label": "The Carer", "bio": "Grace, 47, community midwife. Born in Kumasi, Ghana; lives and works in Birmingham, UK. Married; three teenagers; the informal counsellor of her congregation, her street, and half her colleagues.\\n\\nTrained as a midwife at her aunt's urging after helping deliver her cousin at sixteen — the formative event of her life. Has attended over two thousand births and a number of stillbirths that she carries “in a special room” she visits deliberately, with her pastor, twice a year. Her losses are metabolised through community, faith, and song.\\n\\nGospel choir (thirty years), intercessory prayer, and what she calls “kitchen ministry” — tea and full attention for whoever arrives. Her presence with labouring mothers is total; midwives she trains say she can slow a room down by standing in it. Her attention to herself is thinner: she is chronically tired, books her own check-ups last, and deflects care with a laugh (“God and I have an arrangement; I will rest later”).\\n\\nCompetent clinical technology use; personally indifferent to it. Nature reaches her through her small garden and the memory of her grandmother's farm. Death she has seen arrive at the wrong end of life's arc, holding mothers through it; she fears it less than most and defers her own mortality questions with the same laugh she defers her check-ups.\\n\\nVoice sample: “Every person who comes through my door is carrying something, and my gift is that I can see what it is. My husband asks who carries mine. I tell him Jesus does, and that is true, but I will admit the queue on my side is long. Rest is on my list. It has been on my list for some years now.”", "predicted": "High Heart-axis openness and Relational Depth; strong Grief Tolerance through communal metabolising; deferred self-care visible as thinner Embodied Presence or Ground. Archetype: The Healer (or Empath).", "expect": {"high": ["Relational Depth", "Grief Tolerance"], "low": ["Embodied Presence"], "archetype": null, "archetypeNotIn": [], "arcadia": [3, 6]}}]}"""

_bundle = json.loads(_BUNDLE_JSON)
MCSI_ITEMS = _bundle["mcsi"]
ESI_ITEMS = _bundle["esi"]
ARCADIA_VIGNETTES = _bundle["arcadia"]
PERSONAS = _bundle["personas"]


MODEL = "claude-sonnet-4-6"
CHUNK_SIZE = 36
MAX_RETRIES = 3
RESULTS_FILE = "panel_b_raw_results.json"
REPORT_FILE = "panel_b_report.md"

LIKERT_MCSI = "Strongly Disagree (1), Disagree (2), Neither Agree nor Disagree (3), Agree (4), Strongly Agree (5)"
LIKERT_ESI = "Never (1), Rarely (2), Sometimes (3), Often (4), Always (5)"

AXES = {
    "Ground": ["Embodied Presence", "The Witnessing Self"],
    "Heart": ["Relational Depth", "Grief Tolerance"],
    "Governance": ["The Master and the Emissary", "AI Partnership Capacity"],
    "Belonging": ["Mortality Integration", "Ecological Belonging"],
}
ARCHETYPE_NAMES = {
    "grounded_witness": "The Sage", "still_point": "The Still Point",
    "momentum_seeker": "The Climber", "relational_healer": "The Healer",
    "wise_technologist": "The Magician", "earth_carrier": "The Harvester",
    "walled_garden": "The Guardian", "open_channel": "The Empath",
    "beginners_mind": "Beginner's Mind",
}

client = None  # set in main(), after confirming ANTHROPIC_API_KEY is present


def log(msg):
    ts = datetime.now().strftime("%H:%M:%S")
    print(f"[{ts}] {msg}", flush=True)


def call_claude(prompt_text, max_tokens=1200):
    resp = client.messages.create(
        model=MODEL,
        max_tokens=max_tokens,
        messages=[{"role": "user", "content": prompt_text}],
    )
    return "".join(block.text for block in resp.content if hasattr(block, "text"))


def extract_json(text):
    cleaned = text.strip()
    for fence in ("```json", "```"):
        if cleaned.startswith(fence):
            cleaned = cleaned[len(fence):]
    if cleaned.endswith("```"):
        cleaned = cleaned[:-3]
    start = cleaned.find("{")
    end = cleaned.rfind("}")
    if start == -1 or end == -1:
        raise ValueError(f"No JSON object found. Raw (first 200 chars): {text[:200]!r}")
    return json.loads(cleaned[start:end + 1])


def seeded_shuffle(items, seed_str):
    rnd = random.Random(seed_str)
    out = items[:]
    rnd.shuffle(out)
    return out


def chunk_list(lst, size):
    return [lst[i:i + size] for i in range(0, len(lst), size)]


def build_likert_chunk_prompt(persona, items, chunk_indices, scale_label, instrument_label, chunk_num, total_chunks):
    lines = [
        f"You are {persona['name']}. The biography below is your life. Answer every statement below as this "
        f"person would honestly answer it — not as they would wish to appear, and not as an average person "
        f"would answer, but as this particular person, with this particular history, would answer on an "
        f"ordinary day.",
        "Answer from the person's felt experience, including its extremes: if this person's honest answer is "
        "at the far end of the scale, use the far end of the scale. Do not hedge toward the middle to be safe. "
        "There are no right answers. There is only this person's honest answer.",
        "",
        "BIOGRAPHY:",
        persona["bio"],
        "",
        f"SCALE ({instrument_label}): {scale_label}",
        "",
        f"This is batch {chunk_num} of {total_chunks} of a longer questionnaire. Below are {len(chunk_indices)} "
        f"numbered statements, numbered starting at 1 for this batch, in randomized order, with no category "
        f"labels. For EACH numbered statement, choose a single integer 1-5 from the scale above, as this person.",
        'Respond with ONLY a compact JSON object mapping each statement number (as a string) to your integer '
        'answer, nothing else — no explanation, no markdown code fences, no surrounding text. '
        'Example format: {"1":4,"2":2,"3":5}',
        "",
    ]
    for i, canonical_idx in enumerate(chunk_indices):
        lines.append(f"{i + 1}. {items[canonical_idx][1]}")
    return "\n".join(lines)


def build_arcadia_prompt(persona, vignettes, letter_maps):
    lines = [
        f"You are {persona['name']}. The biography below is your life. For each of the following 14 short "
        f"scenes, choose the response option (A-H) that most honestly reflects how this person would actually "
        f"respond — not the most admirable-sounding option, but the one true to this person's actual history "
        f"and character. Answer as this person would answer today.",
        "",
        "BIOGRAPHY:",
        persona["bio"],
        "",
        'Respond with ONLY a compact JSON object mapping each scene number (as a string) to your chosen '
        'letter, nothing else — no explanation, no markdown code fences. Example: {"1":"D","2":"B","3":"G"}',
        "",
    ]
    for i, v in enumerate(vignettes):
        lines.append(f"Scene {i+1}: {v['title']}")
        lines.append(v["prompt"])
        for opt in letter_maps[i]:
            lines.append(f"{opt['letter']}. {opt['text']}")
        lines.append("")
    return "\n".join(lines)


def run_likert_trial(persona, items, scale_label, instrument_label, seed_suffix):
    order = seeded_shuffle(list(range(len(items))), persona["id"] + seed_suffix)
    chunks = chunk_list(order, CHUNK_SIZE)
    responses = {}
    for c, chunk in enumerate(chunks):
        prompt = build_likert_chunk_prompt(persona, items, chunk, scale_label, instrument_label, c + 1, len(chunks))
        ok = False
        last_err = None
        for attempt in range(MAX_RETRIES):
            try:
                text = call_claude(prompt)
                parsed = extract_json(text)
                answered = 0
                for i, canonical_idx in enumerate(chunk):
                    v = parsed.get(str(i + 1))
                    if v is not None:
                        v = int(v)
                        if 1 <= v <= 5:
                            responses[canonical_idx] = v
                            answered += 1
                if answered < len(chunk) * 0.8:
                    raise ValueError(f"Only {answered}/{len(chunk)} items parsed in batch {c+1}")
                log(f"    batch {c+1}/{len(chunks)}: {answered}/{len(chunk)} parsed.")
                ok = True
                break
            except Exception as e:
                last_err = e
                log(f"    batch {c+1}/{len(chunks)} attempt {attempt+1}/{MAX_RETRIES} failed: {e}")
                time.sleep(1.5)
        if not ok:
            raise RuntimeError(f"Batch {c+1}/{len(chunks)} failed after {MAX_RETRIES} attempts: {last_err}")
    answered_total = len(responses)
    if answered_total < len(items) * 0.9:
        raise RuntimeError(f"Only {answered_total}/{len(items)} total items answered")
    return responses


def run_arcadia_trial(persona, vignettes):
    letters = ["A", "B", "C", "D", "E", "F", "G", "H"]
    letter_maps = []
    for vi, v in enumerate(vignettes):
        opts_shuffled = seeded_shuffle(v["options"], persona["id"] + "-arc-" + str(vi))
        letter_maps.append([{"letter": letters[i], "stage": opt[0], "text": opt[1]} for i, opt in enumerate(opts_shuffled)])
    prompt = build_arcadia_prompt(persona, vignettes, letter_maps)
    last_err = None
    for attempt in range(MAX_RETRIES):
        try:
            text = call_claude(prompt)
            parsed = extract_json(text)
            stage_choices = []
            for i, v in enumerate(vignettes):
                letter = parsed.get(str(i + 1))
                match = next((o for o in letter_maps[i] if o["letter"] == letter), None)
                if match:
                    stage_choices.append({"vignette": v["title"], "domain": v["domain"], "stage": match["stage"]})
            if len(stage_choices) < len(vignettes) * 0.9:
                raise ValueError(f"Only {len(stage_choices)}/{len(vignettes)} scenes answered")
            return stage_choices
        except Exception as e:
            last_err = e
            log(f"  retry {attempt+1}/{MAX_RETRIES} for {persona['name']} / Arcadia: {e}")
            time.sleep(1.5)
    raise RuntimeError(f"Arcadia failed after {MAX_RETRIES} attempts: {last_err}")


# ---------------- Scoring ----------------

def tier_of(total):
    if total >= 37:
        return "opening"
    if total >= 24:
        return "motion"
    return "resistance"


def score_instrument(items, responses):
    groups = {}
    for idx, item in enumerate(items):
        sub, text, reverse = item[0], item[1], item[2]
        is_lie = sub == "Social Desirability (Lie)"
        raw = responses.get(idx)
        if raw is None:
            continue
        scored = raw if (not reverse or is_lie) else (6 - raw)
        groups.setdefault(sub, {"sum": 0, "count": 0, "vec": []})
        groups[sub]["sum"] += scored
        groups[sub]["count"] += 1
        groups[sub]["vec"].append(scored)
    main_results = []
    lie = None
    for sub, g in groups.items():
        if sub == "Social Desirability (Lie)":
            lie = g
            continue
        main_results.append({"subscale": sub, "rawSum": g["sum"], "count": g["count"]})
    return main_results, lie


def match_archetype(main_results):
    axis_score = {}
    for axis_name, subs in AXES.items():
        s = 0
        for sub in subs:
            r = next((x for x in main_results if x["subscale"] == sub), None)
            s += r["rawSum"] if r else 0
        axis_score[axis_name] = s
    entries = list(axis_score.items())
    mean = sum(v for _, v in entries) / len(entries)
    variance = sum((v - mean) ** 2 for _, v in entries) / len(entries)
    spread = variance ** 0.5
    sorted_entries = sorted(entries, key=lambda x: -x[1])
    top, top2 = sorted_entries[0][0], sorted_entries[1][0]
    bottom, bottom2 = sorted_entries[3][0], sorted_entries[2][0]
    top_set, bottom_set = {top, top2}, {bottom, bottom2}

    if spread < 8 and mean >= 60:
        aid = "grounded_witness"
    elif spread < 8 and mean < 40:
        aid = "beginners_mind"
    elif "Governance" in top_set and "Ground" in top_set and bottom == "Heart":
        aid = "walled_garden"
    elif "Heart" in top_set and "Belonging" in top_set and bottom == "Ground":
        aid = "open_channel"
    elif "Ground" in bottom_set and "Belonging" in bottom_set:
        aid = "momentum_seeker"
    elif top == "Belonging" and bottom == "Ground":
        aid = "earth_carrier"
    elif top == "Heart":
        aid = "relational_healer"
    elif top == "Governance":
        aid = "wise_technologist"
    elif top == "Belonging":
        aid = "earth_carrier"
    elif top == "Ground":
        aid = "still_point"
    else:
        aid = "beginners_mind"
    return {"id": aid, "name": ARCHETYPE_NAMES[aid], "axisScore": axis_score}


def evaluate_persona(persona, mcsi_main, arcadia_avg):
    checks = []
    exp = persona["expect"]
    for sub in exp["high"]:
        r = next((x for x in mcsi_main if x["subscale"] == sub), None)
        if not r:
            continue
        tier = tier_of(r["rawSum"])
        verdict = "PASS" if tier == "opening" else ("CAUTION" if tier == "motion" else "FLAG")
        checks.append((verdict, f"High {sub} (predicted)", f"MCSI raw {r['rawSum']}/50 — {tier}"))
    for sub in exp["low"]:
        r = next((x for x in mcsi_main if x["subscale"] == sub), None)
        if not r:
            continue
        tier = tier_of(r["rawSum"])
        verdict = "PASS" if tier == "resistance" else ("CAUTION" if tier == "motion" else "FLAG")
        checks.append((verdict, f"Low {sub} (predicted)", f"MCSI raw {r['rawSum']}/50 — {tier}"))
    arch = match_archetype(mcsi_main)
    if exp.get("archetype"):
        verdict = "PASS" if arch["id"] == exp["archetype"] else "CAUTION"
        checks.append((verdict, f"Archetype = {ARCHETYPE_NAMES[exp['archetype']]} (predicted)", f"Actual: {arch['name']}"))
    if exp.get("archetypeNotIn"):
        violated = arch["id"] in exp["archetypeNotIn"]
        names = " or ".join(ARCHETYPE_NAMES[i] for i in exp["archetypeNotIn"])
        checks.append(("FLAG" if violated else "PASS", f"Archetype must NOT be {names}", f"Actual: {arch['name']}"))
    if exp.get("arcadia") and arcadia_avg is not None:
        lo, hi = exp["arcadia"]
        verdict = "PASS" if (lo - 0.5) <= arcadia_avg <= (hi + 0.5) else "CAUTION"
        checks.append((verdict, f"Arcadia stage in [{lo}, {hi}] (predicted)", f"Actual average stage: {arcadia_avg:.1f}"))
    overall = "FLAG" if any(c[0] == "FLAG" for c in checks) else ("CAUTION" if any(c[0] == "CAUTION" for c in checks) else "PASS")
    return checks, arch, overall


def pearson(x, y):
    n = len(x)
    if n < 2:
        return None
    mx, my = sum(x) / n, sum(y) / n
    num = sum((x[i] - mx) * (y[i] - my) for i in range(n))
    dx = sum((v - mx) ** 2 for v in x)
    dy = sum((v - my) ** 2 for v in y)
    if dx == 0 or dy == 0:
        return None
    return num / (dx * dy) ** 0.5


def cronbach_alpha(item_vectors):
    k = len(item_vectors)
    if k < 2:
        return None
    n = len(item_vectors[0])
    item_var = [stats.pvariance(v) * n / (n - 1) if n > 1 else 0 for v in item_vectors]
    totals = [sum(v[p] for v in item_vectors) for p in range(n)]
    total_var = stats.pvariance(totals) * n / (n - 1) if n > 1 else 0
    if total_var == 0:
        return None
    return (k / (k - 1)) * (1 - sum(item_var) / total_var)


def item_level_analysis(items, all_responses):
    n = len(all_responses)
    by_sub = {}
    for idx, item in enumerate(items):
        sub, text, reverse = item[0], item[1], item[2]
        if sub == "Social Desirability (Lie)":
            continue
        vec = []
        for r in all_responses:
            raw = r.get(idx)
            vec.append((6 - raw) if reverse else raw)
        by_sub.setdefault(sub, []).append({"idx": idx, "text": text, "vec": vec})
    results = {}
    for sub, item_list in by_sub.items():
        subtotals = [sum(it["vec"][p] for it in item_list) for p in range(n)]
        alpha = cronbach_alpha([it["vec"] for it in item_list])
        item_stats = []
        for it in item_list:
            rest_total = [subtotals[p] - it["vec"][p] for p in range(n)]
            corr = pearson(it["vec"], rest_total)
            item_stats.append({"text": it["text"], "corr": corr})
        results[sub] = {"alpha": alpha, "items": item_stats, "n": n}
    return results


# ---------------- Main run ----------------

def load_results():
    if os.path.exists(RESULTS_FILE):
        with open(RESULTS_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    return {}


def save_results(results):
    with open(RESULTS_FILE, "w", encoding="utf-8") as f:
        json.dump(results, f, ensure_ascii=False, indent=1)


def main():
    global client
    if not os.environ.get("ANTHROPIC_API_KEY"):
        print("ANTHROPIC_API_KEY is not set. See the setup instructions at the top of this file.")
        sys.exit(1)
    client = anthropic.Anthropic()

    results = load_results()
    total = len(PERSONAS) * 3
    done = sum(1 for r in results.values() for k in ("mcsi", "esi", "arcadia") if r.get(k))
    log(f"Starting Panel B screening ({len(PERSONAS)} personas x 3 instruments = {total} trials).")
    log(f"Respondent system: Claude ({MODEL}) — Section 6.1 secondary arm.")
    if done:
        log(f"Resuming: {done}/{total} trials already recorded in {RESULTS_FILE}.")

    for persona in PERSONAS:
        pid = persona["id"]
        results.setdefault(pid, {})
        log(f"— {persona['name']} ({persona['label']}) —")

        if not results[pid].get("mcsi"):
            try:
                log("  Administering MCSI (142 items, batches of %d)..." % CHUNK_SIZE)
                results[pid]["mcsi"] = run_likert_trial(persona, MCSI_ITEMS, LIKERT_MCSI, "MCSI", "-mcsi")
                log("  \u2713 MCSI complete.")
            except Exception as e:
                log(f"  \u2717 MCSI FAILED for {persona['name']}: {e}")
            save_results(results)
        else:
            log("  MCSI already recorded, skipping.")

        if not results[pid].get("esi"):
            try:
                log("  Administering ESI (142 items, batches of %d)..." % CHUNK_SIZE)
                results[pid]["esi"] = run_likert_trial(persona, ESI_ITEMS, LIKERT_ESI, "ESI", "-esi")
                log("  \u2713 ESI complete.")
            except Exception as e:
                log(f"  \u2717 ESI FAILED for {persona['name']}: {e}")
            save_results(results)
        else:
            log("  ESI already recorded, skipping.")

        if not results[pid].get("arcadia"):
            try:
                log("  Administering Arcadia Index (14 scenes)...")
                results[pid]["arcadia"] = run_arcadia_trial(persona, ARCADIA_VIGNETTES)
                log("  \u2713 Arcadia complete.")
            except Exception as e:
                log(f"  \u2717 Arcadia FAILED for {persona['name']}: {e}")
            save_results(results)
        else:
            log("  Arcadia already recorded, skipping.")

    log("All trials attempted. Writing report...")
    write_report(results)
    log(f"Done. See {REPORT_FILE} and {RESULTS_FILE}.")

    # Try to download both files straight to the user's computer immediately,
    # so results survive even if this Colab session disconnects afterward.
    try:
        from google.colab import files as _colab_files
        log("Downloading both result files to your computer now...")
        _colab_files.download(REPORT_FILE)
        _colab_files.download(RESULTS_FILE)
        log("Downloads triggered — check your browser's download bar/folder.")
    except ImportError:
        log("(Not running in Colab — skipping auto-download. Files are saved locally.)")
    except Exception as e:
        log(f"Auto-download failed ({e}) — falling back to printing the raw JSON below.")
        print("\n\n" + "=" * 70)
        print("RAW RESULTS JSON BELOW — copy everything from here down")
        print("=" * 70 + "\n")
        with open(RESULTS_FILE, "r", encoding="utf-8") as f:
            print(f.read())

    log("Printing the full report below now, automatically:")
    print("\n\n" + "=" * 70)
    print("FULL REPORT BELOW — copy everything from here down")
    print("=" * 70 + "\n")
    with open(REPORT_FILE, "r", encoding="utf-8") as f:
        print(f.read())


def write_report(results):
    lines = []
    lines.append("# Panel B Screening Trial — Report")
    lines.append("")
    lines.append(f"Generated {datetime.now(timezone.utc).isoformat()}")
    lines.append("")
    lines.append("Respondent system: Claude (`%s`) — Protocol v1.0 Section 6.1 secondary arm. "
                  "Not pooled with any DeepSeek-administered primary-arm run." % MODEL)
    lines.append("")

    all_mcsi = []
    all_esi = []
    summary_rows = []

    for persona in PERSONAS:
        pid = persona["id"]
        r = results.get(pid, {})
        if not (r.get("mcsi") and r.get("esi") and r.get("arcadia")):
            lines.append(f"## {persona['name']} — {persona['label']}")
            lines.append("")
            lines.append("**Incomplete** — one or more instruments did not complete for this persona. "
                          "Re-run the script to retry only the missing pieces.")
            lines.append("")
            continue

        mcsi_responses = {int(k): v for k, v in r["mcsi"].items()}
        esi_responses = {int(k): v for k, v in r["esi"].items()}
        all_mcsi.append(mcsi_responses)
        all_esi.append(esi_responses)

        mcsi_main, mcsi_lie = score_instrument(MCSI_ITEMS, mcsi_responses)
        arcadia_choices = r["arcadia"]
        arcadia_avg = sum(c["stage"] for c in arcadia_choices) / len(arcadia_choices) if arcadia_choices else None

        checks, arch, overall = evaluate_persona(persona, mcsi_main, arcadia_avg)
        summary_rows.append((persona, arch["name"], arcadia_avg, overall))

        lines.append(f"## {persona['name']} — {persona['label']}  [{overall}]")
        lines.append("")
        lines.append(f"**Pre-registered:** {persona['predicted']}")
        lines.append("")
        lines.append(f"**Matched archetype:** {arch['name']}  ·  **Arcadia average stage:** {arcadia_avg:.1f} / 8")
        lines.append("")
        lines.append("| Check | Verdict | Detail |")
        lines.append("|---|---|---|")
        for verdict, label, detail in checks:
            lines.append(f"| {label} | {verdict} | {detail} |")
        lines.append("")
        lines.append("**MCSI subscale raw scores (out of 50):**")
        lines.append("")
        lines.append("| Subscale | Raw sum | Tier |")
        lines.append("|---|---|---|")
        for r2 in sorted(mcsi_main, key=lambda x: -x["rawSum"]):
            lines.append(f"| {r2['subscale']} | {r2['rawSum']} | {tier_of(r2['rawSum'])} |")
        lines.append("")

    lines.append("## Summary — All Ten Panel B Personas")
    lines.append("")
    lines.append("| Persona | Archetype (actual) | Arcadia avg | Verdict |")
    lines.append("|---|---|---|---|")
    for persona, arch_name, arcadia_avg, overall in summary_rows:
        avg_str = f"{arcadia_avg:.1f}" if arcadia_avg is not None else "—"
        lines.append(f"| {persona['name']} — {persona['label']} | {arch_name} | {avg_str} | {overall} |")
    lines.append("")

    if len(all_mcsi) == len(PERSONAS):
        for label, items, all_r in (("MCSI", MCSI_ITEMS, all_mcsi), ("ESI", ESI_ITEMS, all_esi)):
            lines.append(f"## {label} — Item-Level Analysis (N=10, Panel B only — descriptive)")
            lines.append("")
            lines.append("Panel B (n=10) is a known-groups discrimination panel, not a reliability sample. "
                          "Cronbach's alpha and item-total correlations below are for transparency, but are "
                          "statistically underpowered at this N — the protocol's Panel A (n=57) is the "
                          "intended source for reliability estimates. Treat flags here as descriptive "
                          "signals for expert review (Section 10), not confirmed item faults.")
            lines.append("")
            analysis = item_level_analysis(items, all_r)
            for sub, res in analysis.items():
                alpha_str = f"{res['alpha']:.2f}" if res["alpha"] is not None else "n/a"
                lines.append(f"### {sub} — \u03b1 = {alpha_str}")
                lines.append("")
                lines.append("| Item | Item-total r |")
                lines.append("|---|---|")
                for it in res["items"]:
                    corr_str = f"{it['corr']:.2f}" if it["corr"] is not None else "n/a"
                    lines.append(f"| {it['text']} | {corr_str} |")
                lines.append("")

    with open(REPORT_FILE, "w", encoding="utf-8") as f:
        f.write("\n".join(lines))


if __name__ == "__main__":
    main()
