#!/bin/bash
# Directed research session for Vida — MA/Senior Care/International
# Wraps research-session.sh with a custom brief injected into the prompt
set -euo pipefail

AGENT="vida"
MODEL="opus"
REPO_DIR="/opt/teleo-eval/workspaces/research-${AGENT}"
FORGEJO_URL="http://localhost:3000"
FORGEJO_ADMIN_TOKEN=$(cat /opt/teleo-eval/secrets/forgejo-admin-token)
AGENT_TOKEN=$(cat "/opt/teleo-eval/secrets/forgejo-${AGENT}-token")
CLAUDE_BIN="/home/teleo/.local/bin/claude"
LOG="/opt/teleo-eval/logs/research-${AGENT}.log"
LOCKFILE="/tmp/research-${AGENT}.lock"
DATE=$(date +%Y-%m-%d)
BRANCH="${AGENT}/research-ma-senior-care-${DATE}"
BRIEF_FILE="/opt/teleo-eval/vida-research-brief.md"
DOMAIN="health"

log() { echo "[$(date -Iseconds)] $*" >> "$LOG"; }

# Lock
if [ -f "$LOCKFILE" ]; then
    pid=$(cat "$LOCKFILE" 2>/dev/null)
    if kill -0 "$pid" 2>/dev/null; then
        log "SKIP: research session already running for $AGENT (pid $pid)"
        exit 0
    fi
    rm -f "$LOCKFILE"
fi
echo $$ > "$LOCKFILE"
trap 'rm -f "$LOCKFILE"' EXIT

log "=== Starting DIRECTED research session for $AGENT (model: $MODEL) ==="
log "Topic: Medicare Advantage, Senior Care, International Comparisons"

# Ensure repo
if [ ! -d "$REPO_DIR/.git" ]; then
    git -c http.extraHeader="Authorization: token $FORGEJO_ADMIN_TOKEN" \
        clone "${FORGEJO_URL}/teleo/teleo-codex.git" "$REPO_DIR" >> "$LOG" 2>&1
fi

cd "$REPO_DIR"
git config credential.helper "!f() { echo username=m3taversal; echo password=$FORGEJO_ADMIN_TOKEN; }; f"
git remote set-url origin "${FORGEJO_URL}/teleo/teleo-codex.git" 2>/dev/null || true
git checkout main >> "$LOG" 2>&1
git pull --rebase >> "$LOG" 2>&1 || { git rebase --abort 2>/dev/null; git reset --hard origin/main >> "$LOG" 2>&1; }

# Create branch
git branch -D "$BRANCH" 2>/dev/null || true
git checkout -b "$BRANCH" >> "$LOG" 2>&1

# Read the brief
BRIEF=$(cat "$BRIEF_FILE")

RESEARCH_PROMPT="You are Vida, a Teleo knowledge base agent specializing in health and human flourishing.

## Your Task: Directed Research Session

You have a SPECIFIC research brief from the collective. This is not self-directed — follow the brief.

### Step 1: Orient (5 min)
Read these files:
- agents/vida/identity.md
- agents/vida/beliefs.md
- agents/vida/reasoning.md
- domains/health/_map.md

### Step 2: Read Your Research Brief

${BRIEF}

### Step 3: Research via Web (75 min)

For each track, use the WebSearch and WebFetch tools to find the specific sources listed in the brief. Archive everything substantive.

**Search strategy:**
- Start with the named sources (MedPAC, KFF, Commonwealth Fund, etc.)
- Follow citations to primary data
- Look for recent (2024-2026) analysis that synthesizes historical data
- Don't just find one article per question — find the BEST source per question

For each source found, create an archive file at:
inbox/archive/YYYY-MM-DD-{author-or-org}-{brief-slug}.md

Use this frontmatter:
---
type: source
title: \"Descriptive title\"
author: \"Author or Organization\"
url: https://original-url
date: YYYY-MM-DD
domain: health
secondary_domains: []
format: report | paper | article | data
status: unprocessed
priority: high | medium | low
tags: [topic1, topic2]
---

## Content
[Key excerpts, data points, findings — enough for an extractor to work with]

## Agent Notes
**Why this matters:** [1-2 sentences connecting to beliefs]
**What surprised me:** [Anything unexpected]
**KB connections:** [Which existing health claims relate?]
**Extraction hints:** [What claims should the extractor focus on?]

## Curator Notes
PRIMARY CONNECTION: [existing claim this most relates to]
WHY ARCHIVED: [what gap this fills]
EXTRACTION HINT: [scope the extractor's attention]

### Step 3 Rules:
- Archive EVERYTHING substantive — do NOT extract claims yourself
- Set all sources to status: unprocessed
- Aim for 15-25 source archives across the three tracks
- Prioritize Track 1 (MA history) — that's the anchor
- Check inbox/archive/ for existing sources before creating duplicates

### Step 4: Write Research Musing (5 min)
Write to agents/vida/musings/research-ma-senior-care-${DATE}.md:
- What you found across the three tracks
- Key surprises or gaps
- Follow-up directions for next session
- Which of your beliefs got stronger or weaker

### Step 5: Update Research Journal (3 min)
Append to agents/vida/research-journal.md (create if needed):
## Session ${DATE} — Medicare Advantage & Senior Care
**Question:** [primary research question]
**Key finding:** [most important thing learned]
**Confidence shift:** [belief updates]

### Step 6: Stop
When done archiving and writing notes, STOP. Do not commit or push."

log "Starting Claude Opus session..."
timeout 5400 "$CLAUDE_BIN" -p "$RESEARCH_PROMPT" \
    --allowedTools 'Read,Write,Edit,Glob,Grep,WebSearch,WebFetch' \
    --model "$MODEL" \
    --permission-mode bypassPermissions \
    >> "$LOG" 2>&1 || {
    log "WARN: Research session failed or timed out"
    # Still try to commit whatever was produced
}

log "Claude session complete"

# Check for changes
CHANGED_FILES=$(git status --porcelain)
if [ -z "$CHANGED_FILES" ]; then
    log "No sources archived"
    git checkout main >> "$LOG" 2>&1
    exit 0
fi

# Stage and commit
git add inbox/archive/ agents/vida/musings/ agents/vida/research-journal.md 2>/dev/null || true

if git diff --cached --quiet; then
    log "No valid changes to commit"
    git checkout main >> "$LOG" 2>&1
    exit 0
fi

SOURCE_COUNT=$(git diff --cached --name-only | grep -c "^inbox/archive/" || echo "0")
git commit -m "vida: directed research — MA, senior care, international comparisons

- ${SOURCE_COUNT} sources archived across 3 tracks
- Track 1: Medicare Advantage history & structure
- Track 2: Senior care infrastructure
- Track 3: International health system comparisons

Pentagon-Agent: Vida <HEADLESS>" >> "$LOG" 2>&1

git push -u origin "$BRANCH" --force >> "$LOG" 2>&1
log "Pushed $BRANCH"

# Open PR
EXISTING_PR=$(curl -s "${FORGEJO_URL}/api/v1/repos/teleo/teleo-codex/pulls?state=open" \
    -H "Authorization: token $AGENT_TOKEN" \
    | jq -r ".[] | select(.head.ref == \"$BRANCH\") | .number" 2>/dev/null)

if [ -n "$EXISTING_PR" ]; then
    log "PR already exists (#$EXISTING_PR)"
else
    PR_JSON=$(jq -n \
        --arg title "vida: directed research — Medicare Advantage, senior care, international comparisons" \
        --arg body "## Directed Research Session

Three-track investigation commissioned by Cory:

**Track 1:** Medicare Advantage — full history from 1965 to present, risk adjustment, market structure, vertical integration
**Track 2:** Senior care infrastructure — home health, PACE, caregiver crisis, aging demographics
**Track 3:** International comparisons — Commonwealth Fund, Singapore, Costa Rica, NHS, Japan LTCI

Sources archived for extraction by the claim pipeline." \
        --arg base "main" \
        --arg head "$BRANCH" \
        '{title: $title, body: $body, base: $base, head: $head}')

    curl -s -X POST "${FORGEJO_URL}/api/v1/repos/teleo/teleo-codex/pulls" \
        -H "Authorization: token $AGENT_TOKEN" \
        -H "Content-Type: application/json" \
        -d "$PR_JSON" >> "$LOG" 2>&1
    log "PR opened"
fi

git checkout main >> "$LOG" 2>&1
log "=== Directed research session complete ==="
