{#- Full Analysis Workflow - the flagship Reality Check command -#}
{#- This is the comprehensive template that includes all methodology content -#}

The flagship Reality Check command for rigorous source analysis.

{% include "partials/prerequisites.md.j2" %}

## Workflow Steps

1. **Start Tracking** - Begin token usage capture (lifecycle mode)
2. **Fetch** - Retrieve and parse source content
   - Primary: `WebFetch` for most URLs
   - Alternative: `curl -L -sS "URL" | rc-html-extract - --format json`
   - `rc-html-extract` returns structured `{title, published, text, headings, word_count}`
   - Use the extract tool when you need clean metadata or main text extraction
3. **Metadata** - Extract title, author, date, type, generate source-id
4. **Stage 1: Descriptive** - Neutral summary, key claims, argument structure
5. **Stage 2: Evaluative** - Evidence quality, fact-checking, disconfirming evidence
6. **Stage 3: Dialectical** - Steelman, counterarguments, synthesis
7. **Extract** - Format claims as YAML
8. **Register** - Add source and claims to database
9. **Provenance** (for high-credence claims) - Link evidence + capture reasoning trails
10. **Complete Tracking** - Finalize token usage + register `analysis_logs` row
11. **Validate** - Run integrity checks
12. **README** - Update data project analysis index
13. **File Inbox** - Move/archive inbox items to permanent locations
14. **Commit** - Stage and commit changes to data repo
15. **Push** - Push to remote
16. **Report** - Generate summary

---

## Multi-source Requests (Compare / Contrast)

If the prompt includes **multiple sources** (multiple URLs/repos/papers) or explicitly asks for **compare/contrast**, `{{ invocation_prefix }}check` is responsible for the **full** multi-source workflow **end-to-end**:

1. Run the source-analysis workflow **once per source** (one `analysis/sources/<source-id>.md` per source)
2. Then, **in the same run**, also write a single cross-source synthesis at `analysis/syntheses/<synth-id>.md`

The synthesis should link back to the relevant source analyses and resolve (or clearly frame) points of agreement and disagreement.

Use `{{ invocation_prefix }}synthesize` as a standalone command when you want to:
- create a synthesis later from existing source analyses
- update/refine an existing synthesis without re-running checks

---

## Analysis Output Contract

Every analysis must produce a **human-auditable analysis** file at:
`PROJECT_ROOT/analysis/sources/<source-id>.md`

The analysis **must** include:

1. **Metadata** (Source ID, URL, author, date/type)
2. **Legends** (top-of-file quick reference)
3. **Three-stage analysis** (Stages 1-3)
4. **Claim tables with evidence + credence**
5. **Extracted claims artifact** (embedded YAML or separate file)
6. **Analysis Log** (append-only pass history + tool/model/tokens/cost when available)

If an analysis lacks claim tables (IDs, evidence levels, credence) it is **not complete**.

### Multi-source Output

For multi-source requests, produce:
- **One** source analysis per source: `analysis/sources/<source-id>.md`
- **One** synthesis (required unless the user explicitly asks not to): `analysis/syntheses/<synth-id>.md`

### Required Elements

**Stage 1 (Descriptive)**:
- Source Metadata table
- Core Thesis (1-3 sentences)
- Key Claims table (rigor-v1: Layer/Actor/Scope/Quantifier + Verified? + Falsifiable By)
- Argument Structure diagram
- Theoretical Lineage
- Scope & Limitations

**Stage 2 (Evaluative)**:
- Key Factual Claims Verified (with Crux? column)
- Disconfirming Evidence Search
- Corrections & Updates (including capture failures)
- Internal Tensions / Self-Contradictions
- Persuasion Techniques
- Unstated Assumptions
- Evidence Assessment
- Credence Assessment

**Stage 3 (Dialectical)**:
- Steelmanned Argument
- Strongest Counterarguments
- Supporting Theories (with source IDs)
- Contradicting Theories (with source IDs)
- Synthesis Notes
- Claims to Cross-Reference

**End**:
- Claim Summary table (all claims)
- Claims to Register (YAML)
- Credence in Analysis (0.0-1.0)

---

## Analysis Template

Use this structure for analysis documents:

```markdown
# Source Analysis: [Title]

{% include "partials/legends.md.j2" %}

## Metadata

| Field | Value |
|-------|-------|
| **Source ID** | [author-year-shorttitle] |
| **Title** | [extracted from source] |
| **Author(s)** | [name(s)] |
| **Date** | [YYYY-MM-DD or YYYY] |
| **Type** | [PAPER/ARTICLE/BLOG/REPORT/INTERVIEW/etc.] |
| **URL** | [source URL] |
| **Reliability** | [0.0-1.0] |
| **Rigor Level** | [SPITBALL/DRAFT/REVIEWED/CANONICAL] |

## Stage 1: Descriptive Analysis

### Core Thesis
[1-3 sentence summary of main argument]

{% include "tables/key-claims.md.j2" %}

{% include "sections/argument-structure.md.j2" %}

{% include "sections/theoretical-lineage.md.j2" %}

### Scope & Limitations
[What does this source attempt to explain? What does it explicitly not address?]

## Stage 2: Evaluative Analysis

### Internal Coherence
[Does the argument follow logically? Any contradictions?]

{% include "tables/factual-claims-verified.md.j2" %}

{% include "tables/disconfirming-evidence.md.j2" %}

{% include "tables/corrections-updates.md.j2" %}

{% include "tables/internal-tensions.md.j2" %}

{% include "tables/persuasion-techniques.md.j2" %}

{% include "tables/unstated-assumptions.md.j2" %}

### Evidence Assessment
[Quality and relevance of supporting evidence]

### Credence Assessment
- **Overall Credence**: [0.0-1.0]
- **Reasoning**: [why this level?]

## Stage 3: Dialectical Analysis

### Steelmanned Argument
[Strongest possible version of this position]

### Strongest Counterarguments
1. [Counter + source if available]
2. [Counter + source if available]

{% include "tables/supporting-contradicting.md.j2" %}

### Synthesis Notes
[How does this update our overall understanding?]

### Claims to Cross-Reference
[Which claims should be checked against other sources?]

---

{% include "tables/claim-summary.md.j2" %}

### Claims to Register

\`\`\`yaml
claims:
  - id: "DOMAIN-YYYY-NNN"
    text: "[Precise claim statement]"
    type: "[F/T/H/P/A/C/S/X]"
    domain: "[DOMAIN]"
    evidence_level: "E[1-6]"
    credence: 0.XX
    operationalization: "[How to test/measure this claim]"
    assumptions: ["..."]
    falsifiers: ["What would refute this"]
    source_ids: ["[source-id]"]
\`\`\`

{% include "sections/credence-assessment.md.j2" %}

{% include "partials/analysis-log.md.j2" %}
```

---

{% include "partials/evidence-hierarchy.md.j2" %}

{% include "partials/claim-types.md.j2" %}

{% include "partials/domain-codes.md.j2" %}

{% include "partials/credence-calibration.md.j2" %}

---

{% include "partials/db-commands.md.j2" %}

---

{% include "partials/provenance-workflow.md.j2" %}

---

## Token Usage Tracking (Lifecycle Mode)

For accurate per-check token attribution, use the lifecycle commands:

```bash
# 1. At workflow START (before fetch)
ANALYSIS_ID=$(rc-db analysis start \
  --source-id "[source-id]" \
  --tool claude-code \
  --model "claude-sonnet-4")

# 2. (Optional) Mark stage completions
rc-db analysis mark --id "$ANALYSIS_ID" --stage check_stage1
rc-db analysis mark --id "$ANALYSIS_ID" --stage check_stage2
rc-db analysis mark --id "$ANALYSIS_ID" --stage check_stage3

# 3. At workflow END (after registration, before validation)
rc-db analysis complete \
  --id "$ANALYSIS_ID" \
  --analysis-file "analysis/sources/[source-id].md" \
  --claims-extracted "DOMAIN-YYYY-001,DOMAIN-YYYY-002" \
  --estimate-cost \
  --notes "3-stage analysis + registration"
```

This captures `tokens_baseline` at start and `tokens_final` at completion, computing `tokens_check = final - baseline` for accurate cost attribution.

If session auto-detection fails (ambiguous sessions), use `rc-db analysis sessions list --tool claude-code` to find your session UUID, then pass `--usage-session-id UUID` to `analysis start`.

---

## Update README (REQUIRED)

After registration and validation, update the data project's README.md:

### 1. Add Syntheses Table Entry (if created)

If you produced a synthesis document, add a row to the "Syntheses" table (kept **above** "Source Analyses"):

```markdown
| YYYY-MM-DD | [Topic](analysis/syntheses/<synth-id>.md) | `[DRAFT/REVIEWED]` | Brief summary |
```

Insert at the **top** of the table (below header row), keeping entries reverse-chronological.

### 2. Add Source Analyses Table Entry

**Edit `$PROJECT_ROOT/README.md` now.** Find the "Source Analyses" table and insert a new row:

```markdown
| YYYY-MM-DD | [Title](analysis/sources/<source-id>.md) | `[REVIEWED]` | Brief summary |
```

Insert at the **top** of the table (below header row), keeping entries reverse-chronological.

### 3. Update Stats Tables

Run the stats update script to refresh claim/source counts:

```bash
# From the realitycheck framework directory
scripts/update-readme-stats.sh "$PROJECT_ROOT"
# or: bash scripts/update-readme-stats.sh "$(dirname "$REALITYCHECK_DATA")"
```

This updates the "Current Status" and "Claim Domains" tables automatically.

---

## File Inbox Items (if applicable)

If the source originated from `inbox/`, **file it to its permanent location** after analysis is complete. Do not leave processed items in `inbox/`.

### Filing Destinations

| Source Type | Destination | Notes |
|-------------|-------------|-------|
| URL (fetched via WebFetch) | No file action needed | URL is recorded in source metadata |
| URL placeholder file (`*.url`, `*.txt`) | **Delete** | `rm inbox/<file>` |
| PDF/document (primary source) | `reference/primary/<source-id>.<ext>` | Rename to match source-id |
| PDF/document (supporting) | `reference/captured/<filename>` | Keep original filename |
| Screenshot/image | `reference/captured/<source-id>-<desc>.<ext>` | Descriptive suffix |
| Data file (CSV, JSON, etc.) | `reference/captured/<filename>` | Keep original filename |
| Video/audio transcript | `reference/captured/<source-id>-transcript.<ext>` | |

### Filing Commands

```bash
# For primary documents (rename to source-id)
mv inbox/original-document.pdf reference/primary/<source-id>.pdf

# For supporting materials (keep original name)
mv inbox/supporting-data.csv reference/captured/

# For URL placeholders (just delete)
rm inbox/some-article.url

# For screenshots
mv inbox/screenshot.png reference/captured/<source-id>-homepage.png
```

### Update Evidence Links (if applicable)

If you created `evidence_links` pointing to the inbox location, update them:

```bash
# The location field should use the new path
# artifact=reference/primary/<source-id>.pdf; locator=p.15
```

### Verify Inbox is Clean

After filing, `inbox/` should contain only **unprocessed** items:

```bash
ls inbox/  # Should not contain items you just analyzed
```

---

## Commit and Push (REQUIRED)

**You MUST commit and push after every successful analysis.** This is not optional.

```bash
# From the data project root
cd "$(dirname "$REALITYCHECK_DATA")"

# Stage all changes (including filed reference materials)
git add data/ analysis/ tracking/ README.md claims/ reference/

# Stage inbox deletions (if any files were removed)
git add -u inbox/

# Commit with descriptive message
git commit -m "data: add [source-id] - [brief description]"

# Push to remote
git push
```

**Do not stop until changes are committed and pushed.** The analysis is incomplete without version control.

---

## Continuation Mode

When using `--continue` on an existing analysis:

1. **Find existing analysis**: Look for `analysis/sources/[source-id].md`
2. **Read current state**: Load the existing analysis and registered claims
3. **Iterate, don't overwrite**: Add to the existing analysis rather than replacing it
4. **Focus areas**:
   - Extract claims that were skipped or noted as "TODO"
   - Deepen specific sections (more counterfactuals, stronger steelman)
   - Add evidence that was found after initial analysis
   - Address questions or gaps identified in the original pass
   - Cross-reference with newly added claims in the database
5. **Preserve content**: Append new sections, update claim counts, note what changed
