CommunityResearch & Data Analysisgithub.com

5219rayhsu/open-book-is-good-skill

A Claude skill that teaches an AI agent to replicate a self-study exam question system from official open exam questions using a clean-room methodology.

What is open-book-is-good-skill?

This skill equips an AI agent with a comprehensive, judgment-driven workflow to replicate a 'Self-Study Exam Question System' (Open-Book-Is-Good) from official, publicly released exam question PDFs. It is designed primarily for national exams in Taiwan (e.g., GSAT, CAP) and has been proven on professional certification exams. The process follows a strict 7-phase pipeline: reconnaissance → download & conversion → judgment parsing → structured question bank → mandatory full answer verification → figure extraction → clean-room explanation generation → mandatory red-team review → build single-file or website. The core philosophy is 'judgment-based, not scripted', meaning every step begins with inspecting real data (e.g., detecting if a page is server-rendered or JS-rendered, or identifying question types from the official answer key) before selecting the appropriate strategy. The skill enforces two non-skippable quality gates: a full, per-question answer match verification against the official answer key, and a mandatory adversarial red-team review of all AI-generated explanations, allowing the user to choose between a full review or a statistical stop-rule-based spot-check. It also provides robust handling for 'dirty data' (encoding, naming, and layout variations year-over-year) and mandates a clean-room approach to comply with copyright law (Article 9 of Taiwan's Copyright Act), ensuring only the official exam content is used while the explanations are generated independently by the AI without relying on third-party publications. The skill includes detailed references for every phase, with emphasis on safe, deterministic build processes to avoid triggering content filters by keeping base64 image data out of agent conversations.

Works with✓Claude Code✓Codex CLI~Cursor
npx skills add 5219rayhsu/open-book-is-good-skill

Installed? Explore more Research & Data Analysis skills: affaan-m/uspto-database, affaan-m/scholar-evaluation, affaan-m/literature-review · View all 6 →

Ask in your favorite AI

Open a new chat with this agent skill pre-loaded.

Documentation

Open-Book-Is-Good: Exam Question Self-Study System Replication Manual

This manual provides a judgment-based replication guide to transform officially released exam question materials into a complete "Exam Question Self-Study System". It instructs the AI agent on how to: Reconnaissance on data sources → Download & Convert → Judgment Parsing → Build Question Bank → Mandatory Full Answer Verification → Extract Figures → Generate Clean-Room Explanations (with verification discipline) → Mandatory Red-Team for Explanations (ask user: full or spot-check) → Build Single-File / Website. This workflow has been proven on national professional certification exams in Taiwan and is being extended to other public exams like the Taiwanese university entrance exam (GSAT) and high school entrance exam (CAP).

Two Non-Skippable Gates (consistent with the "Quality Threshold" table):

  1. Full Answer Verification — Every parsed answer must be checked one by one against the official answer key. Full check, no sampling. This catches global misalignment (e.g., an answer key row being assigned to the wrong question) that structure-level checks (e.g., answer within A–D range) cannot detect.
  2. Explanation Red-Team — After the AI generates explanations for multiple-choice and essay questions, a mandatory adversarial red-team review must be performed; before execution, ask the user whether to do a "full review" (check every question) or a "spot-check" (using a statistical stopping rule), and do not skip this step.

When to Use This Skill

  • You have officially released exam questions that are free to reproduce (per Article 9 of the Copyright Act, see §9), and you want to turn them into a practice question bank.
  • You want to replicate or extend an exam question self-study system like "Open-Book-Is-Good": add a new subject, a new year, or a new exam type (different country, different exam).
  • You need to convert PDF exam questions into a structured question bank, crop figures, generate clean-room explanations, and package them into an offline single-file or website.

Not suitable for: Copyright-protected commercial test books (publisher-compiled layout, explanations); non-public, license-required exam questions.


Core Philosophy: Judgment-Based, Not Scripted

The soul of this process is a single phrase: First inspect real data, then choose a strategy, and build in quality thresholds.

  • Judgment-based, not a rigid script: Each exam's layout, question types, and answer key format differ. The parser must first "detect the reality" of this exam paper (Are there question groups? Single choice? Multiple choice / non-choice? What does the answer key look like? Are there many figures?), then select the corresponding strategy — rather than force-fitting a universal script. GSAT is complex (5 options, multiple-choice, non-choice, mixed-format questions coexist, with major structural differences between subjects), while CAP is simpler (all single-choice, 4 options). Hence, almost one parser per subject.
  • Built-in quality thresholds: Judgment is not arbitrary; it solidifies the maintainer's judgment into permanent, non-drifting thresholds (see §4). Better to miss than to be wrong: rules vary by situation (image-based vs text-only questions, question groups vs independent questions), not a one-size-fits-all approach.
  • Make judgments after inspecting actual data: Using len(answer) to infer the question type after capturing the official answer is more reliable than guessing from the question text; using the official answer table as the authoritative question list filters out false positives like isolated numbers accidentally extracted from appendices. The basis for judgment is real data, not specifications or assumptions.

7-Phase Process Overview

Reconnaissance → Download & Convert → Judgment Parsing → Build Question Bank →【Mandatory Full Answer Verification】→ Extract Figures → Generate Explanations
  →【Mandatory Explanation Red-Team (full or spot-check, ask user)】→ Build

Each phase has a corresponding detailed document in references/ that the agent should load during execution.

Phase 1: Reconnaissance on Data Sources → references/data-sources.md

Locate the official exam questions and standard answers. Two verified data source patterns:

  • Server-Rendered (GSAT via ceec.edu.tw): The list page is static HTML; fetch directly with curl -A Mozilla. Use Python regex to extract file_pool/*.pdf links from the HTML. curl + python is superior to WebFetch (WebFetch may summarize and miss modified links).
  • JS-Rendered (CAP via cap.rcpet.edu.tw): The main page is client-rendered; curl cannot fetch the links. The breakthrough is that examination.html loads a static page exam/{year}/{year}exam.html via an iframe, which then lists the Google Drive file IDs. These are consolidated into cap_drive_ids.json, downloaded by fetch_cap.py (handles Drive's virus scan confirmation page, _is_pdf() validity check, and idempotent skip).

When facing a new data source, the first step is always to reconnaissance its rendering method, then decide whether to use curl directly or go via iframe/API.

⚠️ Government/exam open data filenames, encodings, and layouts drift year over year — it's dirty data. Never use exact-match for file classification — e.g., ceec 113 Math A's exam file name is missing a character ("數a" instead of "數學a"), so an exact-match would miss the entire subject-year without error, exiting with 0. Before any comparison, always apply unicodedata.normalize('NFKC', s), use relaxed matching with alias sets, and sys.exit(1) for zero matches to avoid overwriting good data. Full robustness principles, ceec teaching cases, and pre-fetch self-check list are in references/dirty-data-robustness.md, which applies to Phases 1–3.

Phase 2: Download & Convert → references/parsing.md §1

First, convert the PDFs to Markdown using markitdown:

markitdown data/raw/{year}_{subject}_exam.pdf -o data/raw/{year}_{subject}_exam.md

Markitdown understands layout, providing a clean reading order for prose (question stems, group passages) — something raw PyMuPDF cannot achieve. But markitdown is not a silver bullet: multi-column side-by-side options, complex statistical tables, and special layouts (e.g., CAP English) will fail; in those cases, fall back to PyMuPDF's coordinate order (get_text("dict") sorted by (page, y, x)). Judging which approach is reliable is part of the judgment-based process. The answer PDF is not converted to md; it is parsed directly using PyMuPDF's find_tables() for table extraction.

Phase 3: Judgment Parsing → references/parsing.md

First detect "what this exam paper looks like" (detection table in §2), then choose the strategy. Concrete implementation methods:

  • Infer question type from answer: len(answer) > 1 → multiple choice; single letter → single choice; empty with no options → non-choice (essay).
  • Answer table is the authoritative question number list: Use it to filter out false positive isolated numbers.
  • Question group span sanity check: Header like (a, b) requires a <= b and the span is not excessive.
  • Incomplete options → fallback: If the answer is a letter but only < 4 options were parsed → layout is fragmented; switch to PyMuPDF coordinate-based extraction for those questions.
  • ToUnicode collapse itself is not the parser's fault: Some official PDFs have broken ToUnicode mappings in the font; homemade parsers, third-party APIs, and pdftotext all reproduce the same damage, so cross-referencing cannot catch it. Detection criteria, sorting question exemptions, and vision-based recovery hard gates are in references/dirty-data-robustness.md under "Official PDF text layer itself can be broken."
  • Question group answering policy classification (based on the previous judgment, for platform question breakdown): This is a key classification step that must be done during parsing. For each sub-question stem, determine if it can "appear alone": if it references a sibling question ("承上題" / "依前題" / "根據第 N 小題" / "同上題條件" / "利用前小題的結果") → mark standalone=false (platform must present the entire group together, requiring ≥2 questions at once); otherwise → standalone=true (can appear alone, but comes with its shared passage/figure). Key distinction: does "上述/如圖" refer to shared material (passage/figure → can still be standalone) or to the content/answer of a previous sub-question (→ cannot be standalone). This judgment is made during parsing and the result is recorded (see Phase 4 for the field).

One parser per subject (parse_gsat.py / parse_eng.py / parse_soc.py / parse_cap_*.py), all sharing the same schema and qid-keyed idempotent merge (rerunning a subject only overwrites that subject). Faithful reproduction: never rewrite, summarize, or translate; skip exam instructions on the first page; group_id / passage binding for question groups, never split.

Phase 4: Question Bank bank.json → references/data-sources.md §5

A plain-text question bank, one object per question. Core fields: qid (globally unique key), exam, year, subject, no, group_id, passage, stem, options, answer (can be multiple-choice), type, needs_figure, figure (stores only filename). Figures store only filenames, never image data, making the bank lintable, diffable, and git-delta-friendly.

  • Question group fields (shared material + answering policy): group_id binds the group (created during parsing, never split). Added standalone (bool, default true) — whether this sub-question can appear alone. Sub-questions of the "承上題" type are labeled standalone=false → the platform must present the entire group together when used in simulation/practice/error review/weakness modes. standalone=true sub-questions can be extracted individually. Shared figures and passages must be written into every sub-question of the group (each sub-question gets its own figure / passage, even if they share the same one); otherwise, a standalone sub-question extracted alone will lack its figure/material and become invalid. Classification is done in Phase 3, and the result is recorded here. For figure group propagation, see Phase 5. For details on how the frontend engine displays group context on different answer surfaces (full passage introduction, stem-only, chained stacking, etc.), see references/frontend-engine-rules.md §1.
  • Leave an anchor point when rewriting stems: The stem is faithfully reproduced by default. However, for subjects like math, if the stem is converted to LaTeX or cleaned for display, the rewritten stem no longer matches the PDF text layer; figure cropping (Phase 5) that relies on stem matching for positioning will fail or capture the wrong region. Whenever the stem is rewritten, save a separate PDF-faithful locating anchor (suggested field locate_anchor: question number + plain prose prefix before the first mathematical symbol, must be unique on the page); use this anchor for positioning, never display it. Why not ASCII-fy the entire segment to fix it: the PDF text layer for math symbols often uses PUA glyphs / broken ToUnicode / no encoding at all, and matching against non-existent characters is impossible. See the "Locating the Question" section in exam-pdf-asset-extractor.

Mandatory Gate A: Full Answer Verification (Every Question, No Sampling)

This is a non-skippable step. It must be run every time, and fully.

After the question bank is formed, before generating explanations, compare the answer field of every question one-by-one against the official standard answer, list all mismatches, and correct until 0 mismatches remain before proceeding. This applies only to multiple-choice questions; essay/calculation questions have no official standard answers, so this gate does not apply to them. Those are covered by the essay red-team in Phase 7.

  • Why it's mandatory: The answers from the official answer PDF do not guarantee correct alignment to question numbers. PDF parsing commonly causes global misalignment (an answer key row assigned to the wrong question). This type of error cannot be caught by structure checks (the answer still falls within A–D, looks normal); only per-question comparison can catch it.
  • Full check, no sampling: Answer verification is a hard fact of "correct or incorrect". Sampling only provides a confidence interval, not "which questions are wrong". Therefore, this gate checks every question individually, unlike the explanation red-team below which allows spot-checks.
  • Method: Independently re-parse the official standard answer source (PDF find_tables / answer sheet), and diff it answer-by-answer against bank.json. Use the official answer table as the authoritative question list for alignment. Output only counts and the mismatch list (qid, bank answer, official answer).
  • This gate was used to verify 600 questions in the national nursing exam with 0 mismatches. For existing exam archives that have not been run through this gate, it must be retroactively applied.

Phase 5: Figure Extraction → references/figures.md

An image-dependent question without its figure is trashed; therefore, crop the corresponding area from the original PDF page and render it as PNG, faithfully reproducing the original without simplification or rearrangement.

  • Do not rely on page.get_images(): Maps and statistical charts are often vector drawings; embedded bitmaps may not be found, or vector layers may be missed. Instead, use PyMuPDF to render the entire block (raster + vector together, rasterizing at zoom 2.2).
  • Locating the question: For GSAT, use the text prefix of the stem/question group marker (long prefix preferred + uniqueness requirement); for CAP, use the question number line (stable left margin). Group figures are placed in the passage area; independent figures are placed after the question stem.
  • Shared group figure → write into all sub-questions in the group: A shared figure for a question group is cropped only once (at the position of the sub-question where it actually appears), but the figure field must be propagated to every sub-question of that group_id. The detector only provides a "figure → question number" mapping; group completion is done when wiring the figure into bank.json by using group_id (the detector does not know about groups). Without this propagation, a standalone sub-question (Phase 4 standalone=true) extracted individually for simulation/error review/weakness modes would lack its figure.
  • Figure-to-question mapping varies by exam family; do not apply the same pipeline universally: Math figures appear below the question stem (map to the nearest question stem above); non-math figures are often shared material above the question number or adjacent independent questions sharing a figure without a group → use "caption-anchored (read the 圖N caption and map to questions referencing that label)" first; for untagged figures (e.g., most CAP figures use deictic words), fall back to "position-based (figure at top of page → assign to the first question below)". needs_figure for non-math subjects will be wrong in both directions: false negatives (wide figures filtered out, top-of-page figures missed) need to be recovered; false positives (pure text questions / \dfrac formula questions) need to be downgraded. For each (exam family × subject), first sample 1-3 exam papers to determine if needs_figure can be bulk-labeled, whether 圖N tags exist, and whether figures are above or below questions, then select the method. See exam-pdf-asset-extractor "Mapping figures to questions" + "What varies per exam family".
  • Locating rewritten stems will fail (math is worst): LaTeX/cleaned stems will not match the PDF text layer, leading to "stem cannot be located" or a false pure-text figure being captured (a short band height = warning sign of wrong region capture, same category as cropping the wrong figure; check both before commit). Use only the locating anchor: question number + plain prose prefix before the first symbol (or the locate_anchor field from Phase 4); do not compare the entire LaTeX stem. The figure is not necessarily between the stem and options (math often places it above the stem or in the group's shared area); real figures should be located using image/drawing-rect anchors.
  • Before cropping math figures, check the deployment site's rendering capability: If the deployment already uses KaTeX/MathJax to render LaTeX, many needs_figure=true cases are legacy from an earlier offline single-file version that "cropped formulas as images" — reassess and downgrade them, letting the renderer handle them. Only truly geometric figures (polyhedra, coordinate graphs, circuit/diagrams) should be cropped. Forcing a crop on every math needs_figure will only produce pure-text false images.
  • False figure signals (answer sheet instructions / doodle boilerplate): Before Q1, some exams have an independent "Answer Card Marking Instructions" page (grid + marking example), which looks like a figure to any ink detector and is a strong false positive (every GSAT math p0 has this); national exam PDFs from the Ministry of Examination are cleaner (starts directly from question 1, answer card is separate). First line of defense: skip pages with no questions + require every figure to correspond to a question, which filters this out. See exam-pdf-asset-extractor "Known False-Figure Signals" + "Erase-Text Figure Detection".
  • Band boundaries: Top margin with padding, not exceeding the page header; hard lower limit at the starting point of the next question; figure bottom protection (band_image_bottom) ensures no half-figure is cropped. Width is always single-column full page width (do not clip by text x0, otherwise figures floating next to text will be cut).
  • Lossless fidelity: No pngquant, no DPI reduction (maps become illegible); only lossless optimization (e.g., oxipng).

Scripts: extract_figures.py (GSAT S/G naming), extract_figures_cap.py (CAP C naming), both support --dry-run to preview bands first.

Phase 6: Explanations (With Verification Discipline) → references/explanations-redteam.md

Generate explanations in a clean-room fashion, never copying from publishers. The input is only "question stem + options + official standard answer key"; do not feed publisher explanation styles into the prompt. Each explanation has two fields {t, c}: t is the explanation text, c is the confidence level (high / med / low), making it clear to the user that this is "AI-generated, not an authoritative conclusion." The master explanations.json file's meta.note must always state that verification is required. Explanations are keyed by qid and merged idempotently (merge_stage3.py is the sole writer).

Explanations cover AI-generated multiple-choice explanations and essay question solutions. All AI-generated analyses (including essays, short answers, Chinese-to-English reference points) must go through the mandatory red-team in Phase 7. Official graded sample essays are not AI-generated and are excluded.

t is not as long as you like: Fixed three-paragraph structure (correct answer / option-by-option analysis / core knowledge tested; blank lines between paragraphs), rules for merging explanations of options sharing the same reason, and character limits (600 characters for conceptual questions, no limit for calculation questions) — see references/explanations-redteam.md §1.4 / §1.5. The model for producing high-volume explanations should approach the quality of a strong model, relying on five mechanisms: gold standard few-shot, zero-token structural linting guard, retrieval anchoring, tiered routing, and audit feedback loop — see §2.1.

Phase 7: Explanation Red-Team (Mandatory) + Build → references/explanations-redteam.md §3, references/build-deploy.md

  • Mandatory, cannot be skipped: After the AI generates explanations for multiple-choice and essay questions, a red-team review is required before entering the build phase.
  • Ask the user before executing: Should we do a full review (check every explanation) or a spot-check (statistical stopping rule)? The user decides; the agent must not skip or default to one without asking.
    • Full review — every explanation is adversarially reviewed one by one (recommended for small question sets, high-stakes exams, or when answers are disputed).
    • Spot-check — if true errors reach a threshold of ≥ 4 / 40 (lower bound of Wilson CI ≥ 4%), upgrade that subject to a stronger model and regenerate; otherwise, continue with the current model. The check is dynamic and continues until a stopping condition is met.
  • Adversarial red-team (multiple-choice): Use the strongest model to actively find fault (e.g., wrong answer given, misleading wording, outdated facts, incorrectly high confidence level) — not just re-iterate.
  • Essay/questions without official answers: Different anchor (no official answer to compare), use the six angles from references/explanations-redteam.md §3.4 (recalculate calculations, check against criteria/regulations, coverage of the question intent, timeliness, fabricated citations, confidence level), and for calculation questions, independently recalculate.
  • Restraint gate: Only fix confirmed errors, not for the sake of rewriting; re-lint and re-validate after each fix, minimizing the change surface.
  • Build: build_app.py uses only the Python standard library and is deterministic. Each exam results in a self-contained single file (no combined versions), plus a root index.html as a directory index. Figures are base64-embedded into window.__FIGS__ only at this build step. Frontend is ES5, uses el() / textContent (preventing XSS), each file is under 800 lines. The website version (PWA) uses a Service Worker with cache-first strategy and on-demand figure caching; any change to the shell must increment the CACHE version number. After every build/frontend change, run a preview smoke test (0 console errors to pass).

The built engine also has an interaction logic layer: how to pick the next question in practice mode (weakness Laplace-weighted + fingerprint cooldown + periodic review), how the "Mark" and "Save" buttons differ (in-answer notation and bookmarking in the review interface vs. a dedicated collection page) — see references/frontend-engine-rules.md §2, §3.

A complete end-to-end walkthrough example is in examples/walkthrough.md (GSAT Social Studies 111, the hardest subject).


Quality Thresholds (Apply Every Time, Never Drift)

ThresholdRule
Full Answer Verification (Mandatory)Every answer field must be checked one-by-one against the official answer key. Full check, no sampling. Resolve all mismatches to 0 before proceeding. Catches global parsing misalignment (structure checks cannot catch).
Explanation Red-Team (Mandatory)After AI generates multiple-choice and essay explanations, a mandatory adversarial red-team review is required. Ask the user before execution: full or spot-check. For spot-check, if true errors reach k≥4, n≈40 (lower bound of Wilson CI ≥ 4%), upgrade that subject to a stronger model; otherwise, continue.
Full-Width LintChinese paragraphs must not mix half-width punctuation. CI gate (lint.py + lint.yml). Corrections use CJK prefix rules (only convert a half-width clause punctuation mark that immediately follows a CJK character), prefer to miss a conversion than to convert incorrectly (maintain a ratio 3:1; preserve punctuation after numbers).
Explanation Requires VerificationEach explanation is tagged with confidence level c, and meta.note states: "AI-generated, not official answer. Verification required."
Restraint GateOnly fix confirmed errors (wrong answer identified, factual error, clearly mislabeled confidence). Do not fix for phrasing alone. Re-lint and re-validate after each fix, minimizing the change surface.
Faithful ReproductionParsing never rewrites, summarizes, or translates; question groups are never split; the self-check makes "faithful" verifiable.

Model Routing

Three tiers based on cost discipline, spending resources where reasoning is truly needed, and avoiding the cost inversion of "cheap generation → expensive verification":

TaskModel
Explanation Generation (multiple-choice + essay; text, facts, calculations)Opus or Codex Large Model (partial or full, user's choice)
Red-Team ReviewOpus or Codex (reviewer ≥ generator, see Principle 1)
Mechanical (answer verification, download/convert/file operations, structure/full-width lint)Sonnet / Haiku

Two principles:

  1. Red-team reviews upwards (reviewer ≥ generator): The reviewer must be at least as capable as the generator, otherwise it will miss true errors and flag false ones. Sonnet is not suitable for content red-team; it is only for mechanical and structural linting.
  2. Avoid cost inversion: A cheap model generates, then a strong model rewrites a large portion = you pay twice. Generate directly with a strong model once, and the red-team only needs light verification, which is overall more economical.

Empirical calibration (CPA exam, 2026-06): Sonnet ~67% errors on calculations, ~20% errors on text; Codex ~8% errors on calculations.

Red-team always uses the strongest model. The explanation red-team itself is mandatory and cannot be skipped; but full or spot-check is determined by the user — for spot-checks, a statistical stopping rule decides whether to upgrade, not per-question re-judgment. Empirical testing on the education track (Chinese, English, Social Studies): Sonnet generation + Opus spot-check, true error rate far below the upgrade threshold, so all subjects continue with Sonnet. (Exception: Full Answer Verification gate — always full check, no sampling.)


§9 Copyright and Clean-Room

Legal Basis: Copyright Act Article 9, Paragraph 1, Subparagraph 5

Exam papers and their backup exam papers held in accordance with the law shall not be the subject of copyright.

Therefore, official exam questions and standard answers can be freely reproduced, without authorization or payment. The standard answers are used as the authoritative answer key.

Clean-Room Discipline (Protected Content Cannot Be Touched)

§9 liberates the "exam questions" themselves, but not the value-added parts added by publishers:

  • ❌ Do not copy publisher layouts (categorization, difficulty labels, chapter mapping, passage introductions).
  • ❌ Do not copy publisher explanations; never feed publisher answer/explanation styles into any generation prompt.
  • ✅ Explanations are self-generated (looking only at official exam questions and official answers), all tagged as "AI-generated, verification required" with confidence levels, and passed through lint + mandatory red-team (full or spot-check).
  • ✅ Writing essays use official graded sample essays (highest to lowest scores); AI does not write complete essays. English short answers and Chinese-to-English translations have near-standard answers, AI can compile reference answers and tag them as requiring verification.

License: The methods and code (scripts, engine) are MIT; question data is in the public domain under §9; writing samples belong to the official authority and are provided under their own license. Rationale (see docs/DECISIONS.md): norms over laws — rather than forcing derivative works to be open-source via copyleft, it is better to give full freedom for forking, modifying, and commercial use, letting "open is better than closed" naturally establish norms.


Three Layers of Documentation (Don't Mix Them Up)

When replicating, you must write three different documents for different audiences. New open-source projects most often miss the third layer:

DocumentAudienceContent
SKILL.md (+ references/)AI agentThe replication manual body, loaded and executed by the agent (this file).
skill repo README.mdGitHub visitorsThe storefront: what this skill is, how to install, how to use, licensing.
Product/project README.mdGeneral public / contributorsVision + how to contribute — the most important for community participation, but most often omitted.

Base64 Safety Golden Rule (Highest Priority)

Putting any base64 string into a conversation, terminal, or tool output will trigger Anthropic's AUP content filter and kill the session — this is a project inviolable rule. The entire figure architecture is designed to keep base64 out of those channels entirely.

The data flow is three segments with clear responsibilities (only describe the architecture, never paste any base64 content):

Original PDF ──extract_figures──► data/figures/{filename}.png   (Standalone binary PNG)
                                           │
bank.json only writes figure="{filename}.png"      │  (Plain text, lintable, git diffable)
                                           ▼
build_app.py at build time: PNG ──► base64 ──► embedded in window.__FIGS__ (Output HTML only)

Fine-grained rules (agents/contributors must follow):

  • Never put any base64 string into a conversation, terminal output, tool parameter, or Read result.
  • Cropping/batch scripts only print counts and sizes (number of figures, bytes, filenames, coordinates, list of missing files); to view a figure, use Read to open the PNG file, do not cat, head, or feed bytes into the prompt.
  • bank.json / staging JSON stores only filenames; base64 lives only inside build_app.py's figures_block() and the final HTML.
  • js_safe_json() converts any occurrence of </ in the data to ``, preventing premature closing of <script> tags.

Scope is a Decision for the Maintainer, Not a Technical Decision

Which years / curricula / exam types to include is decided by the maintainer based on their target audience (education track: only new curriculum 111–115). When changing the target audience (adding old curriculum, another country's exams), adjust the inclusion scope accordingly; the rest of the process (reconnaissance → download → parse → bank → crop → explain → build) stays the same. GSAT and CAP share the same platform, with a test selector to switch between them; questions from different exams are not mixed by default. For national exams, each exam is presented independently to the user.

However, the national exam track has "shared leverage": Different exams often share core subjects (e.g., Clinical/Counseling psychologist exams both use Abnormal Psychology, Psychological Assessment, etc.). Before starting a new exam, create a "subject overlap matrix". Shared subjects are built once, tagged with an exams array, and deduplicated at the bank level (only merge if it's the exact same official paper), saving effort and ensuring consistency across exams — see references/shared-question-banks.md.

There is another layer of deduplication for mixed-paper simulation mode: content fingerprint deduplication before assembling a simulation set (stem + ordered options), and for twin questions across different years with the same stem but completely different options, never use stem-only deduplication; instead, use independent stem fingerprints + universal stem exemptions on the same practice session to ensure mutual exclusivity — also in references/shared-question-banks.md.


References Index

FileTopic
references/data-sources.mdData source reconnaissance, download, Copyright §9, clean-room, bank.json schema
references/parsing.mdJudgment-based parsing, markitdown vs PyMuPDF, per-subject parsers, idempotent merge, self-verification
references/figures.mdFigure extraction (full-block render), localization, band boundaries, base64 safety architecture, lossless fidelity
references/explanations-redteam.mdClean-room explanations, fixed three-paragraph structure + merged explanation rules, quality alignment via five mechanisms, model routing, adversarial red-team, Wilson stopping rule, restraint gate, lint, essay policy
references/build-deploy.mdBuild single-file/website, PWA/Service Worker, long-term size sustainability, product-layer convergence decisions
references/dirty-data-robustness.mdDirty data points in government/exam open data: NFKC normalization, relaxed matching, zero-match error reporting, no error swallowing, atomic writes, detection of broken ToUnicode in official PDF text layers and vision-based recovery hard gates; includes ceec "Missing character in 數a" teaching case + pre-fetch self-check list
references/shared-question-banks.mdCross-exam shared question banks (for national exams): subject overlap matrix, shared subjects built once, exams array for multi-exam tagging, deduplication discipline (merge only exact same official paper), content fingerprint deduplication for mixed-paper simulation mode, twin questions across years must not be stem-only deduplicated
references/frontend-engine-rules.mdFrontend answer engine: group / standalone question introduction rules (per-suit surface roles), question picking algorithm (weakness weighting, fingerprint cooldown, periodic review), distinction between "Mark" and "Save" buttons
examples/walkthrough.mdEnd-to-end example: GSAT Social Studies 111 (the most difficult subject)
examples/sample-output/Real output slices: GSAT Social Studies 111 question group (passage + sub-questions + figures + explanation JSON), showing what the pipeline produces
scripts/Reference implementations for each phase (model scripts: scrape / parse / crop / merge / build); judgment-based, requires adaptation to your own data; see scripts/README.md

Related Skills