Universal Prompt: Generate Knowledge Base Term Document

The "Base + Override" Architecture

You are generating a learning document for a single term in a specific technology stack. This document provides the Universal Structure (the Base). Before writing, you MUST read the _meta/technology_context.md file located in the target technology's folder to understand the Persona, Tone, and Coding Guidelines (the Override).


Instructions

Inputs

Provide these inputs before running:

  • Target Folder: (e.g. 03-javascript or 06-react or 15-rust)
  • Term name: (e.g. Closure or useState or `as` Casting)
  • Term description: (e.g. from the master list)
  • Level: (e.g. Level 3 — Functions & Scope)

Output

Save the generated document to:

knowledge-base/{Target Folder}/terms/level_{NN}/{term_name_snake_case}.md

Document Structure

Generate the document following this exact 7-section markdown structure. Every section is separated by a horizontal rule (---). Section numbers are fixed: §1 through §7, in the order shown below.

§1  Prerequisites
§2  Term Category
§3  Explanation
§4  Common Mistakes & Pitfalls
§5  Practice Exercises
§6  Related Terms
§7  Key Takeaways

Section-by-Section Specifications


§0 — Document Header

# {Term Name}

> **{Level}**
> {One-sentence term description}

---

The H1 is the exact, human-readable term name (e.g. `as` Casting (Primitive Numeric Coercion) or Unit Type (())). The blockquote block contains the level label on line 1 and the description on line 2.


§1 — Prerequisites

## 1. Prerequisites

- [Term Name](relative/path/term.md) — One-line reminder of what it means.
- [Term Name](relative/path/term.md) — One-line reminder of what it means.

---

List the terms the reader must already understand before learning this term. Use 2–5 items. For each:

  • Use the term name as a clickable cross-link.
  • Append followed by a brief one-line reminder of what it means (not a full definition).

CROSS-LINKING RULE:

  • Same technology folder → relative path from the terms/ directory (e.g. [Variable](../level_01/variable.md)).
  • Different technology folder → step out with ../../../ (e.g. [Promise](../../../03-javascript/terms/level_06/promise.md)).

STRICT MARKDOWN LINK SYNTAX: Always use - [Human Readable Title](relative/path.md) — Description:

  • Place only the clean human-readable title inside [...].
  • Place only the relative file path inside (...).
  • NEVER embed the file path inside the title brackets.
  • ✅ Correct: - [SELECT](../level_03/select.md) — The query statement.
  • ❌ Wrong: - [SELECT (../level_03/select.md)](../level_03/select.md) — The query statement.

CROSS-LINKING & MISSING TERMS: Link to relevant terms even if they don't exist yet. If the target file is missing:

  1. Write the link using a best-guess relative path.
  2. At the end of your response, list all missing terms you linked to.
  3. When told to create missing term files:
    • Deduplicate: Search _meta files for existing synonyms first.
    • Categorize: Assign the correct folder, level, and learning order.
    • Update master list: Insert it into _meta/*_terms_zero_to_hero.md.
    • Generate: Create the term file following this prompt.
    • Fix links: Update any broken links in other files pointing to the new term.
    • Commit: Commit all cascade changes atomically.

RELATIONSHIP REGISTRY (Single Source of Truth): Before writing Prerequisites and Related Terms:

  1. Read _meta/relationships.json in the target technology folder.
  2. Use any existing registered edges as the authoritative list.
  3. After generating the term file, update _meta/relationships.json:
    • Add (or update) the entry for this term.
    • Include all prerequisites and related terms with their descriptions.
  4. Run node validate_relationships.js to verify graph consistency.
  5. Run node build_cross_module_index.js if any cross-module edges were added.

⚠️ Sections are located by their heading text, not by number. Tools that update Prerequisites or Related Terms MUST search by heading name.


§2 — Term Category

## 2. Term Category

**{Category Label} ({Parenthetical Qualifier})**: {1–2 paragraphs explaining what kind of
construct this is, how it differs from analogous features in other languages or frameworks,
and the precise conceptual role it plays in this technology.}

---

Format:

  • Start with a bold label that names the category and a parenthetical qualifier that captures the term's defining character in one short phrase.
    • Example: **Rust Keyword (the blunt instrument)**
    • Example: **Rust-specific (the explicitness)**
    • Example: **React Hook (the state anchor)**
  • Write 1–2 paragraphs explaining:
    • What kind of construct this is (keyword, function, trait, hook, concept, etc.).
    • How it differs from analogous features in other languages or frameworks.
    • The precise problem it solves or role it plays.

Do not just write a one-liner classification. Give the reader meaningful context for why this thing exists and why it looks the way it does.


§3 — Explanation

## 3. Explanation

### (1) Design Motivation — "Why did we design this?"

{Story of the problem that existed before this concept, why existing alternatives were
insufficient, and what goal the designers had in mind. 2–4 paragraphs.}

### (2) Reality Metaphor

{One concrete metaphor from everyday life, business, nature, or engineering that maps
directly to the concept. Explain the mapping explicitly. 1–3 paragraphs.}

### (3) {Technology} Code Examples

#### Short Snippet
\`\`\`{language}
// 5–15 lines demonstrating the core concept in isolation.
// Include inline comments on the key lines.
\`\`\`

#### Fuller Example
\`\`\`{language}
// 15–40 lines showing real-world usage in a mini-scenario.
// Use comments to explain non-obvious behavior.
// Follow the coding guidelines in technology_context.md.
\`\`\`

---

Design Motivation — Tell the story: What was painful before? What alternatives existed? Why were they insufficient? Why did the designers make this choice?

Reality Metaphor — Use one cohesive metaphor that maps cleanly. Explicitly state what each element of the metaphor corresponds to in the technology.

Code Examples — Name the subsection ### (3) {Technology} Code Examples (e.g. ### (3) Rust Code Examples, ### (3) JavaScript Code Examples). Provide two nested sub-sections:

  • Short Snippet (5–15 lines): Isolated demonstration of the concept. Include brief inline comments.
  • Fuller Example (15–40 lines): A mini real-world scenario. Comments should explain why, not just what.

§4 — Common Mistakes & Pitfalls

## 4. Common Mistakes & Pitfalls

### Mistake 1: {Short Title}

**The mistake:** {What the developer does wrong.}

**Why it's wrong:** {Why this is incorrect — compiler behavior, runtime behavior, data
corruption, conceptual misunderstanding, etc.}

*Incorrect:*
\`\`\`{language}
// code that demonstrates the mistake
\`\`\`

*Fix:*
\`\`\`{language}
// corrected code
\`\`\`

### Mistake 2: {Short Title}
...

### Mistake 3: {Short Title}
...

---

List exactly 3 mistakes. Each mistake must have all five elements: title, mistake description, explanation of why it's wrong, incorrect code, and corrected code.

Focus on mistakes that:

  • Beginners commonly make when first encountering this term.
  • Produce silent bugs or confusing compiler/runtime errors.
  • Reveal a conceptual misunderstanding, not just a typo.

§5 — Practice Exercises

## 5. Practice Exercises

### Exercise 1: {Descriptive Title}

**Scenario:** {2–4 sentences describing a real-world, professional context
(IoT, financial systems, compilers, databases, web APIs, etc.) that motivates
the exercise. Make it feel like a genuine engineering task.}

**Requirements:**
1. {Concrete, measurable task. Name the exact types, functions, or structs to define.}
2. {Another concrete task with specific behavioral requirements.}
3. {Another concrete task.}
(3–5 numbered requirements total)

> [!check]- Answer
>
> #### Implementation
>
> \`\`\`{language}
> // Full, working, runnable implementation.
> // Include inline comments explaining non-obvious decisions.
> // Include #[cfg(test)] / describe() / test blocks at the bottom.
> \`\`\`
>
> #### Technical Explanation
>
> 1. **{Key Concept}**: {1–3 sentences explaining why this specific language feature was
>    needed here, the tradeoffs made, and any subtle behavior (e.g. truncation, saturation,
>    lifetimes, borrow rules).}
> 2. **{Another Key Concept}**: {Explanation.}
> 3. **{Another Key Concept}**: {Explanation.}
> (3–5 numbered points)

---

### Exercise 2: {Descriptive Title}

**Scenario:** {Different domain from Exercise 1.}

**Requirements:**
1. ...
2. ...
3. ...

> [!check]- Answer
>
> #### Implementation
>
> \`\`\`{language}
> // Full implementation with tests
> \`\`\`
>
> #### Technical Explanation
>
> 1. **{Key Concept}**: {Explanation.}
> 2. ...

---

### Exercise 3: {Descriptive Title}

**Scenario:** {Different domain from Exercises 1 and 2.}

**Requirements:**
1. ...
2. ...
3. ...

> [!check]- Answer
>
> #### Implementation
>
> \`\`\`{language}
> // Full implementation with tests
> \`\`\`
>
> #### Technical Explanation
>
> 1. **{Key Concept}**: {Explanation.}
> 2. ...

---

Quality bar for exercises — each one must:

  1. Use a distinct real-world domain (e.g. IoT telemetry, financial pricing, database internals, game engine, compiler tooling, network protocol, distributed systems). No two exercises in the same file should use the same domain.

  2. Scenario — Write 2–4 sentences that establish a professional engineering context. The reader should understand why this exercise matters in production. Avoid toy problems.

  3. Requirements — Number each requirement. Be specific: name the exact structs, types, functions, traits, or methods to implement. Specify the exact signatures, error types, and behavioral invariants. Give the reader enough detail to write the code without guessing.

  4. Implementation (inside the callout):

    • Must be full, working, runnable code — not pseudocode or skeletons.
    • Must include a #[cfg(test)] / describe() / test block at the bottom of the code.
    • Tests must assert concrete values (assert_eq!, assert!(matches!(...)), etc.) — not just assert!(result.is_ok()) alone.
    • Include inline comments on lines that use the term being taught, explaining why that specific form was chosen.
  5. Technical Explanation (inside the callout):

    • Write 3–5 numbered analytical points.
    • Each point must have a bold title followed by 1–3 sentences.
    • Explain the mechanism — why did the language/runtime behave this way? What invariants are upheld? What would happen if you did it differently?
    • Connect back explicitly to the term being taught.

EXERCISE FORMAT RULES — DO NOT DEVIATE:

  • Exercises use **Scenario:** + **Requirements:**NOT **Problem:**.
  • The answer callout is > [!check]- AnswerNOT > [!tip]-.
  • Inside the callout, use > #### Implementation then > #### Technical ExplanationNOT > **Explanation:**.
  • Separate all three exercises with ---.
  • Do not place any code blocks outside the > [!check]- callout.

⚠️ CALLOUT PREFIX RULE — CRITICAL: Every single line inside > [!check]- MUST start with > . This includes every line of the code block — the opening fence, all code lines, blank separator lines, and the closing fence. Failure to prefix any line breaks the callout and renders code outside it.

✅ CORRECT — every line, including code body, is prefixed with > :

> [!check]- Answer
>
> #### Implementation
>
> ```typescript
> interface Fish {
>   swim(): void;
> }
>
> function isFish(pet: Fish | Bird): pet is Fish {
>   return (pet as Fish).swim !== undefined;
> }
> ```

❌ WRONG — code lines after the opening fence are missing > :

> [!check]- Answer
>
> #### Implementation
>
> ```typescript
> interface Fish {
  swim(): void;      ← ❌ missing `> `
}
                    ← ❌ blank line missing `> `
function isFish ... ← ❌ missing `> `
```                 ← ❌ closing fence missing `> `

Golden Rule: When writing multi-line code inside a callout, every single character row must begin with > (blockquote + space). There are no exceptions — not for blank lines, not for closing fences.

Auto-fix: If bare lines are found in existing files, run:

node knowledge-base/fix_callout_prefixes.js [folder|--all]

## 6. Related Terms

- [Term Name](relative/path/term.md) — One-line description of how it relates.
- [Term Name](relative/path/term.md) — One-line description of how it relates.
- [Term Name](relative/path/term.md) — One-line description of how it relates.

---

List 3–5 related terms. Follow the same CROSS-LINKING RULE and STRICT MARKDOWN LINK SYNTAX defined in §1.

For each item, the description should explain how this related term connects to the current term (contrast, complement, alternative, superset, etc.) — not just what the related term is in isolation.

Related terms should be drawn from _meta/relationships.json. If a term is clearly related but missing from the registry, add it and follow the CROSS-LINKING & MISSING TERMS procedure.


§7 — Key Takeaways

## 7. Key Takeaways

- {Most important thing to remember about this term.}
- {Second most important thing.}
- {Third most important thing.}
- {Optional fourth point.}
- {Optional fifth point.}

Write 3–5 bullet points. Each bullet should be:

  • A standalone, memorable statement — not a repeat of the definition.
  • Actionable or diagnostic: the reader should be able to use it to make decisions or catch mistakes.
  • Concise: one or two sentences maximum per bullet.

Do not add a --- after Key Takeaways (it's the last section).


Filename Convention

Convert the exact term name to a snake_case markdown filename:

  1. Lowercase all letters.
  2. Remove all special characters: ` [ ] ! ? ( ) < > #.
  3. Replace spaces, hyphens, and slashes with a single underscore _.

Examples:

  • `as` Casting (Primitive Numeric Coercion)as_casting.md
  • Unit Type (())unit_type.md
  • useState Hookusestate_hook.md

Quality Checklist (Self-review before saving)

Before saving the generated file, verify:

  • All 7 sections present in order, each separated by ---.
  • §2 Term Category starts with a Bold Label (parenthetical qualifier): format.
  • §3 Explanation has all three subsections: Design Motivation, Reality Metaphor, Code Examples.
  • §3 Code Examples subsection name includes the technology name (e.g. ### (3) Rust Code Examples).
  • §4 has exactly 3 mistakes, each with all 5 elements (title, mistake, why, incorrect code, fix).
  • §5 has exactly 3 exercises, each with Scenario + Requirements + Implementation + Technical Explanation.
  • All exercise code blocks are inside the > [!check]- Answer callout.
  • Every line inside > [!check]- callouts starts with > — including code body lines, blank lines, and closing fences.
  • All implementations include test code.
  • Technical Explanation has 3–5 numbered bold-titled points per exercise.
  • Cross-links use correct relative paths and clean [Title](path.md) — Description syntax.
  • _meta/relationships.json updated and node validate_relationships.js passes.
  • No section uses **Problem:**, > [!tip]-, **Expected output:**, or **Explanation:** (those are the old format).

Git Commit Guidelines

When committing, use Conventional Commits format with the level_NN scope:

docs(level_{NN}): add {Term Name} term doc
Built with LogoFlowershow