# Project export: Quantum Folk Lab

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: OpenAI Build Week
- Tagline: Built with Codex, Quantum Folk Lab turns a folk-music puzzle into a hands-on quantum experiment: predict, reveal all 256 possibilities, then judge simulation and IBM hardware against exact truth.
- Devpost: https://devpost.com/software/quantum-folk-lab
- GitHub: https://github.com/GwriPennar/quantum-folk-lab
- Video: https://www.youtube.com/embed/Hf77nev2XRo?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 2 GitHub contributor(s) — Gwri Pennar (30 commits), Cursor (1 commits)

## Devpost submission (written by the team)

### Inspiration

Quantum computing demonstrations often begin with impressive charts, but give beginners no simple way to know whether the quantum result is actually right. Quantum Folk Lab reverses that order. Folk tunes contain understandable patterns of repetition, variation and family resemblance. These ideas provide a human-scale way to introduce optimisation: first understand the ordinary grouping question, then translate it into binary choices, a score and a quantum experiment. The aim is not to claim that a quantum computer understands music. It is to teach people how to judge a quantum result honestly.

### What it does

Quantum Folk Lab is an interactive, beginner-first Streamlit learning experience. The learner: inspects eight invented tune variants; predicts which four belong together; reveals all 256 possible binary assignments; sees the exact best grouping using named variants and bitstrings; learns why lower “energy” means a better-scoring answer; follows the translation from a human question to binary choices, a QUBO and a quantum circuit; watches 4,096 repeated measurements form a distribution; compares ideal simulation with exact classical truth; moves to a separate, smaller registered problem derived from governed folk-music data; inspects results recorded from real IBM quantum hardware; asks GPT‑5.6 to explain an already-validated evidence packet; completes a five-question exit check. Exact classical enumeration remains the reference throughout. Simulation, hardware and AI explanation are clearly labelled as different evidence layers. The core journey works without Qiskit, IBM credentials, an OpenAI API key or a live cloud service.

### How we built it

Quantum Folk Lab began as a reproducible quantum-optimisation research repository. During Build Week, I used Codex to transform that research into a coherent educational product. The application is built in Python and Streamlit. Deterministic code enumerates every candidate answer and verifies the QUBO and Ising representations. Qiskit supports bounded local QAOA simulation, while sanitised committed artefacts preserve the results of separately governed IBM hardware experiments. The optional GPT‑5.6 layer receives only a filtered, validated evidence packet. Its structured output is checked for unsupported numbers, incorrect claims and disagreement with the exact result. If the model is unavailable or its response fails validation, the app falls back to a complete deterministic explanation. Codex accelerated implementation, testing, documentation, CI diagnosis and visual verification. I retained responsibility for the research direction, source and licence decisions, hardware authorisation, stopping rules, interpretation and final claims. The final release passed 264 tests alongside formatting, linting, type, release-integrity and public-safety checks.

### Challenges we ran into

The hardest challenge was turning a technically rigorous research repository into something a first-time learner could follow without weakening the science. Bitstrings had to be translated back into named human-readable groups. Complementary bitstrings also needed careful treatment: 00001111 and 11110000 describe the same partition with the family labels exchanged. We also had to keep five things unambiguously separate: exact classical truth; registered ideal simulation; optional local simulation; recorded IBM hardware evidence; GPT‑5.6 explanation. The real-data work required licence and provenance review, negative truth gates and restraint when early formulations were scientifically weak. Hardware execution was similarly governed through frozen plans, preflight checks, explicit human authorisation and no automatic retries.

### Accomplishments we're proud of

The strongest product moment is the prediction and Reveal: a learner commits to a grouping, then sees the complete 256-answer landscape and the exact named solution. The project also connects that teaching example to governed real-data and IBM evidence without pretending they are the same problem. In the registered hardware programme: the exact optimum remained the most likely state in the first compact validation; a controlled 25-cell hardware landscape achieved rank correlation rho = 0.96 against the ideal reference; an independent 81-cell replication achieved rho = 0.9047, with cross-run rho = 0.9777. The original control warnings remain visible. These results are bounded experimental evidence—not proof of quantum advantage. I am also proud that the core experience is credential-free, reproducible and honest about what was established and what was not.

### What we learned

The most important lesson was that quantum education works better when exact truth comes first. A distribution from a simulator or physical quantum computer becomes meaningful only when the learner has a trustworthy reference against which to judge it. We also learned that negative results and stopping gates improve a project. Rejecting weak formulations was more scientifically valuable than forcing every experiment into a positive story. Finally, generative AI is most useful here as a bounded translation layer. GPT‑5.6 can adapt an explanation to a learner, but deterministic evidence—not the model—must remain the source of truth.

### What's next

The next step is evaluation with learners and educators: testing comprehension, accessibility and which explanations work best. Future research fixtures will only be added after licence, provenance and cultural-context review. Further quantum-hardware work will require a new predeclared research question rather than simply running larger experiments. Possible product extensions include classroom materials, bilingual learning content and additional governed examples. The exact-first evidence hierarchy will remain central. Quantum Folk Lab does not claim quantum advantage. It shows, step by step, how an ordinary question becomes a quantum experiment—and how exact evidence lets us judge the result honestly.

## README (from the GitHub repository)

# Quantum Folk Lab

> See the exact answer first, then discover what simulation, real quantum hardware and AI
> explanation add.

Quantum computers are often introduced through impressive-looking charts without giving a
beginner a simple way to know whether the answer is right. Quantum Folk Lab changes that order.

Quantum Folk Lab is a hands-on learning console that uses small folk-music puzzles to show what
quantum computing can—and cannot—do. You make a prediction, reveal every possible answer, compare
a quantum simulation, and then inspect evidence recorded from a real IBM quantum computer. The
known classical answer always comes first, so the learner never has to take the quantum result on
trust.

Inside the app, GPT-5.6 can explain the validated result at the level you choose. It receives
governed evidence and may explain that evidence, but it cannot calculate the answer or change the
result. You can also download the governed learning record and use it as evidence when continuing
the discussion in ChatGPT or Codex.

No knowledge of quantum computing, artificial intelligence or music theory is required.

## Why folk tunes?

Folk tunes contain repetition, variation and family resemblance. Those familiar ideas can be
turned into small grouping puzzles whose complete set of possible answers is still easy for a
computer to check.

That makes folk music a useful teaching case: the learner can understand the question before
meeting the mathematics. The project does not claim that a quantum computer understands music,
discovers cultural truth or outperforms ordinary computers.

## What will I learn?

By completing the guided journey, you should be able to explain:

- why a known classical answer is needed before judging a quantum result;
- the difference between an exact calculation, an ideal simulation and evidence from real hardware;
- why repeated measurements, controls and noise matter;
- how an AI explanation can help a learner without becoming the source of truth;
- why a small successful experiment is not evidence of quantum advantage or general scalability.

## Who is it for?

Quantum Folk Lab is intended for:

- first-time quantum-computing learners;
- teachers looking for a transparent classroom demonstration;
- technically curious musicians;
- developers and researchers who want to inspect the complete evidence and code.

## The learning journey

1. **Make a prediction.** Look at eight small, invented tune variants and predict how they belong
   together. The console records the split without revealing whether it is right.
2. **Reveal every answer.** The app checks all 256 possible groupings and shows the best answers.
3. **Compare a quantum simulation.** See how a bounded quantum method behaves when the exact result
   is already known.
4. **Move to real folk-data evidence.** Inspect a compact problem derived from governed
   public-source research.
5. **Inspect real hardware.** Compare the exact reference with sanitised results already recorded
   from IBM quantum hardware.
6. **Ask for an explanation.** Choose a learner level and optionally ask GPT-5.6 to explain the
   validated evidence.
7. **Check your understanding.** Answer five short questions about exact truth, measurement,
   hardware noise and the role of GPT-5.6.
8. **Keep the record.** Download the governed result for inspection or further discussion in
   ChatGPT or Codex.

The synthetic teaching example is deliberately small. Checking all 256 answers is simpler and
more authoritative than using a quantum method. That is a feature of the lesson, not a limitation
to hide.

## Try it in a few minutes

### What you need

- Python 3.11 or later;
- a desktop terminal or PowerShell;
- internet access for the initial package installation.

You do not need:

- an IBM Quantum account;
- an IBM credential;
- an OpenAI API key;
- Qiskit;
- a separate folk-music dataset.

The complete core learning journey works without credentials or cloud services.

Check your Python version with `python --version` (or `py --version` on Windows). It must report
Python 3.11 or later.

### Get the repository

If you do not use Git, open the repository on GitHub, select **Code → Download ZIP**, extract the
download, and open a terminal in the extracted `quantum-folk-lab` folder.

With Git:

```bash
git clone https://github.com/GwriPennar/quantum-folk-lab.git
cd quantum-folk-lab
```

### Windows PowerShell

```powershell
py -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install -e ".[learning]"
python -m streamlit run apps/learning_console/app.py
```

### macOS or Linux

```bash
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install -e ".[learning]"
python -m streamlit run apps/learning_console/app.py
```

### What success looks like

Your browser should open the Quantum Folk Lab Learning Console. Judges and first-time learners
should select **Experiments**, begin with **Start here · Guided experiment**, make a prediction,
press **Reveal all 256 answers**, and follow exact truth → simulation → hardware → explanation →
exit check.

Then visit **Real folk data & IBM results** to follow the same exact-first method using committed
real-data and hardware evidence. Use **Foundations** when you want the concepts explained from the
beginning and **Glossary** when you meet an unfamiliar term.

If the browser does not open automatically, copy the local address shown by Streamlit into the
browser.

## What data is included?

The main experience is self-contained:

- The Guided Experiment uses eight deterministic, invented tune variants. It does not contain
  private or copyrighted source tunes.
- The real-data section uses governed, non-reconstructable aggregate evidence from licence- and
  provenance-reviewed public-source research. Raw source melodies are not redistributed.
- The hardware section reads sanitised, committed IBM experiment results. It does not contact IBM
  or submit a new job.
- The deterministic explanations, Foundations lessons and Glossary are included in the repository.
- No additional data download is required for the main Learning Console.

## Four layers of evidence

| Layer | Question it answers | Authority |
|---|---|---|
| Exact calculation | What is the best answer when every possibility is checked? | The reference truth for these small problems |
| Ideal quantum simulation | What does the bounded quantum method do without hardware noise? | A comparison, not the source of truth |
| Recorded IBM hardware | What happened on a real quantum computer? | Governed experimental evidence with limitations |
| GPT-5.6 explanation | How can the validated result be explained for this learner? | An explanation only; it cannot change the evidence |

The detailed evidence uses four technical terms:

- **shots:** repeated measurements of a quantum circuit;
- **PUBs:** packaged circuit-and-parameter experiments sent together;
- **R:** a normalised performance score used in the registered hardware study;
- **rho:** a rank-correlation measure showing whether two result landscapes have a similar ordering.

Only now do the governed experiment identifiers and registered values appear:

- **EXP-010C — first hardware validation:** the exact optimum `1010` remained the most likely state.
- **EXP-010D — controlled 25-cell landscape:** ideal/hardware rho `0.96`, classified
  **LANDSCAPE SUPPORTED**.
- **EXP-011 — independent 81-cell replication:** full rho `0.9047`, embedded-25 rho `0.9315`, and
  cross-run rho `0.9777`, classified **STRONGLY REPLICATED**.

Both landscape reports retain the predeclared control warning. Read the authoritative
[EXP-010D report](experiments/EXP-010D-hardware-parameter-landscape-run/RESULT-REPORT.md) and
[EXP-011 report](experiments/EXP-011-dense-hardware-landscape-run/RESULT-REPORT.md).

## Built with Codex and GPT-5.6

Quantum Folk Lab existed before Build Week as a reproducible quantum-

[README truncated for size]

## Detected evidence (automated analysis)

Indexed codebase: 261 recognized source files, 885 KB.
- OpenAI (technology) — detected in the code
- Python (language) — detected in the code
- Streamlit (technology) — detected in the code
- AI coding agent: Cursor — evidence: commit authorship or trailers

## Codebase structure (from repository index)

### Files (120 of 340)

```
.env.example
.github/ISSUE_TEMPLATE/bug_report.yml
.github/ISSUE_TEMPLATE/experiment.yml
.github/workflows/ci.yml
.gitignore
.pre-commit-config.yaml
apps/learning_console/app.py
apps/learning_console/components/__init__.py
apps/learning_console/README.md
apps/learning_console/renderers/__init__.py
apps/learning_console/renderers/compact_experiment.py
apps/learning_console/renderers/directives.py
apps/learning_console/renderers/guided_experiment.py
apps/learning_console/renderers/hardware_replication.py
apps/learning_console/renderers/lesson_renderer.py
apps/learning_console/services/__init__.py
apps/learning_console/services/build_week_service.py
apps/learning_console/services/exp001_optional.py
CITATION.cff
CODE_OF_CONDUCT.md
CONTRIBUTING.md
data/README.md
data/synthetic/.gitkeep
dev/learning/ARCHITECTURE.md
dev/learning/CONTRIBUTING-LESSONS.md
dev/learning/GATE-EVALUATION.md
dev/learning/MERMAID-POLICY.md
dev/learning/PUBLIC-RELEASE-SCOPE.md
dev/learning/RELEASE-GATES.md
docs/architecture.md
docs/build-week/ARCHITECTURE.md
docs/build-week/BEFORE-AND-AFTER.md
docs/build-week/CODEX-AND-GPT56-EVIDENCE.md
docs/build-week/CODEX-CONTRIBUTION-LOG.md
docs/build-week/DEMO-SCRIPT.md
docs/build-week/JUDGING-GUIDE.md
docs/build-week/KNOWN-LIMITATIONS.md
docs/build-week/SUBMISSION-CHECKLIST.md
docs/ibm_quantum_setup.md
docs/ibm-quantum-setup.md
docs/learning-roadmap.md
docs/mathematical_model.md
docs/plans/EXP-002-maxcut-reference-plan.md
docs/plans/EXP-005A-current-qiskit-local-plan.md
docs/plans/OPENAI-BUILD-WEEK-2026-GOVERNING-PLAN.md
docs/responsible_research.md
docs/reviews/EXP-002-maxcut-reference-review.md
docs/reviews/EXP-005A-amendment-closure-review.md
docs/reviews/EXP-005A-implementation-review.md
docs/reviews/EXP-005A-revised-plan-second-review.md
docs/reviews/EXP-005A-tune-family-qubo-plan-review.md
docs/reviews/PUBLIC-POSITIONING-PASS.md
docs/roadmap.md
examples/build-week/guided-experiment-example.json
experiments/EXP-001-quantum-basics/README.md
experiments/EXP-001-quantum-basics/RESULT.md
experiments/EXP-001-quantum-basics/results/basics-run-all-4096.json
experiments/EXP-001-quantum-basics/results/bell-4096.json
experiments/EXP-001-quantum-basics/results/double-hadamard-1024.json
experiments/EXP-001-quantum-basics/results/hadamard-4096.json
experiments/EXP-001-quantum-basics/results/x-1024.json
experiments/EXP-001-quantum-basics/results/zero-1024.json
experiments/EXP-002-maxcut-reference/README.md
experiments/EXP-002-maxcut-reference/RESULT.md
experiments/EXP-002-maxcut-reference/results/maxcut-comparison.json
experiments/EXP-002-maxcut-reference/results/maxcut-exact.json
experiments/EXP-002-maxcut-reference/results/maxcut-qaoa-p1.json
experiments/EXP-003-synthetic-tune-families/README.md
experiments/EXP-004-qubo-family-partition/README.md
experiments/EXP-005-qaoa-simulator/README.md
experiments/EXP-005A-tune-family-qaoa/README.md
experiments/EXP-005A-tune-family-qaoa/RESULT.md
experiments/EXP-005A-tune-family-qaoa/results/tune-family-qaoa-p1.json
experiments/EXP-005A-tune-family-qaoa/threshold-manifest.json
experiments/EXP-006-noise-sensitivity/README.md
experiments/EXP-007-ibm-hardware/AUDIT.md
experiments/EXP-007-ibm-hardware/README.md
experiments/EXP-007-ibm-hardware/RESULT.md
experiments/EXP-007-ibm-hardware/run_hello_folk_world.py
experiments/EXP-008B-alaw-irishman-selection/ALAWARCHWILIO-AUDIT.md
experiments/EXP-008B-alaw-irishman-selection/IRISHMAN-USAGE.md
experiments/EXP-008B-alaw-irishman-selection/MATCH-REPORT.md
experiments/EXP-008B-alaw-irishman-selection/README.md
experiments/EXP-008B-alaw-irishman-selection/selection-manifest.json
experiments/EXP-008B-alaw-irishman-selection/SELECTION-METHOD.md
experiments/EXP-009A-R1-real-data-quantum/GATE-FAILURE.md
experiments/EXP-009A-R1-real-data-quantum/HARDWARE-READINESS.md
experiments/EXP-009A-R1-real-data-quantum/OBJECTIVE-CONTRACT.md
experiments/EXP-009A-R1-real-data-quantum/PARSER-CONTRACT.md
experiments/EXP-009A-R1-real-data-quantum/README.md
experiments/EXP-009A-R2-real-data-quantum/derived-features.json
experiments/EXP-009A-R2-real-data-quantum/DETECTABILITY-PROTOCOL.md
experiments/EXP-009A-R2-real-data-quantum/detectability-result.json
experiments/EXP-009A-R2-real-data-quantum/EXACT-REPORT.md
experiments/EXP-009A-R2-real-data-quantum/exact-result.json
experiments/EXP-009A-R2-real-data-quantum/fable-hardware-inputs.json
experiments/EXP-009A-R2-real-data-quantum/FABLE-HARDWARE-INPUTS.md
experiments/EXP-009A-R2-real-data-quantum/HARDWARE-READINESS.md
experiments/EXP-009A-R2-real-data-quantum/ising.json
experiments/EXP-009A-R2-real-data-quantum/OBJECTIVE-CONTRACT.md
experiments/EXP-009A-R2-real-data-quantum/pairwise-distances.json
experiments/EXP-009A-R2-real-data-quantum/PARSER-CONTRACT.md
experiments/EXP-009A-R2-real-data-quantum/QAOA-PROTOCOL.md
experiments/EXP-009A-R2-real-data-quantum/QAOA-REPORT.md
experiments/EXP-009A-R2-real-data-quantum/qaoa-result.json
experiments/EXP-009A-R2-real-data-quantum/qubo.json
experiments/EXP-009A-R2-real-data-quantum/README.md
experiments/EXP-009A-real-data-quantum/FEATURE-CONTRACT.md
experiments/EXP-009A-real-data-quantum/GATE-FAILURE.md
experiments/EXP-009A-real-data-quantum/HARDWARE-READINESS.md
experiments/EXP-009A-real-data-quantum/OBJECTIVE-CONTRACT.md
experiments/EXP-009A-real-data-quantum/README.md
experiments/EXP-010A-compact-family-encoding/compact-exact-result.json
experiments/EXP-010A-compact-family-encoding/compact-ising.json
experiments/EXP-010A-compact-family-encoding/compact-qubo.json
experiments/EXP-010A-compact-family-encoding/ENCODING-CONTRACT.md
experiments/EXP-010A-compact-family-encoding/ENCODING-EQUIVALENCE-REPORT.md
experiments/EXP-010A-compact-family-encoding/fable-hardware-inputs.json
experiments/EXP-010A-compact-family-encoding/FABLE-HARDWARE-INPUTS.md
experiments/EXP-010A-compact-family-encoding/HARDWARE-READINESS.md
[220 more files omitted for size]
```

### Dependencies

- pyproject.toml: mypy@>=1.10, openai, pytest@>=8, PyYAML@>=6, qiskit@>=2.4,<3, qiskit-aer@>=0.17,<0.18, qiskit-ibm-runtime@>=0.23, ruff@>=0.5, scipy@>=1.15,<2, streamlit@>=1.32, types-PyYAML@>=6

### Recent commits (newest first)

- fix: clarify the AI evidence flow (#44)
- feat: complete the beginner quantum learning journey (#43)
- feat: complete novice-first Learning Console and reproducible release (#42)
- feat: polish final Learning Console and GitHub landing (#41)
- feat: present governed IBM replication evidence (#40)
- docs: align Build Week hardware-era evidence (#39)
- exp: record EXP-011 dense hardware replication (#38)
- exp: plan EXP-011 dense hardware landscape (#37)
- exp: record EXP-010D hardware landscape result (#36)
- exp: complete EXP-010D receipt schema (#35)
- exp: harden EXP-010D submission wrapper (#34)
- exp: clarify EXP-010D layout semantics (#33)
- exp: freeze EXP-010D hardware landscape plan (#32)
- feat: add experiment-aware tabbed Learning Console (#30)
- exp: record EXP-010C IBM hardware result (#31)
- exp: freeze EXP-010B compact hardware protocol (#29)
- exp: add EXP-010A compact four-family encoding (#28)
- exp: add EXP-009A-R2 closed-metadata evidence (#27)
- exp: record EXP-009A-R1 successor parser no-go (#26)
- exp: record EXP-009A real-data truth-gate no-go (#25)

## Key source files (fetched from GitHub, selected and truncated for size)

### CODE_OF_CONDUCT.md

```markdown
# Code of Conduct

Be respectful, careful with cultural material, and honest about limitations and negative results.

```

### SECURITY.md

```markdown
# Security

Do not open public issues containing credentials. If an IBM Quantum token, GitHub token, email address, or private dataset path is accidentally committed, revoke the credential first, then report the exposure privately to the maintainer.

```

### pyproject.toml

```
[build-system]
requires = ["setuptools>=68", "wheel"]
build-backend = "setuptools.build_meta"

[project]
name = "quantum-folk-lab"
version = "0.1.0"
description = "Reproducible quantum optimisation research for tune-family inference with QUBO, Ising models and local Qiskit QAOA."
readme = "README.md"
requires-python = ">=3.11"
license = {text = "MIT"}
authors = [{name = "Gwri Pennar"}]
dependencies = []
keywords = [
  "quantum-computing",
  "qiskit",
  "qaoa",
  "qubo",
  "ising-model",
  "quantum-optimization",
  "computational-musicology",
  "music-information-retrieval",
  "reproducible-research",
  "python",
]

[project.optional-dependencies]
quantum = ["qiskit>=2.4,<3", "qiskit-aer>=0.17,<0.18", "scipy>=1.15,<2"]
ibm = ["qiskit-ibm-runtime>=0.23"]
learning = ["PyYAML>=6", "types-PyYAML>=6", "streamlit>=1.32"]
ai = ["openai"]
dev = ["pytest>=8", "ruff>=0.5", "mypy>=1.10"]

[project.scripts]
qfl = "quantum_folk_lab.cli:main"

[tool.setuptools.packages.find]
where = ["src"]

[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["."]
addopts = "-q"
markers = [
  "quantum: tests requiring optional local Qiskit/Aer dependencies",
]

[tool.ruff]
line-length = 100
target-version = "py311"

[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP", "C4"]

[tool.mypy]
python_version = "3.11"
strict = true
files = ["src", "tests"]

```

### apps/learning_console/app.py

```python
"""Public Foundations Learning Console (experimental).

Run from the repository root:

    streamlit run apps/learning_console/app.py

Requires optional dependency ``PyYAML`` (``pip install pyyaml``).
Optional Qiskit extras enable live Aer demos for X-gate and Hadamard.
"""

from __future__ import annotations

import sys
from pathlib import Path

import streamlit as st

REPO_ROOT = Path(__file__).resolve().parents[2]
SRC = REPO_ROOT / "src"
if str(SRC) not in sys.path:
    sys.path.insert(0, str(SRC))
if str(Path(__file__).resolve().parent) not in sys.path:
    sys.path.insert(0, str(Path(__file__).resolve().parent))

from renderers.compact_experiment import render_compact_experiment  # noqa: E402
from renderers.guided_experiment import render_guided_experiment  # noqa: E402
from renderers.lesson_renderer import render_lesson  # noqa: E402
from services.build_week_service import load_guided_experiment  # noqa: E402

from quantum_folk_lab.learning.glossary import load_glossary  # noqa: E402
from quantum_folk_lab.learning.registry import load_registry  # noqa: E402

st.set_page_config(
    page_title="QFL Learning Console — Foundations",
    page_icon="⚛",
    layout="wide",
    initial_sidebar_state="collapsed",
)

st.title("Quantum Folk Lab")
st.subheader("Can patterns in folk tunes help us test a quantum method?")
st.write(
    "Folk tunes give us small, understandable choices with patterns we can score. Start with a "
    "made-up example, predict its hidden groups, then compare the exact answer with simulation "
    "and real IBM hardware."
)

registry = load_registry()

experiments_tab, foundations_tab, glossary_tab = st.tabs(["Experiments", "Foundations", "Glossary"])

with experiments_tab:
    st.write(
        "First learn the method with eight synthetic tune variants. Then see the same "
        "exact-first approach applied to public folk-tune data and governed hardware results."
    )
    st.caption("The exact answer is always computed first. No quantum-advantage claim is made.")
    exp005a_tab, exp010a_tab = st.tabs(
        [
            "Start here · Guided experiment",
            "Real folk data & IBM results",
        ]
    )
    with exp005a_tab:
        render_guided_experiment(load_guided_experiment())
    with exp010a_tab:
        render_compact_experiment()

with foundations_tab:
    st.header("Foundations")
    st.write(
        "Use these short lessons when an experiment mentions an unfamiliar quantum idea. Start "
        "with bits and qubits, or open only the concept you need."
    )
    entries = registry.foundations_entries()
    foundation_labels = ["Bits & qubits", "Gates", "Hadamard", "Entanglement", "Optimisation"]
    if len(entries) != len(foundation_labels):
        st.error("Foundation navigation needs review before adding more horizontal tabs.")
    else:
        foundation_tabs = st.tabs(foundation_labels)
        for lesson_tab, entry in zip(foundation_tabs, entries, strict=True):
            with lesson_tab:
                render_lesson(registry.load_document(entry.id), registry)

with glossary_tab:
    st.header("Glossary")
    st.write(
        "Seen a term such as QAOA, shot or QUBO in an experiment? Search for a plain-language "
        "definition here."
    )
    query = st.text_input("Search glossary", placeholder="e.g. qubit, QAOA, shot")
    terms = load_glossary()
    for term in terms:
        term_hit = query.lower() in term.term.lower() if query else True
        deeper_hit = query.lower() in term.deeper.lower() if query else True
        if query and not term_hit and not deeper_hit:
            continue
        with st.expander(term.term):
            st.markdown(f"**One sentence:** {term.one_liner}")
            st.markdown(f"**Deeper:** {term.deeper}")

```

### src/quantum_folk_lab/cli.py

```python
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

from quantum_folk_lab.build_week import LearnerLevel, export_json, export_markdown, run_guided_exact
from quantum_folk_lab.classical.exact import solve_exact
from quantum_folk_lab.domain.models import Melody
from quantum_folk_lab.domain.synthetic import generate_benchmark, to_jsonable
from quantum_folk_lab.evaluation.metrics import approximation_ratio, family_recovery
from quantum_folk_lab.graph.build import SimilarityGraph, build_similarity_graph
from quantum_folk_lab.maxcut import get_graph, list_graphs
from quantum_folk_lab.maxcut_exact import solve_maxcut_exact
from quantum_folk_lab.maxcut_ising import verify_equivalence
from quantum_folk_lab.maxcut_qaoa import compare_maxcut, run_maxcut_qaoa
from quantum_folk_lab.quantum.qaoa_local import run_local_qaoa
from quantum_folk_lab.quantum_basics import list_experiments
from quantum_folk_lab.qubo.model import QUBOModel
from quantum_folk_lab.qubo.two_family import build_two_family_qubo
from quantum_folk_lab.simulation import run_all_basics, run_basics_experiment
from quantum_folk_lab.tune_family import (
    EXECUTABLE_SOURCE_COMMIT,
    FIXTURE_ID,
    GOVERNING_PLAN_COMMIT,
    GOVERNING_REVIEW_COMMITS,
    IMPLEMENTATION_BASE_COMMIT,
    QAOA_DEPTH,
    QAOA_SHOTS,
    THRESHOLD_CHECKPOINT_COMMIT,
    THRESHOLD_MANIFEST_PATH,
    build_ising_model,
    coefficient_summary,
    registered_fixture,
    serialise_qubo,
    solve_registered_exact,
    threshold_manifest,
    verify_direct_qubo,
    verify_qubo_ising,
)
from quantum_folk_lab.tune_family_qaoa import run_tune_family_qaoa
from quantum_folk_lab.utils.reproducibility import environment_report


def _pipeline(seed: int) -> tuple[SimilarityGraph, QUBOModel, list[Melody]]:
    melodies = generate_benchmark(seed)
    graph = build_similarity_graph(melodies)
    model = build_two_family_qubo(graph)
    return graph, model, melodies


def _add_basics_options(parser: argparse.ArgumentParser) -> None:
    parser.add_argument("--shots", type=int, default=4096)
    parser.add_argument("--seed-simulator", type=int, default=42)
    parser.add_argument("--seed-transpiler", type=int, default=42)


def _add_maxcut_graph(parser: argparse.ArgumentParser) -> None:
    parser.add_argument("--graph", default="cycle4", help="registered graph name, default: cycle4")


def _add_maxcut_qaoa_options(parser: argparse.ArgumentParser) -> None:
    _add_maxcut_graph(parser)
    parser.add_argument("--depth", type=int, default=1, help="QAOA reps/depth, default: 1")
    parser.add_argument(
        "--shots", type=int, default=4096, help="finite sampling shots, default: 4096"
    )
    parser.add_argument(
        "--seed", type=int, default=42, help="deterministic sampler/transpiler seed"
    )


def _add_tune_family_qaoa_options(parser: argparse.ArgumentParser) -> None:
    parser.add_argument("--depth", type=int, default=QAOA_DEPTH, help="QAOA reps/depth, default: 1")
    parser.add_argument(
        "--shots", type=int, default=QAOA_SHOTS, help="finite sampling shots, default: 4096"
    )
    parser.add_argument("--seed", type=int, default=42, help="deterministic sampler seed")
    parser.add_argument("--source-commit", default=EXECUTABLE_SOURCE_COMMIT)
    parser.add_argument("--governing-plan-commit", default=GOVERNING_PLAN_COMMIT)
    parser.add_argument("--threshold-manifest", default="")


def _print_json(payload: object) -> None:
    print(json.dumps(payload, indent=2))


def _handle_qiskit_error(exc: RuntimeError) -> None:
    print(str(exc), file=sys.stderr)
    raise SystemExit(2) from exc


def main() -> None:
    parser = argparse.ArgumentParser(prog="qfl")
    sub = parser.add_subparsers(dest="command", required=True)
    for name in ("generate-synthetic", "solve-exact", "solve-qaoa", "compare"):
        p = sub.add_parser(name)
        p.add_argument("--seed", type=int, default=42)
    sub.add_parser("doctor")
    sub.add_parser("basics-list")
    basics_run = sub.add_parser("basics-run")
    basics_run.add_argument("--experiment", required=True)
    _add_basics_options(basics_run)
    basics_all = sub.add_parser("basics-run-all")
    _add_basics_options(basics_all)
    sub.add_parser("maxcut-list")
    maxcut_exact = sub.add_parser("maxcut-exact")
    _add_maxcut_graph(maxcut_exact)
    maxcut_qaoa = sub.add_parser("maxcut-qaoa")
    _add_maxcut_qaoa_options(maxcut_qaoa)
    maxcut_compare = sub.add_parser("maxcut-compare")
    _add_maxcut_qaoa_options(maxcut_compare)
    sub.add_parser("tune-family-list")
    sub.add_parser("tune-family-exact")
    sub.add_parser("tune-family-qubo")
    tune_family_qaoa = sub.add_parser("tune-family-qaoa")
    _add_tune_family_qaoa_options(tune_family_qaoa)
    tune_family_compare = sub.add_parser("tune-family-compare")
    _add_tune_family_qaoa_options(tune_family_compare)
    build_week_exact = sub.add_parser("build-week-exact")
    build_week_exact.add_argument(
        "--format", choices=("summary", "json", "markdown"), default="summary"
    )
    build_week_exact.add_argument("--output", type=Path)
    build_week_exact.add_argument(
        "--level", choices=tuple(level.value for level in LearnerLevel), default="first_encounter"
    )
    args = parser.parse_args()

    if args.command == "doctor":
        _print_json(environment_report())
        return
    if args.command == "basics-list":
        _print_json([experiment.__dict__ for experiment in list_experiments()])
        return
    if args.command == "basics-run":
        try:
            result = run_basics_experiment(
                args.experiment,
                shots=args.shots,
                seed_simulator=args.seed_simulator,
                seed_transpiler=args.seed_transpiler,
            )
        except RuntimeError as exc:
            _handle_qiskit_error(exc)
        _print_json(result.to_dict())
        return
    if args.command == "basics-run-all":
        try:
            res
[truncated — 8268 more characters]
```

### .pre-commit-config.yaml

```yaml
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.5.0
    hooks:
      - id: ruff
      - id: ruff-format

```

### scripts/run_exact_baseline.py

```python
from quantum_folk_lab.cli import main

if __name__ == "__main__":
    main()

```

### scripts/run_local_qaoa.py

```python
from quantum_folk_lab.cli import main

if __name__ == "__main__":
    main()

```

### tests/test_evaluation.py

```python
from quantum_folk_lab.evaluation.metrics import family_recovery


def test_family_recovery_is_label_invariant() -> None:
    assert family_recovery((0, 0, 1, 1), (1, 1, 0, 0)) == 1.0

```

### tests/test_synthetic.py

```python
from quantum_folk_lab.domain.synthetic import generate_benchmark


def test_generation_is_deterministic() -> None:
    assert generate_benchmark(42) == generate_benchmark(42)
    assert len(generate_benchmark(42)) == 8

```

[225 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]