feat: DB-driven KB topic manager — admin UI + migration

- Create kb_generator_topics table (140 topics migrated from hardcoded array)
- kb_intent_generator.php now loads active topics from DB instead of $BATCHES array
- Admin panel: MANAGE TOPICS button opens full topic manager modal
  - Browse all 140 topics with search, category, and active/disabled filters
  - Inline active toggle per topic (checkbox)
  - Add new topic form (topic_id, category, name, description)
  - Edit existing topics (all fields)
  - Delete topics with confirmation
  - Run count display
- Backend API cases: kb_topics, kb_topic_save, kb_topic_delete, kb_topic_toggle
- Topics can now be added/managed without any code changes

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014p87VFec84hNaf2WpvmLrW
This commit is contained in:
2026-07-02 07:04:20 -05:00
parent a13f750846
commit 7327104612
2 changed files with 275 additions and 283 deletions
+10 -283
View File
@@ -83,289 +83,16 @@ if ($forceRun) log_line('Force-run flag set — bypassing 20-hour guard.');
log_line('Starting daily KB intent generation run.');
/* ── topic batches (25 topics × ~40 intents = 1,000+) ── */
$BATCHES = [
['id' => 'math_arith', 'category' => 'mathematics', 'topic' => 'Arithmetic and number sense',
'desc' => 'place value to billions, prime vs composite, GCF/LCM, order of operations (PEMDAS), integer arithmetic, absolute value, rounding and estimation, scientific notation, divisibility rules, factors and multiples, mental math strategies, number line, comparing and ordering decimals'],
['id' => 'math_fractions', 'category' => 'mathematics', 'topic' => 'Fractions, decimals, and percentages',
'desc' => 'equivalent fractions, simplifying fractions, adding/subtracting unlike denominators, multiplying/dividing fractions, mixed numbers vs improper fractions, converting between fractions/decimals/percentages, percent increase/decrease, discount and tax calculations, ratio and proportion, unit rate, cross-multiplication'],
['id' => 'math_algebra1', 'category' => 'mathematics', 'topic' => 'Algebra I — equations and inequalities',
'desc' => 'one-step and two-step equations, distributing and combining like terms, solving inequalities, graphing on a number line, slope-intercept form (y=mx+b), point-slope form, standard form, graphing linear equations, systems of equations (substitution, elimination, graphing), functions vs relations, domain and range'],
['id' => 'math_algebra2', 'category' => 'mathematics', 'topic' => 'Algebra II — advanced functions',
'desc' => 'quadratic formula and discriminant, completing the square, factoring (trinomials, difference of squares, grouping), polynomial long division, synthetic division, rational expressions, radical expressions, complex numbers, exponential functions, logarithms and log properties, sequences (arithmetic/geometric), binomial theorem'],
['id' => 'math_geometry', 'category' => 'mathematics', 'topic' => 'Geometry — shapes, proofs, and measurements',
'desc' => 'types of angles (complementary, supplementary, vertical, corresponding), triangle congruence (SSS, SAS, ASA, AAS, HL), similarity and scale factors, Pythagorean theorem and its converse, special right triangles (30-60-90, 45-45-90), circle theorems (inscribed angles, chords, arcs), area and perimeter of all polygons, surface area and volume of 3D solids, coordinate geometry, transformations (translation, rotation, reflection, dilation), two-column proofs'],
['id' => 'math_trig', 'category' => 'mathematics', 'topic' => 'Trigonometry',
'desc' => 'SOH-CAH-TOA, unit circle (all quadrants), reference angles, reciprocal trig functions (csc, sec, cot), inverse trig functions, trig identities (Pythagorean, sum/difference, double-angle), Law of Sines and Law of Cosines, solving trig equations, graphing sine and cosine (amplitude, period, phase shift), radians vs degrees, polar coordinates'],
['id' => 'math_precalc', 'category' => 'mathematics', 'topic' => 'Pre-calculus',
'desc' => 'function composition and inverses, piecewise functions, transformations of functions, polynomial end behavior, rational function asymptotes, partial fractions, conic sections (parabola, ellipse, hyperbola, circle), parametric equations, vectors (magnitude, dot product, component form), matrices (operations, determinants, inverses), systems of nonlinear equations, limits concept introduction'],
['id' => 'math_calc1', 'category' => 'mathematics', 'topic' => 'Calculus I — limits and derivatives',
'desc' => 'epsilon-delta definition of limit, limit laws, one-sided limits, limits at infinity, continuity, Intermediate Value Theorem, definition of derivative, power rule, product rule, quotient rule, chain rule, implicit differentiation, related rates, Mean Value Theorem, Rolle\'s theorem, critical points, first and second derivative tests, optimization problems, curve sketching'],
['id' => 'math_calc2', 'category' => 'mathematics', 'topic' => 'Calculus II — integrals and series',
'desc' => 'Riemann sums, Fundamental Theorem of Calculus, u-substitution, integration by parts, trig substitution, partial fractions, improper integrals, area between curves, volumes of revolution (disk/washer/shell), arc length, sequences vs series, convergence tests (integral, comparison, ratio, root, alternating series), Taylor and Maclaurin series, power series radius of convergence'],
['id' => 'math_stats', 'category' => 'mathematics', 'topic' => 'Statistics and probability',
'desc' => 'mean/median/mode/range, standard deviation and variance, normal distribution (68-95-99.7 rule), z-scores, sampling methods (random, stratified, cluster), bias in studies, correlation vs causation, scatter plots and regression lines, probability rules (addition, multiplication, conditional), permutations vs combinations, binomial distribution, hypothesis testing basics, p-values, confidence intervals, Type I and II errors'],
['id' => 'math_discrete', 'category' => 'mathematics', 'topic' => 'Discrete mathematics',
'desc' => 'set theory (union, intersection, complement, De Morgan\'s laws), logic gates and truth tables, proof techniques (direct, contradiction, induction), graph theory (vertices, edges, paths, trees), Euler and Hamiltonian paths, counting principles (multiplication rule, pigeonhole), modular arithmetic, cryptography basics (RSA overview), recursion, finite automata, Boolean algebra'],
['id' => 'math_linear', 'category' => 'mathematics', 'topic' => 'Linear algebra',
'desc' => 'vectors in R2/R3, vector addition and scalar multiplication, linear combinations and span, matrix multiplication, matrix transpose, determinant (2x2 and 3x3), inverse matrix, row reduction and RREF, systems of linear equations as matrices, rank and nullity, eigenvalues and eigenvectors, diagonalization, dot product and cross product, linear transformations, projections'],
['id' => 'sci_scientific', 'category' => 'science', 'topic' => 'Scientific method and experimental design',
'desc' => 'forming a hypothesis, independent vs dependent variables, control groups and constants, experimental vs observational studies, data collection methods, accuracy vs precision, significant figures, error analysis, scientific notation in measurements, peer review process, correlation vs causation, pseudoscience red flags, famous experiments in science history'],
['id' => 'bio_cell2', 'category' => 'biology', 'topic' => 'Cell biology — structure and function',
'desc' => 'prokaryotic vs eukaryotic cells, plant vs animal cell differences, organelle functions (nucleus, mitochondria, ribosome, ER rough/smooth, Golgi, lysosome, vacuole, chloroplast), cell membrane structure (phospholipid bilayer, membrane proteins), passive transport (diffusion, osmosis, facilitated diffusion), active transport, endocytosis/exocytosis, cell cycle phases (G1/S/G2/M), mitosis stages in detail, cytokinesis'],
['id' => 'bio_genetics', 'category' => 'biology', 'topic' => 'Genetics — inheritance and molecular biology',
'desc' => 'Mendel\'s laws (segregation, independent assortment), monohybrid and dihybrid crosses, Punnett squares, incomplete vs codominance, sex-linked traits, pedigree analysis, DNA double helix structure, base pairing (A-T, G-C), DNA replication (helicase, polymerase, ligase), transcription (DNA→mRNA), translation (mRNA→protein via ribosomes and tRNA), mutations (point, frameshift, silent, nonsense), genetic disorders (Down syndrome, sickle cell, Huntington\'s, cystic fibrosis)'],
['id' => 'bio_evolution', 'category' => 'biology', 'topic' => 'Evolution and natural selection',
'desc' => 'Darwin\'s voyage and observations, four conditions for natural selection, artificial selection examples, types of variation (genetic, phenotypic), genetic drift and founder effect, bottleneck effect, gene flow, Hardy-Weinberg equilibrium, speciation (allopatric vs sympatric), reproductive isolation mechanisms, convergent vs divergent evolution, homologous vs analogous structures, vestigial structures, fossil record as evidence, comparative anatomy and embryology, molecular phylogenetics, tree of life'],
['id' => 'bio_ecology2', 'category' => 'biology', 'topic' => 'Ecology — populations and communities',
'desc' => 'population growth (exponential vs logistic), carrying capacity, predator-prey cycles (Lotka-Volterra), competitive exclusion principle, keystone species, ecological succession (primary vs secondary), trophic levels (producers/consumers/decomposers), energy flow (10% rule), nutrient cycles (carbon, nitrogen, water, phosphorus), biome types and characteristics, invasive species impacts, island biogeography, biodiversity indices'],
['id' => 'bio_human', 'category' => 'biology', 'topic' => 'Human physiology — organs and systems',
'desc' => 'cardiovascular system (heart chambers, valves, blood pressure, cardiac output), respiratory system (mechanics of breathing, gas exchange at alveoli, pulmonary volumes), digestive system (enzyme actions at each stage, absorption in small intestine, large intestine water reabsorption), nervous system (neuron structure, action potential, synapse, CNS vs PNS, reflex arcs), endocrine system (pituitary, thyroid, adrenal, pancreas, hormones), urinary system (nephron function, filtration/reabsorption/secretion), immune system (innate vs adaptive, B-cells, T-cells, antibodies, vaccines)'],
['id' => 'bio_micro', 'category' => 'biology', 'topic' => 'Microbiology — bacteria, viruses, and fungi',
'desc' => 'bacterial cell structure (cell wall, flagella, plasmids), bacterial reproduction (binary fission, conjugation, transformation, transduction), antibiotic mechanisms and resistance, virus structure (capsid, envelope, spike proteins), viral replication cycle (lytic vs lysogenic), HIV/AIDS mechanism, common diseases by pathogen type, Koch\'s postulates, fungal cell wall (chitin), mycology basics, prions, archaea vs bacteria, microbiome and human health'],
['id' => 'chem_atomic', 'category' => 'chemistry', 'topic' => 'Atomic structure and the periodic table',
'desc' => 'subatomic particles (proton/neutron/electron), atomic number vs mass number, isotopes and atomic mass calculation, electron configuration (s/p/d/f orbitals), aufbau principle, Pauli exclusion, Hund\'s rule, periodic table groups and periods, trends (atomic radius, ionization energy, electronegativity, electron affinity), metals/nonmetals/metalloids, alkali metals, halogens, noble gases'],
['id' => 'chem_bonding', 'category' => 'chemistry', 'topic' => 'Chemical bonding and molecular structure',
'desc' => 'ionic bond formation (metal + nonmetal), lattice energy, covalent bonds (single/double/triple), Lewis dot structures, formal charge, resonance structures, VSEPR theory (linear/trigonal planar/tetrahedral/trigonal bipyramidal/octahedral), bond polarity vs molecular polarity, intermolecular forces (London dispersion, dipole-dipole, hydrogen bonding), metallic bonding, network solids, hybrid orbitals (sp/sp2/sp3)'],
['id' => 'chem_reactions', 'category' => 'chemistry', 'topic' => 'Chemical reactions and stoichiometry',
'desc' => 'balancing chemical equations, types of reactions (synthesis, decomposition, single/double displacement, combustion, acid-base, redox), oxidation states, identifying oxidizing/reducing agents, mole concept and Avogadro\'s number, molar mass calculations, percent composition, empirical vs molecular formula, stoichiometric calculations, limiting reagent, theoretical vs actual vs percent yield, solution stoichiometry (molarity, dilution)'],
['id' => 'chem_thermo', 'category' => 'chemistry', 'topic' => 'Thermochemistry and kinetics',
'desc' => 'enthalpy (ΔH), endothermic vs exothermic reactions, Hess\'s law, bond enthalpy, heat capacity and calorimetry (q=mcΔT), entropy (ΔS) and disorder, Gibbs free energy (ΔG = ΔH - TΔS), spontaneity, reaction rate factors (temperature, concentration, surface area, catalysts), collision theory, activation energy, Arrhenius equation, reaction mechanisms, rate laws, zero/first/second order reactions, half-life'],
['id' => 'chem_equil', 'category' => 'chemistry', 'topic' => 'Chemical equilibrium and acids/bases',
'desc' => 'Le Chatelier\'s principle (temperature, pressure, concentration changes), equilibrium constant K (Kc and Kp), reaction quotient Q, ICE tables, Ksp and solubility product, common ion effect, Arrhenius/Brønsted-Lowry/Lewis acid-base definitions, strong vs weak acids and bases, Ka and Kb, pH and pOH calculations, buffer solutions (Henderson-Hasselbalch), titration curves, indicators, hydrolysis of salts'],
['id' => 'phys_mechanics', 'category' => 'physics', 'topic' => 'Classical mechanics',
'desc' => 'kinematics equations (big four), free fall and g = 9.8 m/s², projectile motion (horizontal/vertical components), Newton\'s three laws in detail, free body diagrams, normal force, tension, friction (static vs kinetic, μ), inclined planes, circular motion (centripetal force and acceleration), universal gravitation (F = Gm1m2/r²), work-energy theorem, conservative vs non-conservative forces, elastic vs inelastic collisions, center of mass, rotational motion (torque, moment of inertia, angular momentum)'],
['id' => 'phys_waves', 'category' => 'physics', 'topic' => 'Waves, sound, and optics',
'desc' => 'transverse vs longitudinal waves, wavelength/frequency/amplitude/period relationships (v=fλ), standing waves and harmonics, Doppler effect, sound intensity (decibels), resonance, interference (constructive/destructive), diffraction, reflection (law of reflection), refraction (Snell\'s law, index of refraction), total internal reflection, lenses (converging/diverging, focal length), mirrors (concave/convex), optical instruments (telescope, microscope), polarization, double-slit experiment'],
['id' => 'phys_em', 'category' => 'physics', 'topic' => 'Electricity and magnetism',
'desc' => 'electric charge (Coulomb\'s law), electric field lines, electric potential (voltage), capacitance, Ohm\'s law (V=IR), series vs parallel circuits, Kirchhoff\'s voltage and current laws, electric power (P=IV), magnetic fields (right-hand rules), magnetic force on moving charge (F=qvB), electromagnetic induction, Faraday\'s law, Lenz\'s law, transformers, AC vs DC, Maxwell\'s equations overview, electromagnetic spectrum'],
['id' => 'phys_thermo', 'category' => 'physics', 'topic' => 'Thermodynamics and modern physics',
'desc' => 'temperature scales (Celsius/Fahrenheit/Kelvin conversions), thermal expansion, ideal gas law (PV=nRT), kinetic molecular theory, first law of thermodynamics (ΔU=Q-W), second law (entropy always increases), heat engines and efficiency, Carnot cycle, blackbody radiation, photoelectric effect, Bohr model of hydrogen, de Broglie wavelength, Heisenberg uncertainty principle, nuclear reactions (fission vs fusion), radioactive decay types (alpha/beta/gamma), half-life calculations, E=mc²'],
['id' => 'earth_geo', 'category' => 'science', 'topic' => 'Geology — rocks, minerals, and plate tectonics',
'desc' => 'mineral identification (hardness, luster, cleavage, streak, color), Mohs scale, rock cycle in detail, igneous rocks (intrusive vs extrusive, granite vs basalt, crystal size), sedimentary rocks (clastic/chemical/organic, deposition environments), metamorphic rocks (contact vs regional, foliated vs non-foliated), relative vs absolute dating, index fossils, half-life and radiometric dating, plate boundaries (convergent/divergent/transform), subduction zones, mountain building, seafloor spreading, paleomagnetism as evidence'],
['id' => 'earth_atmos', 'category' => 'science', 'topic' => 'Atmosphere, weather, and meteorology',
'desc' => 'atmospheric layers (troposphere/stratosphere/mesosphere/thermosphere/exosphere), atmospheric composition, air pressure and altitude, Coriolis effect, global wind patterns (trade winds, westerlies, polar easterlies), Hadley/Ferrel/Polar cells, weather fronts (cold/warm/stationary/occluded), air masses and their source regions, cloud types (cumulus/stratus/cirrus/cumulonimbus), dew point and relative humidity, thunderstorm anatomy, tornado formation, hurricane structure and categories, El Niño/La Niña'],
['id' => 'earth_ocean', 'category' => 'science', 'topic' => 'Oceanography and hydrosphere',
'desc' => 'ocean zones (epipelagic/mesopelagic/bathypelagic/abyssopelagic/hadal), ocean currents (surface vs deep thermohaline circulation), tides (gravitational pull of Moon and Sun), wave generation and breaking, ocean chemistry (salinity, pH, oxygen levels), coral reef ecosystems and bleaching, marine food webs, overfishing and bycatch, plastic pollution, ocean acidification mechanism, hydrothermal vents and chemosynthesis, sea level rise and coastal erosion'],
['id' => 'environ_sci', 'category' => 'science', 'topic' => 'Environmental science and sustainability',
'desc' => 'ecosystem services, carbon cycle and carbon sinks, nitrogen cycle (fixation, nitrification, denitrification), greenhouse gases (CO2, methane, N2O, water vapor), greenhouse effect vs global warming, climate feedback loops (positive/negative), renewable energy types (solar/wind/hydro/geothermal), fossil fuel formation and combustion impacts, deforestation rates and consequences, biodiversity hotspots, endangered species classifications (IUCN), sustainable agriculture, circular economy, life cycle assessment'],
['id' => 'hist_ancient', 'category' => 'history', 'topic' => 'Ancient civilizations — Egypt, Greece, Rome, Mesopotamia',
'desc' => 'Mesopotamian city-states (Sumer, Akkad, Babylon), Code of Hammurabi, cuneiform writing, ziggurat architecture, Egyptian Old/Middle/New Kingdoms, pharaohs (Ramesses II, Cleopatra, Tutankhamun), hieroglyphics and Rosetta Stone, pyramids of Giza construction theories, Greek city-states (Athens vs Sparta), Athenian democracy origins, Persian Wars (Marathon, Thermopylae, Salamis), Peloponnesian War, Macedonian Empire under Alexander the Great, Roman Republic institutions (Senate, consuls, tribunes), Punic Wars, Julius Caesar\'s rise and assassination, Pax Romana, causes of Rome\'s fall'],
['id' => 'hist_medieval', 'category' => 'history', 'topic' => 'Medieval period and the Middle Ages (500-1500)',
'desc' => 'fall of Western Roman Empire, Byzantine Empire at Constantinople, feudalism structure (king/lords/knights/serfs), manorialism and serfdom, Catholic Church power (Pope vs monarchs, Investiture Controversy), Crusades (1st through 4th), Reconquista in Spain, Black Death (bubonic plague) and its social impact, Magna Carta (1215) and its significance, Hundred Years\' War, Joan of Arc, Mongol Empire (Genghis and Kublai Khan), Silk Road trade, Islamic Golden Age (algebra, astronomy, medicine), feudal Japan (samurai, shogunate)'],
['id' => 'hist_early_mod', 'category' => 'history', 'topic' => 'Early modern period — Renaissance, Reformation, Exploration (1400-1700)',
'desc' => 'Italian Renaissance origins (Florence, Medici patronage), humanism philosophy, Leonardo da Vinci, Michelangelo, Raphael, Gutenberg\'s printing press impact, Protestant Reformation (Martin Luther\'s 95 Theses, Calvin, Zwingli), Catholic Counter-Reformation and Council of Trent, Spanish Inquisition, Age of Exploration (motivations: gold/god/glory), Portuguese exploration (Vasco da Gama, Magellan), Spanish conquest (Columbus, Cortés/Aztecs, Pizarro/Incas), Columbian Exchange, Atlantic slave trade beginnings, Thirty Years\' War, Scientific Revolution (Copernicus, Galileo, Newton)'],
['id' => 'hist_revolutions', 'category' => 'history', 'topic' => 'Age of Revolutions (1700-1850)',
'desc' => 'Enlightenment thinkers (Locke, Rousseau, Voltaire, Montesquieu) and their ideas, American Revolution causes (taxation without representation, Boston Massacre, Tea Party), Declaration of Independence key ideas, Articles of Confederation weaknesses, Constitutional Convention of 1787, Bill of Rights, French Revolution phases (Estates General, storming Bastille, Reign of Terror, Thermidorian Reaction), Napoleon\'s rise, Code Napoleon, Napoleonic Wars, Congress of Vienna, Latin American independence movements (Bolívar, San Martín, Toussaint L\'Ouverture), Industrial Revolution in Britain (spinning jenny, steam engine, factories, urbanization)'],
['id' => 'hist_19c', 'category' => 'history', 'topic' => '19th century — imperialism and nationalism',
'desc' => 'European colonialism in Africa (Berlin Conference/Scramble for Africa 1884-85), British Empire at peak (India as the crown jewel, Opium Wars in China), Social Darwinism ideology, Meiji Restoration in Japan, Crimean War, unification of Germany (Bismarck) and Italy (Risorgimento), US westward expansion and Manifest Destiny, Trail of Tears and Native American displacement, American Civil War causes (slavery, states\' rights, sectionalism), key battles (Gettysburg, Antietam), Reconstruction, Reconstruction Amendments (13th/14th/15th), Gilded Age robber barons'],
['id' => 'hist_ww1', 'category' => 'history', 'topic' => 'World War I (1914-1918)',
'desc' => 'MAIN causes (Militarism, Alliance system—Triple Alliance vs Triple Entente, Imperialism, Nationalism), assassination of Franz Ferdinand, Schlieffen Plan, trench warfare conditions, Western Front stalemate, Eastern Front collapse, new weapons technology (machine guns, poison gas, tanks, airplanes, submarines), U-boat campaign and sinking of Lusitania, US entry (1917), Zimmermann Telegram, Russian Revolution and withdrawal, Battle of Somme casualties, Treaty of Versailles terms, League of Nations creation and US rejection, redrawing of European map'],
['id' => 'hist_interwar', 'category' => 'history', 'topic' => 'Interwar period and rise of fascism (1919-1939)',
'desc' => 'Great Depression causes (Black Tuesday 1929, bank failures, Smoot-Hawley tariff, Dust Bowl), Hoovervilles, FDR\'s New Deal programs (CCC, WPA, Social Security, FDIC), rise of Nazism in Germany (Weimar Republic failures, hyperinflation, Hitler\'s Mein Kampf), Nuremberg Laws and early persecution, Mussolini\'s fascist Italy, Spanish Civil War as testing ground, Japanese expansionism in Asia (Manchuria, Nanjing), Soviet collectivization and Gulag, Stalin\'s purges, Appeasement policy, Nazi-Soviet Pact'],
['id' => 'hist_ww2', 'category' => 'history', 'topic' => 'World War II (1939-1945)',
'desc' => 'Blitzkrieg tactics, Battle of Britain (RAF vs Luftwaffe), Operation Barbarossa (German invasion of USSR), Battle of Stalingrad as turning point, Pacific Theater (Pearl Harbor, Midway, island-hopping campaign), Holocaust (Nuremberg Laws to Final Solution, Wannsee Conference, six major death camps, six million Jews plus five million others), D-Day (June 6 1944), Battle of the Bulge, firebombing of Dresden and Tokyo, Manhattan Project and atomic bombs (Hiroshima August 6, Nagasaki August 9), V-E Day and V-J Day, war crimes tribunals at Nuremberg'],
['id' => 'hist_cold_war', 'category' => 'history', 'topic' => 'Cold War (1947-1991)',
'desc' => 'Truman Doctrine and containment policy, Marshall Plan, Berlin Blockade and Airlift, NATO formation, Korean War (38th parallel, UN coalition), McCarthyism and Red Scare, Suez Crisis, Hungarian Revolution 1956, Sputnik launch and Space Race, Cuban Revolution and Castro, Bay of Pigs failure, Cuban Missile Crisis (13 days), Berlin Wall construction, Vietnam War escalation (Gulf of Tonkin), Tet Offensive, Nixon\'s détente and visit to China, SALT treaties, Soviet invasion of Afghanistan, Reagan\'s military buildup, fall of Berlin Wall 1989, Soviet collapse 1991'],
['id' => 'hist_civil_rights', 'category' => 'history', 'topic' => 'US Civil Rights Movement',
'desc' => 'Reconstruction\'s end and Jim Crow laws, Plessy v. Ferguson (1896) separate but equal, Great Migration north, NAACP founding and legal strategy, Brown v. Board of Education (1954), Montgomery Bus Boycott and Rosa Parks, Little Rock Nine, sit-in movement (Greensboro), Freedom Riders, March on Washington and \'I Have a Dream\' speech, Birmingham campaign (Bull Connor), Civil Rights Act of 1964, Voting Rights Act of 1965, Malcolm X and Black Power, assassination of MLK, Fair Housing Act 1968, long-term impact and ongoing inequality'],
['id' => 'hist_20c_world', 'category' => 'history', 'topic' => 'Modern world history (1945-2000)',
'desc' => 'decolonization waves (India 1947, African independence 1950s-60s), creation of Israel and Arab-Israeli wars (1948, 1967, 1973), apartheid in South Africa and Mandela, partition of India and Pakistan, Chinese Communist Revolution and Mao Zedong (Great Leap Forward, Cultural Revolution), Korean War armistice, Vietnam War end and reunification, Cambodian genocide (Khmer Rouge), Iran Islamic Revolution 1979, Iran-Iraq War, Gulf War 1991, Yugoslav Wars and ethnic cleansing, Rwandan genocide 1994, Oslo Accords and peace process'],
['id' => 'govt_us', 'category' => 'civics', 'topic' => 'US government — structure and function',
'desc' => 'Article I: Congress (bicameral, House apportionment, Senate 2 per state, legislative process including conference committee), Article II: President (electoral college, cabinet, executive orders, veto power, commander in chief), Article III: Supreme Court (judicial review established by Marbury v. Madison, original vs appellate jurisdiction, lifetime appointments), federalism (enumerated/implied/reserved/concurrent powers, 10th Amendment), checks and balances examples, constitutional amendments process, political parties history'],
['id' => 'govt_state_local', 'category' => 'civics', 'topic' => 'State and local government',
'desc' => 'state constitutions vs US Constitution, governors\' powers, state legislatures (unicameral vs bicameral), state court systems, initiative and referendum process, recall elections, state budget process, county government (commissioners, sheriff, tax assessor), city government types (mayor-council, council-manager, commission), school boards, special districts, home rule charters, municipal bonds, local taxation (property tax), zoning and land use'],
['id' => 'govt_econ_pol', 'category' => 'economics', 'topic' => 'Economic policy and the Federal Reserve',
'desc' => 'monetary policy tools (federal funds rate, open market operations, reserve requirements, discount rate), quantitative easing, inflation targeting (2% goal), Federal Reserve structure (Board of Governors, 12 regional banks, FOMC), fiscal policy (government spending and taxation), Keynesian vs supply-side economics, automatic stabilizers, budget deficit vs national debt, crowding out effect, Laffer curve, trade policy (tariffs, quotas, trade agreements—USMCA, WTO), balance of payments'],
['id' => 'us_const_law', 'category' => 'civics', 'topic' => 'Constitutional law and landmark Supreme Court cases',
'desc' => 'Marbury v. Madison (judicial review), McCulloch v. Maryland (necessary and proper clause), Dred Scott v. Sandford, Plessy v. Ferguson, Brown v. Board of Education, Griswold v. Connecticut (right to privacy), Miranda v. Arizona (Miranda rights), Roe v. Wade and Dobbs v. Jackson, Obergefell v. Hodges (same-sex marriage), Citizens United v. FEC (campaign finance), District of Columbia v. Heller (Second Amendment), NFIB v. Sebelius (ACA), Dobbs v. Jackson Women\'s Health, recent First Amendment cases'],
['id' => 'econ_micro', 'category' => 'economics', 'topic' => 'Microeconomics — consumers and firms',
'desc' => 'utility and marginal utility, consumer surplus, producer surplus, deadweight loss, price elasticity of demand and supply, income elasticity, cross-price elasticity, production function (inputs, outputs), total/average/marginal costs, economies of scale, short run vs long run, perfect competition (many sellers, price taker, normal profit), monopoly (price maker, deadweight loss, barriers to entry), oligopoly (interdependence, game theory, Nash equilibrium, price leadership), monopolistic competition (product differentiation, advertising)'],
['id' => 'econ_macro', 'category' => 'economics', 'topic' => 'Macroeconomics — national and global economy',
'desc' => 'GDP calculation methods (expenditure: C+I+G+NX; income: wages+rents+interest+profits), real vs nominal GDP, GDP deflator, business cycle phases (expansion, peak, contraction, trough), types of unemployment (frictional, structural, cyclical, seasonal), natural rate of unemployment, Phillips curve trade-off, CPI calculation and core inflation, hyperinflation examples (Weimar, Zimbabwe, Venezuela), multiplier effect, aggregate demand/supply model, short-run vs long-run equilibrium, stagflation'],
['id' => 'econ_personal', 'category' => 'economics', 'topic' => 'Personal finance and consumer economics',
'desc' => 'creating a personal budget, 50/30/20 rule, zero-based budgeting, emergency fund sizing (3-6 months expenses), compound interest calculations, Rule of 72, credit score components (FICO: payment history 35%, amounts owed 30%, length of credit history 15%, new credit 10%, credit mix 10%), how credit cards work (APR, minimum payment trap, grace period), types of loans (mortgage, auto, personal, student), debt-to-income ratio, net worth calculation, tax brackets and effective vs marginal tax rates'],
['id' => 'lit_classics', 'category' => 'literature', 'topic' => 'Classic American and British literature',
'desc' => 'The Great Gatsby (American Dream critique, symbolism — green light, Valley of Ashes, Gatsby\'s parties), To Kill a Mockingbird (racial injustice, moral growth, Atticus Finch), Of Mice and Men (friendship, dreams, euthanasia themes), Romeo and Juliet (fate, impulsive love, family conflict), Hamlet (revenge, procrastination, \'To be or not to be\'), Macbeth (ambition, guilt, supernatural), 1984 (totalitarianism, doublethink, surveillance), Brave New World (dystopia, conditioning, soma), Lord of the Flies (human nature, civilization vs savagery), Catcher in the Rye (alienation, phoniness, adolescence)'],
['id' => 'lit_world', 'category' => 'literature', 'topic' => 'World literature and diverse voices',
'desc' => 'One Hundred Years of Solitude (magic realism, Buendía family, Macondo), Things Fall Apart (colonialism\'s impact on Igbo culture, Okonkwo\'s tragedy), The Alchemist (personal legend, journey metaphor), Don Quixote as first modern novel, Dostoevsky\'s Crime and Punishment (guilt and redemption), Tolstoy\'s War and Peace, Kafka\'s The Metamorphosis (alienation, absurdism), Camus and existentialism (The Stranger, The Plague), Chimamanda Ngozi Adichie, Haruki Murakami, postcolonial literature themes'],
['id' => 'lit_poetry', 'category' => 'literature', 'topic' => 'Poetry — forms, devices, and analysis',
'desc' => 'poetry forms (sonnet 14 lines—Shakespearean vs Petrarchan, haiku 5-7-5, villanelle, free verse, ode, elegy, ballad, epic), meter (iambic pentameter, feet: iamb/trochee/spondee/dactyl/anapest), rhyme scheme (ABAB CDCD EFEF GG), sound devices (alliteration, assonance, consonance, onomatopoeia), figurative language (simile, metaphor, personification, hyperbole, understatement, synecdoche, metonymy), imagery and sensory details, tone vs mood, theme vs subject, major poets (Emily Dickinson, Walt Whitman, Langston Hughes, Maya Angelou, Robert Frost, Pablo Neruda)'],
['id' => 'grammar_writing', 'category' => 'literature', 'topic' => 'Grammar, mechanics, and writing craft',
'desc' => 'parts of speech (noun, pronoun, verb, adjective, adverb, preposition, conjunction, interjection), sentence types (simple, compound, complex, compound-complex), clauses (independent vs dependent), phrases (noun, verb, prepositional, participial, gerund, infinitive), common errors (run-ons, comma splices, sentence fragments, dangling modifiers, subject-verb agreement, pronoun-antecedent agreement), punctuation rules (semicolons, colons, dashes, commas in all uses), parallel structure, active vs passive voice, essay structure (thesis, body paragraphs, counterargument, conclusion), MLA/APA citation basics'],
['id' => 'rhetoric', 'category' => 'literature', 'topic' => 'Rhetoric, argument, and persuasion',
'desc' => 'Aristotle\'s three appeals: ethos (credibility), pathos (emotion), logos (logic), rhetorical situation (author, audience, purpose, context), claim types (fact, value, policy), types of evidence (statistical, anecdotal, expert testimony, analogical), logical fallacies in detail (ad hominem, straw man, false dichotomy, slippery slope, appeal to authority, bandwagon, red herring, circular reasoning, hasty generalization, post hoc ergo propter hoc), Toulmin model (claim, grounds, warrant, backing, qualifier, rebuttal), analyzing speeches and op-eds'],
['id' => 'fin_budgeting', 'category' => 'personal_finance', 'topic' => 'Budgeting, saving, and debt management',
'desc' => 'tracking income vs expenses, fixed vs variable expenses, budget apps (Mint, YNAB, EveryDollar), paying yourself first, high-yield savings accounts vs regular savings, CDs and money market accounts, emergency fund where to keep it, good debt vs bad debt, credit card interest calculation (daily periodic rate), minimum payment trap math, debt avalanche (highest interest first) vs snowball (smallest balance first) method, student loan types (subsidized vs unsubsidized, PLUS, private), income-driven repayment plans, loan forgiveness programs'],
['id' => 'fin_investing2', 'category' => 'personal_finance', 'topic' => 'Investing — stocks, bonds, and retirement',
'desc' => 'individual stocks vs index funds vs ETFs, expense ratios and why they matter, S&P 500 historical returns (~10% nominal), asset allocation by age, rebalancing portfolio, tax-advantaged accounts (401k contribution limits, employer match, traditional vs Roth tax treatment, IRA income limits), Social Security benefits calculation, Medicare basics, required minimum distributions, capital gains tax (short-term vs long-term rates), wash sale rule, dividend reinvestment, bond ratings (investment grade vs junk), duration and interest rate risk'],
['id' => 'fin_taxes', 'category' => 'personal_finance', 'topic' => 'Taxes — income, deductions, and filing',
'desc' => 'W-2 vs W-4 vs 1099 forms, filing status (single, MFJ, MFS, HOH, qualifying widow(er)), standard deduction vs itemizing, above-the-line vs below-the-line deductions, credits vs deductions difference, EITC and Child Tax Credit, Schedule C for self-employment, SE tax, quarterly estimated taxes, AMT basics, state income taxes, property taxes and how assessed, sales tax vs use tax, gift tax exclusion, estate tax threshold, IRS audit red flags, free filing options'],
['id' => 'health_chronic', 'category' => 'health', 'topic' => 'Chronic disease prevention and management',
'desc' => 'Type 2 diabetes: insulin resistance mechanism, A1C test, glycemic control strategies, prevention through lifestyle, Type 1 vs Type 2 differences, cardiovascular disease risk factors (LDL vs HDL cholesterol, triglycerides, blood pressure categories—normal/elevated/Stage 1/Stage 2 hypertension, ASCVD risk calculator), metabolic syndrome criteria, cancer screening guidelines (mammogram, colonoscopy, PSA, Pap smear) by age and risk, BMI limitations as metric, waist circumference as predictor, sleep apnea screening, chronic pain management approaches'],
['id' => 'mental_health2', 'category' => 'mental_health', 'topic' => 'Mental health — therapy, medication, and recovery',
'desc' => 'DSM-5 major categories, cognitive behavioral therapy (CBT) techniques (thought records, behavioral activation, exposure hierarchy), dialectical behavior therapy (DBT) skills (mindfulness, distress tolerance, emotion regulation, interpersonal effectiveness), EMDR for trauma, psychodynamic therapy, medication classes (SSRIs, SNRIs, benzodiazepines, mood stabilizers, antipsychotics — mechanisms and side effects), finding a therapist (types of licenses: LCSW, LPC, psychologist, psychiatrist), crisis resources (988 Suicide and Crisis Lifeline), stigma reduction, peer support groups'],
['id' => 'substances', 'category' => 'health', 'topic' => 'Substance use, addiction, and recovery',
'desc' => 'addiction as brain disease (dopamine pathway, nucleus accumbens, prefrontal cortex), tolerance and withdrawal, alcohol (BAC levels and effects, liver disease progression, fetal alcohol syndrome, DSM criteria for AUD), opioids (natural, semi-synthetic, synthetic — fentanyl 100x morphine), opioid overdose signs and naloxone (Narcan) administration, stimulants (cocaine, meth, amphetamines), cannabis effects on developing brain, vaping and e-cigarette risks (EVALI), treatment approaches (MAT with buprenorphine/methadone, 12-step programs, inpatient vs outpatient), harm reduction philosophy'],
['id' => 'nutrition2', 'category' => 'health', 'topic' => 'Advanced nutrition and dietetics',
'desc' => 'macronutrient ratios for different goals (endurance vs strength vs weight loss), complete vs incomplete proteins, essential amino acids, omega-3 vs omega-6 fatty acids (EPA/DHA sources, anti-inflammatory role), fiber types (soluble vs insoluble, prebiotic fiber), micronutrient deficiencies (iron deficiency anemia, vitamin D and bone health, B12 deficiency in vegans, iodine and thyroid, zinc and immune function), food label reading (serving sizes, ingredient order, added sugars), ultra-processed food research, Mediterranean diet evidence, gut microbiome diversity'],
['id' => 'fitness2', 'category' => 'health', 'topic' => 'Exercise science and performance',
'desc' => 'FITT principle (frequency, intensity, time, type), periodization (linear vs undulating), compound lifts (squat, deadlift, bench press, overhead press — form cues), RPE scale and heart rate zones, VO2 max testing and improvement, lactate threshold training, EPOC (afterburn effect), muscle fiber types (Type I slow-twitch vs Type IIa/IIb fast-twitch), DOMS explanation and management, overtraining syndrome signs, sleep and testosterone/cortisol balance, creatine monohydrate evidence, protein timing myth vs reality, progressive overload tracking'],
['id' => 'sleep_science', 'category' => 'health', 'topic' => 'Sleep science and circadian biology',
'desc' => 'sleep stages (N1/N2/N3 NREM and REM cycling), circadian rhythm and suprachiasmatic nucleus, melatonin production timing, sleep debt and recovery, adenosine buildup and caffeine mechanism, blue light and screen exposure, recommended hours by age group, sleep disorders (insomnia, sleep apnea—types and CPAP, narcolepsy, RLS, parasomnias), sleep hygiene evidence-based practices, napping science (20-min power nap vs 90-min full cycle), shift work health effects, chronic sleep deprivation cognitive impacts'],
['id' => 'cooking2', 'category' => 'cooking', 'topic' => 'Cooking techniques and food science',
'desc' => 'Maillard reaction vs caramelization (temperatures, foods, flavors produced), collagen breakdown in braising (why tough cuts get tender), emulsification (mayo, hollandaise — lecithin role), gluten development (flour protein content, kneading, resting), leavening agents (baking soda vs baking powder, yeast fermentation, steam), salt roles (seasoning, texture, curing, fermentation), knife cuts (brunoise, julienne, chiffonade, batonnet, dice sizes), pan sauces (fond, deglazing, reduction), sous vide temperature and time, fermentation (kimchi, sourdough starter maintenance, yogurt making)'],
['id' => 'ai_ml', 'category' => 'technology', 'topic' => 'Artificial intelligence and machine learning',
'desc' => 'supervised vs unsupervised vs reinforcement learning, training data and overfitting, bias in AI systems, neural network layers (input/hidden/output), activation functions, backpropagation, convolutional neural networks for image recognition, recurrent neural networks and LSTMs for sequence data, transformer architecture and attention mechanism, large language models (GPT, Claude, Gemini — how they work), prompt engineering basics, AI hallucination problem, generative AI (image synthesis, DALL-E, Midjourney), AI ethics (fairness, accountability, transparency), AI regulation debates'],
['id' => 'cybersec', 'category' => 'technology', 'topic' => 'Cybersecurity and digital safety',
'desc' => 'CIA triad (confidentiality, integrity, availability), threat actors (nation-states, hacktivists, cybercriminals, insiders), attack vectors: phishing (spear phishing, whaling), social engineering, malware types (ransomware, trojan, rootkit, keylogger, worm, virus), SQL injection, cross-site scripting (XSS), man-in-the-middle attacks, password security (length vs complexity, password managers, 2FA types — SMS vs authenticator vs hardware key), VPN use cases and limitations, zero-day vulnerabilities, patch management importance, NIST cybersecurity framework, GDPR and data privacy basics'],
['id' => 'web_dev', 'category' => 'technology', 'topic' => 'Web development fundamentals',
'desc' => 'HTML semantic elements (header, nav, main, article, aside, footer), CSS box model (content/padding/border/margin), Flexbox vs CSS Grid layout, responsive design (media queries, mobile-first), JavaScript fundamentals (DOM manipulation, event listeners, async/await, fetch API, JSON), HTTP methods (GET/POST/PUT/DELETE/PATCH), REST API design principles, HTTP status codes (200/201/301/302/400/401/403/404/500), cookies vs localStorage vs sessionStorage, CORS, HTTPS and TLS/SSL certificates, web accessibility (WCAG guidelines, ARIA attributes), performance optimization (lazy loading, minification, CDN)'],
['id' => 'networking', 'category' => 'technology', 'topic' => 'Computer networking and protocols',
'desc' => 'OSI model (7 layers — Physical/Data Link/Network/Transport/Session/Presentation/Application), TCP vs UDP (reliability vs speed trade-off), TCP three-way handshake (SYN/SYN-ACK/ACK), IP addressing (IPv4 vs IPv6, CIDR notation, subnetting), private vs public IP addresses (RFC 1918), NAT and PAT, DNS resolution process (recursive vs iterative), DHCP lease process, ARP, routing protocols (OSPF, BGP), VLANs, firewalls (stateful vs stateless), network topologies, Wireshark packet analysis basics, common ports (22/SSH, 80/HTTP, 443/HTTPS, 53/DNS, 25/SMTP, 3306/MySQL)'],
['id' => 'cloud_tech', 'category' => 'technology', 'topic' => 'Cloud computing and modern infrastructure',
'desc' => 'IaaS vs PaaS vs SaaS differences with examples, public vs private vs hybrid cloud, major providers (AWS, Azure, GCP — key services), virtualization (hypervisors Type 1 vs Type 2, containers vs VMs), Docker (images, containers, Dockerfile, volumes, networking), Kubernetes concepts (pods, nodes, deployments, services, ingress), serverless computing (Lambda, Cloud Functions), microservices vs monolith architecture, DevOps principles (CI/CD pipelines, infrastructure as code — Terraform/Ansible), auto-scaling, load balancing, CDN mechanics, object storage vs block storage vs file storage'],
['id' => 'cs_concepts', 'category' => 'computer_science', 'topic' => 'Computer science fundamentals',
'desc' => 'data structures (arrays, linked lists, stacks, queues, hash tables, trees, graphs, heaps), Big O notation (O(1)/O(log n)/O(n)/O(n log n)/O(n²)), sorting algorithms (bubble, selection, insertion, merge, quick, heap — time/space complexity), searching (linear vs binary search), tree traversals (inorder/preorder/postorder, BFS vs DFS), hash table collision resolution (chaining vs open addressing), recursion and memoization, dynamic programming (overlapping subproblems, optimal substructure), greedy algorithms, NP-hard vs P problems, basic compiler theory (lexing, parsing, AST)'],
['id' => 'tx_hist2', 'category' => 'texas', 'topic' => 'Texas independence and the Republic era',
'desc' => 'Stephen F. Austin as Father of Texas, Mexican immigration terms and empresario land grants, Antonio López de Santa Anna\'s centralist policies that angered Texans, Gonzales \'Come and Take It\' cannon skirmish, siege and Battle of the Alamo (February-March 1836 — Bowie, Travis, Crockett, ~200 defenders vs ~2,000 Mexican troops), Goliad Massacre, Sam Houston\'s retreat and strategy, Battle of San Jacinto (18 minutes, \'Remember the Alamo!\'), Texas Declaration of Independence, Republic of Texas presidents (Burnet, Houston, Lamar, Jones), annexation debate and US entry December 1845'],
['id' => 'tx_culture2', 'category' => 'texas', 'topic' => 'Texas food, music, and traditions',
'desc' => 'BBQ regions: East Texas (smoky, tomato sauce), Central Texas (salt/pepper rub, oak-smoked brisket — Lockhart and Taylor), West Texas (direct heat), South Texas (mesquite), Tex-Mex origins (fajitas, puffy tacos, queso, breakfast tacos differ from Mexican cuisine), chili — Texas \'Bowl of Red\' (no beans), kolaches (Czech immigrant legacy, especially in Central Texas), Blue Bell ice cream, Dr Pepper (Waco 1885), Austin as live music capital (6th Street, ACL Fest, SXSW), Willie Nelson, Waylon Jennings, George Strait, Selena, Beyoncé (Houston), rodeo (HLSR largest in world)'],
['id' => 'tx_land', 'category' => 'texas', 'topic' => 'Texas land, law, and property',
'desc' => 'Texas land grant history and republic-era sovereignty over public lands (unique among states — state retains public land, not federal government), homestead exemption and its generosity in Texas, community property state laws, no state income tax (trade-off: higher property taxes), water law (prior appropriation vs riparian doctrine in Texas — Rule of Capture for groundwater), mineral rights vs surface rights separation, oil and gas leases (royalties, working interests), eminent domain and Texas Constitution Article I §17, deed restrictions in unincorporated areas, Texas Open Beaches Act'],
['id' => 'tx_economy2', 'category' => 'texas', 'topic' => 'Texas industries and economic drivers',
'desc' => 'Permian Basin and its resurgence (horizontal drilling and fracking), Texas Railroad Commission regulating oil and gas, refinery corridor along Gulf Coast (Houston Ship Channel), LNG exports from Freeport and Sabine Pass, Texas as top wind energy state (West Texas and Panhandle capacity), semiconductor manufacturing (Samsung Austin, TI Dallas), defense contractors (Lockheed Martin Fort Worth, Raytheon), Dell Technologies (Round Rock), Tesla Gigafactory (Austin), SpaceX Starbase (Boca Chica), healthcare sector (Texas Medical Center in Houston — largest medical complex in world), agricultural exports (cotton, beef, pecans, sorghum)'],
['id' => 'dfw_deep', 'category' => 'texas', 'topic' => 'DFW Metroplex — business, culture, and growth',
'desc' => 'DFW Airport as second busiest by operations in US, American Airlines headquarters (Fort Worth), Fort Worth Stockyards National Historic District (Billy Bob\'s Texas, nightly cattle drive, Cowtown history), Sundance Square entertainment district, Kimbell Art Museum (Kahn building), Modern Art Museum of Fort Worth, Fort Worth Zoo (consistently top-ranked), Dallas Arts District (largest urban arts district in US), AT&T Stadium (Jerry World — Cowboys), Globe Life Field (Rangers), American Airlines Center (Mavs/Stars), Toyota Music Factory, Perot Museum of Nature and Science, ongoing population growth (4th largest metro)'],
['id' => 'us_politics2', 'category' => 'national', 'topic' => 'US electoral system and political parties',
'desc' => 'Electoral College mechanics (538 total, 270 to win, winner-take-all in 48 states, Maine/Nebraska district method), faithless electors, 12th Amendment and tie-breaking by House, presidential primary system (caucuses vs primaries, superdelegates in Democratic Party), gerrymandering types (packing vs cracking), redistricting and census cycle, campaign finance law (FEC, super PACs post-Citizens United, dark money 501c4s, contribution limits), third parties and spoiler effect (Duverger\'s Law), swing states and Electoral College strategy, voter turnout patterns by demographic'],
['id' => 'us_social', 'category' => 'national', 'topic' => 'US social issues and culture wars',
'desc' => 'abortion debate: Roe v. Wade history, Casey v. Planned Parenthood undue burden standard, Dobbs decision and state-level landscape, viability and fetal pain debates, gun control: Second Amendment interpretation, AR-15 and assault weapons ban debate, background check gaps (gun show loophole), red flag laws, mass shooting frequency and response, immigration politics: border security vs humanitarian obligations, DACA recipients, asylum law, Title 42, remain in Mexico policy, transgender issues in sports and healthcare, DEI programs, affirmative action (SFFA v. Harvard decision 2023), drug legalization debate'],
['id' => 'us_media2', 'category' => 'national', 'topic' => 'US media landscape and information ecosystems',
'desc' => 'legacy media decline (newspaper closures, local news desert problem), cable news business model (outrage = ratings), Fox News vs MSNBC audience segmentation, social media news consumption, Twitter/X transformation under Musk, Facebook and political content algorithms, TikTok and national security debate (ByteDance, data collection concerns), YouTube and radicalization pathways, podcasting replacing radio, Substack and newsletter journalism, fact-checking organizations (PolitiFact, Snopes, FactCheck.org), media literacy skills for students, Section 230 debate, AI-generated news and deepfakes'],
['id' => 'world_climate', 'category' => 'world', 'topic' => 'Climate change — science, politics, and impacts',
'desc' => 'IPCC reports and scientific consensus, 1.5°C vs 2°C warming targets (Paris Agreement), tipping points (West Antarctic ice sheet, Amazon dieback, permafrost methane release, Atlantic circulation weakening), observed impacts already occurring (sea level rise rate, Arctic sea ice minimum records, coral bleaching frequency, wildfire seasons lengthening, extreme heat events), climate refugees projections, carbon budget remaining, carbon capture technologies (DAC, BECCS), solar geoengineering controversy (stratospheric aerosol injection), just transition for fossil fuel workers, climate justice and vulnerable nations'],
['id' => 'world_tech_race', 'category' => 'world', 'topic' => 'Global technology competition',
'desc' => 'US-China semiconductor war (CHIPS Act, export controls on advanced chips and chip-making equipment, ASML extreme UV lithography monopoly), 5G infrastructure competition (Huawei bans in Western countries), AI development race (OpenAI/Google vs Alibaba/Baidu/Tencent), quantum computing race (implications for encryption), rare earth minerals as geopolitical leverage (China controls ~60% of production), India\'s tech emergence (Bengaluru, UPI digital payments), Israeli startup ecosystem, data localization laws vs global internet, digital currency competition (e-CNY vs US dollar dominance)'],
['id' => 'africa2', 'category' => 'world', 'topic' => 'Africa — economic potential and challenges',
'desc' => 'African Continental Free Trade Area (AfCFTA) — 54 countries, world\'s largest free trade zone by countries, China\'s investment in Africa via BRI (roads, ports, hospitals — debt trap diplomacy concerns), Sahel security crisis (Mali, Burkina Faso, Niger coups 2021-2023, Wagner Group presence), East African tech scene (M-Pesa mobile money in Kenya, Nairobi\'s Silicon Savannah), Nigeria as largest African economy (oil dependency, currency devaluation), South Africa\'s load-shedding power crisis (Eskom), Ethiopia\'s Grand Renaissance Dam dispute with Egypt, demographic dividend (youngest population globally by 2050), brain drain challenge'],
['id' => 'mid_east2', 'category' => 'world', 'topic' => 'Middle East — religion, oil, and geopolitics',
'desc' => 'Sunni-Shia divide (historical roots — Karbala, Ali\'s succession), Iran as Shia theocracy (Revolutionary Guards, velayat-e faqih), Saudi Arabia as Sunni leadership (Wahhabism, MBS modernization and authoritarianism), proxy conflict map (Iran: Hezbollah Lebanon, Hamas Gaza, Houthis Yemen, Iraqi militias vs Saudi/UAE/US backing), Israel-Palestine conflict: 1948 Nakba, 1967 Six-Day War and occupation, Oslo Accords failure, two-state solution obstacles (settlements, Jerusalem status, right of return), October 7 2023 Hamas attack and Gaza war, Turkish neo-Ottoman ambitions, Qatar gas wealth and Al Jazeera influence'],
['id' => 'sex_psychology', 'category' => 'sexuality', 'topic' => 'Psychology of sexuality and attraction',
'desc' => 'sexual orientation formation theories (biological: fraternal birth order effect, finger length ratio, twin studies; psychological: Kinsey scale, sexual fluidity), attraction science (pheromones debate, symmetry preference, waist-to-hip ratio, halo effect), love triangles (Sternberg: intimacy+passion+commitment), attachment theory in romantic relationships (secure, anxious, avoidant, disorganized styles), jealousy evolutionary theories, sexual fantasy prevalence studies (Joyal research), paraphilias vs paraphilic disorders (DSM-5 distinction), sexual addiction controversy (not in DSM-5), intersex conditions (prevalence ~1.7%, different from trans identity)'],
['id' => 'sex_health2', 'category' => 'sexuality', 'topic' => 'Comprehensive sexual health across the lifespan',
'desc' => 'adolescent sexual development (Tanner stages, first menstruation average age, nocturnal emissions, masturbation normalization), college sexual health (consent education, STI rates in 18-24 age group, hookup culture research), adult sexual health (frequency normalization, \'use it or lose it\' evidence for aging), postpartum sexuality (recovery timeline, breastfeeding and libido, pelvic floor recovery), menopause and sexual changes (vaginal atrophy, GSM—genitourinary syndrome, lubricants, local estrogen, ospemifene), male aging and sexual health (testosterone decline, ED prevalence by decade, PDE5 inhibitors: sildenafil vs tadalafil), older adult sexuality (cognitive decline and consent complexities)'],
['id' => 'astro_planets', 'category' => 'astronomy', 'topic' => 'Planetary science — geology, atmospheres, and moons',
'desc' => 'Mercury: no atmosphere, extreme temperature swings (-180 to 430°C), MESSENGER/BepiColombo missions; Venus: runaway greenhouse effect (464°C), retrograde rotation, sulfuric acid clouds, Magellan radar mapping; Mars: Olympus Mons largest volcano, Valles Marineris, thin CO2 atmosphere, evidence of ancient liquid water, seasonal dust storms, polar ice caps (CO2+H2O); Jupiter: Great Red Spot (shrinking storm), differential rotation, magnetosphere, ring system; Saturn: ring composition (97% water ice), ring gaps (Cassini Division), Titan\'s methane cycle; Uranus/Neptune: ice giants, Uranus axial tilt 98°, Neptune\'s winds 2100 km/h'],
['id' => 'astro_stellar2', 'category' => 'astronomy', 'topic' => 'Stellar astrophysics in depth',
'desc' => 'stellar nucleosynthesis stages (hydrogen burning, helium flash, CNO cycle in massive stars, triple-alpha process, s-process vs r-process for heavy elements), stellar classification (OBAFGKM spectral types, temperature ranges, color correlation), luminosity classes (I supergiant to V main sequence), variable stars (Cepheid period-luminosity relation used as standard candles, RR Lyrae), X-ray binaries (matter transfer, accretion disk), novae vs supernovae (white dwarf thermonuclear vs core collapse), pulsar timing precision (millisecond pulsars as gravitational wave detectors), magnetar flares and fast radio bursts'],
['id' => 'astro_cosmo', 'category' => 'astronomy', 'topic' => 'Observational cosmology and structure of the universe',
'desc' => 'cosmic distance ladder (stellar parallax → Cepheid variables → Type Ia supernovae → Hubble\'s Law), Hubble constant value dispute (H0 tension: CMB measurements ~67 vs local measurements ~73 km/s/Mpc), large-scale structure (filaments, voids, galaxy clusters, superclusters — Laniakea), cosmic web formation (dark matter halos as seeds), cosmic inflation evidence (flatness problem, horizon problem, monopole problem — all solved by inflation), baryon acoustic oscillations as standard ruler, gravitational lensing as mass probe (Einstein rings, cluster lensing maps of dark matter)'],
['id' => 'space_tech', 'category' => 'space', 'topic' => 'Spacecraft systems and engineering',
'desc' => 'thermal control systems (passive: coatings, MLI blankets; active: heat pipes, louvers, heaters), attitude control (reaction wheels, thrusters, star trackers, gyroscopes), power systems (solar panels — degradation rate in radiation, RTGs for outer planets: Pu-238), communication links (deep space network, high-gain vs low-gain antennas, signal delay to Mars: 3-22 minutes), propulsion types (chemical bipropellant: hypergolic vs cryogenic; electric: Hall thrusters, ion drives Isp comparison), radiation shielding approaches (water, polyethylene, depth of soil on Moon/Mars), autonomous navigation (optical navigation, terrain-relative navigation used by Perseverance landing)'],
['id' => 'space_future2', 'category' => 'space', 'topic' => 'Human spaceflight beyond Earth orbit',
'desc' => 'Mars transit timeline (6-9 month journey, radiation dose accumulation, vehicle shielding options), Mars surface challenges (gravity 38% of Earth, atmospheric pressure 0.6% of Earth, perchlorates in soil, dust storm seasons), ISRU (in-situ resource utilization): Martian CO2+H2O→CH4+O2 propellant (MOXIE experiment on Perseverance), extracting water ice at poles, 3D-printed regolith habitats, psychological factors (isolation, confined quarters, communication delay with Earth — delay means no real-time guidance), Mars One failure lessons, NASA Moon-to-Mars architecture, SpaceX Starship reusability economics for Mars'],
['id' => 'music_theory', 'category' => 'arts', 'topic' => 'Music theory and appreciation',
'desc' => 'staff notation (treble/bass clef, ledger lines, note values), time signatures (4/4, 3/4, 6/8, 5/4 odd meters), key signatures and circle of fifths, major vs minor scales and their emotional qualities, modes (Dorian, Phrygian, Lydian, Mixolydian, Aeolian, Locrian), chord construction (triads: major/minor/diminished/augmented; seventh chords: maj7, dom7, min7), chord progressions (I-IV-V-I, ii-V-I in jazz, 12-bar blues, Andalusian cadence), harmony and counterpoint, musical forms (sonata form, rondo, theme and variations, fugue), Western classical periods (Baroque, Classical, Romantic, Modern) with key composers'],
['id' => 'film_study', 'category' => 'arts', 'topic' => 'Film analysis and cinema history',
'desc' => 'film language: mise-en-scène (lighting, set design, costume, actor positioning), cinematography (camera angles — low/high/Dutch tilt, shots — extreme wide/wide/medium/close-up/ECU, camera movement — pan/tilt/tracking/dolly/steadicam), editing (continuity editing, jump cut, cross-cutting, montage — Eisenstein\'s theory, match cut), sound design (diegetic vs non-diegetic sound, Foley, score vs soundtrack), film movements (German Expressionism, Italian Neorealism, French New Wave, New Hollywood, Dogme 95), auteur theory, genre conventions (film noir, western, horror subgenres), three-act structure vs alternative narrative structures'],
['id' => 'visual_art', 'category' => 'arts', 'topic' => 'Visual art — history, movements, and techniques',
'desc' => 'prehistoric cave paintings (Lascaux, Chauvet — ochre and charcoal techniques), Egyptian art conventions (profile face, frontal eye, hierarchical scale), Greek sculpture evolution (Archaic smile → Classical contrapposto → Hellenistic drama), Renaissance techniques (chiaroscuro, sfumato, linear perspective — Brunelleschi\'s discovery), Baroque drama (Caravaggio\'s tenebrism), Impressionism (capturing light and movement — Monet water lilies, Renoir), Post-Impressionism (Van Gogh\'s brushwork, Cézanne\'s geometry as path to Cubism), Cubism (Picasso, Braque — multiple viewpoints), Abstract Expressionism (Pollock drip technique, Rothko color fields), Pop Art (Warhol, Lichtenstein), Contemporary art market and NFTs'],
['id' => 'philosophy2', 'category' => 'philosophy', 'topic' => 'Philosophy — branches and major thinkers',
'desc' => 'epistemology: Plato\'s Forms and cave allegory, Descartes\' cogito and methodological doubt, empiricism (Locke, Berkeley, Hume — tabula rasa, esse est percipi, problem of induction), Kant\'s synthetic a priori, Gettier problem and justified true belief, ethics: Kantian categorical imperative (two formulations), Mill\'s utilitarianism and harm principle, Rawls\' veil of ignorance and difference principle, virtue ethics (Aristotle\'s eudaimonia, four cardinal virtues), care ethics (Gilligan), metaethics (moral realism vs anti-realism), political philosophy: Hobbes\' Leviathan, Locke\'s natural rights, Rousseau\'s social contract, Nozick\'s libertarianism vs Rawls\' liberal egalitarianism, existentialism (Sartre: existence precedes essence, bad faith, Beauvoir, Camus\' absurdism)'],
['id' => 'world_religion2', 'category' => 'religion', 'topic' => 'Comparative religion and philosophy of religion',
'desc' => 'Hinduism: Brahman and Atman, four goals of life (dharma/artha/kama/moksha), four paths to moksha (jnana/bhakti/karma/raja yoga), major deities (Brahma/Vishnu/Shiva trinity, avatars of Vishnu, Devi), caste system history and discrimination, major texts (Vedas, Upanishads, Bhagavad Gita, Mahabharata, Ramayana), Buddhism: Four Noble Truths, Eightfold Path, Theravada vs Mahayana vs Vajrayana, bodhisattva concept, Zen and meditation, nirvana vs nibbana, Islam: Five Pillars, six articles of faith, Quran revelation to Muhammad, Sunni vs Shia split (historical cause), Hadith and Sharia, Judaism: Torah, Talmud, 13 principles of faith (Maimonides), denominations (Orthodox/Conservative/Reform/Reconstructionist), philosophy of religion (cosmological, ontological, teleological arguments for God; problem of evil)'],
['id' => 'mythology2', 'category' => 'culture', 'topic' => 'Mythology deep dive — creation myths and heroes',
'desc' => 'Greek creation: Chaos → Gaia → Titans → Olympians, Titanomachy, Gigantomachy; hero cycle (monomyth per Joseph Campbell — call, threshold, trials, death/rebirth, return); Perseus (Gorgon, Pegasus, Andromeda), Heracles 12 labors in detail, Odyssey themes (nostos, temptation, identity), Orpheus and Eurydice (looking back as metaphor), Norse: Yggdrasil world tree, nine realms, Ragnarök prophecy, Odin\'s sacrifices for wisdom, Loki as trickster, Egyptian: Ma\'at and cosmic order, Osiris-Set-Horus myth as prototype for dying-rising god, Thoth as wisdom deity, Aztec: five suns creation, Quetzalcoatl feathered serpent, Tlaloc rain god, Japanese: Izanagi/Izanami, Amaterasu in cave, Susanoo storm god, Hindu epics as mythology (Ramayana, Mahabharata)'],
['id' => 'sports_history', 'category' => 'sports', 'topic' => 'Sports history and cultural impact',
'desc' => 'Olympic Games history (ancient Greek Olympics 776 BCE, revival 1896 Athens, Jesse Owens 1936 Berlin, 1968 Mexico City Black Power salute, Munich massacre 1972, political boycotts 1980/1984), integration of professional sports (Jackie Robinson breaking MLB color barrier 1947, early NBA Black players, Althea Gibson and Arthur Ashe in tennis, Billie Jean King vs Bobby Riggs \'Battle of Sexes\'), Muhammad Ali\'s cultural impact (Cassius Clay, Vietnam draft refusal, \'Float like a butterfly\'), Title IX impact on women\'s sports, CTE and NFL concussion crisis, PED era in baseball (McGwire, Bonds, Mitchell Report), Lance Armstrong scandal, doping culture in cycling and track'],
['id' => 'auto_cars', 'category' => 'transportation', 'topic' => 'Automobiles — mechanics, history, and culture',
'desc' => 'internal combustion engine four-stroke cycle (intake/compression/power/exhaust), engine configurations (inline-4, V6, V8, flat/boxer), transmission types (manual clutch/gear system, automatic torque converter, CVT, dual-clutch), braking systems (disc vs drum, ABS operation, brake fade), suspension types (MacPherson strut, double wishbone, air suspension), turbocharging vs supercharging, EV drivetrain (battery pack, single-speed transmission, regenerative braking), charging standards (CCS, CHAdeMO, Tesla NACS becoming standard), range anxiety and charging infrastructure, autonomous vehicle SAE levels 0-5, car insurance types (liability/collision/comprehensive), VIN decoding'],
['id' => 'business_101', 'category' => 'business', 'topic' => 'Business fundamentals and entrepreneurship',
'desc' => 'business entity types (sole proprietorship — unlimited liability, partnership — general vs limited, LLC — operating agreement, corporation — C-corp double taxation vs S-corp pass-through, nonprofit 501c3), business plan components (executive summary, market analysis, competitive analysis, operations plan, financial projections), startup funding stages (bootstrapping, friends/family, angel investors typical check $25k-$500k, seed round, Series A/B/C, venture capital structure, IPO process), business model types (subscription, marketplace, freemium, SaaS, franchise), lean startup methodology (MVP, build-measure-learn loop, pivot), cash flow vs profit distinction (can be profitable but insolvent)'],
['id' => 'marketing', 'category' => 'business', 'topic' => 'Marketing and consumer psychology',
'desc' => '4Ps of marketing (product, price, place, promotion), STP framework (segmentation, targeting, positioning), customer personas, buyer\'s journey (awareness/consideration/decision), AIDA model (attention/interest/desire/action), brand equity and brand architecture, pricing strategies (cost-plus, value-based, penetration, skimming, psychological pricing — $9.99 effect), distribution channels (direct vs indirect, omnichannel), content marketing vs advertising, SEO basics (on-page vs off-page, E-E-A-T), social media algorithms, influencer marketing ROI, customer lifetime value (CLV) vs customer acquisition cost (CAC), Net Promoter Score'],
['id' => 'real_estate', 'category' => 'business', 'topic' => 'Real estate investing and the housing market',
'desc' => 'housing market fundamentals (supply/demand, affordability index, months of supply), mortgage types (conventional vs FHA vs VA vs USDA, fixed vs adjustable rate, 15 vs 30 year), mortgage process (pre-qualification vs pre-approval, underwriting, closing costs ~2-5% of loan), real estate investment types (rental properties — gross rent multiplier, cap rate calculation, cash-on-cash return; REITs — publicly traded vs private, dividend yields; house flipping — 70% rule; vacation rentals — Airbnb regulations), 1031 exchange tax deferral, depreciation deduction, home equity and HELOCs, property management basics, foreclosure process'],
['id' => 'law_criminal', 'category' => 'law', 'topic' => 'Criminal law and the justice system',
'desc' => 'elements of a crime (actus reus + mens rea + causation + concurrence), felony vs misdemeanor vs infraction, crime categories (property, violent, white-collar, victimless, organized), arrest and booking process, Miranda rights (when required and what they are), arraignment and initial appearance, bail determination factors, grand jury vs preliminary hearing, discovery process, plea bargaining (why 97% of federal cases), trial phases (jury selection/voir dire, opening statements, direct/cross examination, closing arguments, jury deliberation, verdict), sentencing guidelines (mandatory minimums, three-strikes laws), appeals process, habeas corpus'],
['id' => 'law_civil', 'category' => 'law', 'topic' => 'Civil law — torts, contracts, and family law',
'desc' => 'elements of a tort: duty, breach, causation, damages; intentional torts (battery, assault, false imprisonment, trespass, conversion, defamation — libel vs slander); negligence standard (reasonable person), contributory vs comparative negligence, strict liability (products liability, abnormally dangerous activities), contract elements (offer, acceptance, consideration, capacity, legality), contract defenses (fraud, duress, undue influence, mistake, impossibility), breach remedies (compensatory, consequential, liquidated, punitive damages, rescission, specific performance), family law (divorce types — fault vs no-fault, property division community vs equitable distribution, custody types — legal vs physical, modification standards, child support calculation methods)'],
['id' => 'environ_energy', 'category' => 'environment', 'topic' => 'Energy systems and the clean energy transition',
'desc' => 'energy units (joules, BTUs, kWh, MMBTU), energy density comparison (gasoline vs lithium-ion vs hydrogen), electricity generation mix by source (coal, natural gas, nuclear, hydro, wind, solar — US and global percentages), solar PV technology (monocrystalline vs polycrystalline vs thin-film, efficiency rates, capacity factor ~20% vs wind ~35%), offshore vs onshore wind trade-offs, battery storage (lithium-ion chemistry, grid-scale applications, pumped hydro as largest storage), nuclear power (fission vs fusion, PWR vs BWR reactor types, Chernobyl and Fukushima causes, small modular reactors, waste storage problem), green hydrogen production (electrolysis using renewable electricity), energy poverty globally'],
['id' => 'wildlife_bio', 'category' => 'environment', 'topic' => 'Wildlife biology and conservation',
'desc' => 'population viability analysis, minimum viable population size, extinction vortex, IUCN Red List categories (Extinct/Critically Endangered/Endangered/Vulnerable/Near Threatened/Least Concern), biodiversity hotspots (defined as >1,500 endemic plant species and lost >70% habitat — examples: Amazon, Madagascar, California Floristic Province), rewilding concepts (keystone species reintroduction — wolves in Yellowstone trophic cascade), CITES treaty and wildlife trafficking, poaching economics and anti-poaching technology, captive breeding programs (California condor, Arabian oryx, black-footed ferret), habitat corridors, climate change as extinction driver'],
['id' => 'psych_social', 'category' => 'psychology', 'topic' => 'Social psychology and group behavior',
'desc' => 'Milgram obedience experiment and lessons about authority, Stanford Prison Experiment and situationism (Zimbardo), Asch conformity experiments and social pressure, bystander effect and diffusion of responsibility, groupthink (symptoms: illusion of invulnerability, collective rationalization, stereotyping out-groups, pressure on dissenters, self-censorship), in-group vs out-group bias and minimal group paradigm, social identity theory (Tajfel and Turner), cognitive dissonance reduction strategies, prejudice vs stereotyping vs discrimination, contact hypothesis for reducing prejudice, social facilitation vs social loafing'],
['id' => 'psych_dev', 'category' => 'psychology', 'topic' => 'Developmental psychology across the lifespan',
'desc' => 'prenatal development stages (germinal/embryonic/fetal), teratogens and critical periods, infant attachment (Harlow\'s monkeys, Ainsworth\'s Strange Situation — secure/anxious/avoidant/disorganized), Piaget\'s four stages in detail (sensorimotor: object permanence; preoperational: egocentrism, animism, conservation failure; concrete operational: seriation; formal operational: abstract reasoning), Vygotsky\'s ZPD and scaffolding, theory of mind (autism spectrum connection), Erikson\'s 8 stages detailed (trust vs mistrust through integrity vs despair), identity formation in adolescence (Marcia\'s statuses), Kohlberg\'s moral stages, midlife crisis research (Levinson), late adulthood (wisdom, successful aging theories)'],
['id' => 'psych_cog', 'category' => 'psychology', 'topic' => 'Cognitive psychology — memory, attention, and thinking',
'desc' => 'Atkinson-Shiffrin memory model (sensory/short-term/long-term), working memory model (Baddeley: phonological loop, visuospatial sketchpad, central executive, episodic buffer), encoding specificity principle, elaborative rehearsal vs rote rehearsal, long-term memory types (explicit: semantic vs episodic; implicit: procedural, priming, conditioning), forgetting theories (decay, interference — proactive vs retroactive, motivated forgetting/repression), schemas and their role in comprehension and memory distortion, flashbulb memories and their reliability, false memory research (Loftus misinformation effect), dual-process theory (System 1 vs System 2), attention (selective, divided, sustained), inattentional blindness'],
['id' => 'medicine_basics', 'category' => 'health', 'topic' => 'Medical terminology and healthcare navigation',
'desc' => 'anatomy directional terms (anterior/posterior, superior/inferior, medial/lateral, proximal/distal, dorsal/ventral), body planes (sagittal, frontal/coronal, transverse), organ systems overview, vital signs (normal ranges for HR, BP, RR, temp, O2 sat), common lab values (CBC — RBC/WBC/platelets, CMP — glucose/creatinine/electrolytes, lipid panel, A1C, TSH), medical abbreviations (PRN, QD, BID, TID, QID, STAT, NPO), types of doctors (MD vs DO, primary care vs specialists), insurance terms (deductible, copay, coinsurance, out-of-pocket max, in-network vs out-of-network, formulary, prior authorization), patient rights (HIPAA, informed consent, advance directives, POLST)'],
['id' => 'pharmacology', 'category' => 'health', 'topic' => 'Pharmacology and medication safety',
'desc' => 'pharmacokinetics (ADME: absorption routes—oral bioavailability, first-pass effect; distribution—volume of distribution, blood-brain barrier; metabolism—CYP450 enzymes and drug interactions; elimination—half-life, renal vs hepatic clearance), pharmacodynamics (receptor agonist vs antagonist, dose-response curves, ED50 vs LD50, therapeutic window), drug interaction mechanisms (induction vs inhibition of CYP450), medication classes with mechanisms: beta-blockers, ACE inhibitors, statins, SSRIs, proton pump inhibitors, NSAIDs (GI and renal risks), opioid analgesics (mu receptor, constipation mechanism), antibiotics (bactericidal vs bacteriostatic, mechanisms of classes), vaccine immunology (live-attenuated vs inactivated vs subunit vs mRNA)'],
['id' => 'first_aid2', 'category' => 'health', 'topic' => 'Emergency medicine and first aid advanced',
'desc' => 'adult CPR sequence (check scene/unresponsive/call 911/30 compressions at 2 inches depth at 100-120/min/2 rescue breaths, AED when available), infant vs child vs adult CPR differences, choking adult Heimlich (5 back blows/5 abdominal thrusts) vs infant (5 back blows/5 chest thrusts), stroke recognition FAST (Face drooping, Arm weakness, Speech difficulty, Time to call 911), heart attack recognition (chest pressure radiating to jaw/arm, diaphoresis, nausea), hypoglycemia vs hyperglycemia recognition and response, anaphylaxis epipen technique (outer thigh, hold 10 seconds, call 911), tourniquet application (2 inches above wound, windlass until bleeding stops, note time), wound care (direct pressure, elevation, when to use tourniquet), burn classification and treatment (cool running water 20 min for minor, no ice, cover with clean cloth, hospital for 2nd/3rd degree)'],
['id' => 'prep_emergency', 'category' => 'safety', 'topic' => 'Emergency preparedness and disaster response',
'desc' => '72-hour kit vs full emergency supply list (water: 1 gallon/person/day for 2 weeks, food: non-perishables with 25-year shelf life, manual can opener, first aid kit, medications 30-day supply, important documents in waterproof container, cash in small bills, battery/solar/crank radio, flashlights and extra batteries, multi-tool, phone charger), shelter-in-place vs evacuation decision, FEMA\'s Ready.gov resources, community emergency response team (CERT) training, earthquake protocol (Drop-Cover-Hold On, stay indoors, don\'t run outside), tornado shelter (lowest floor, interior room, away from windows, bathtub with mattress over you), hurricane evacuation timing, flood never drive through water, wildfire defensible space and go-bag'],
['id' => 'auto_maint', 'category' => 'transportation', 'topic' => 'Vehicle maintenance and troubleshooting',
'desc' => 'oil change intervals (conventional every 3k-5k miles vs synthetic every 7.5k-10k miles), how to check oil level and color (black=dirty, milky=coolant leak, low=burn or leak), tire pressure and TPMS (proper inflation improves fuel economy 0.5-3%), tire rotation every 5k-7.5k miles and why, brake pad wear indicators (squeal vs grind), battery testing (CCA rating, 3-5 year lifespan, terminal corrosion cleaning), coolant system (50/50 mix, when to flush, overheating response — pull over, don\'t open cap hot), air filter replacement interval, transmission fluid check and change, serpentine belt inspection, warning lights meanings (check engine, oil pressure, battery, coolant temp, ABS), jump-starting procedure (red to positive then to positive, black to negative then to chassis ground)'],
['id' => 'nfl_football', 'category' => 'sports', 'topic' => 'American football rules and strategy',
'desc' => 'down-and-distance system, scoring (TD 6+PAT/2pt, FG 3, safety 2), offensive formations (shotgun, I-formation, spread, pistol), route trees (slant, curl, post, corner, go, cross), defensive schemes (4-3 vs 3-4, Cover 2/3/4, Tampa 2, zone vs man, blitz packages), clock management (two-minute drill, quarterback kneel, icing kicker), salary cap mechanics, franchise tag, NFL draft combine, Super Bowl history and records, CTE research and rule changes, pass interference vs defensive holding distinction, illegal contact, roughing the passer evolution'],
['id' => 'nba_basketball', 'category' => 'sports', 'topic' => 'Basketball rules, strategy, and analytics',
'desc' => 'shot clock (24s NBA), foul types (personal/flagrant 1 and 2/technical/intentional), offensive systems (triangle, Princeton, pace-and-space), pick-and-roll coverage schemes (drop/hedge/switch/ICE), zone defenses (2-3/1-3-1), intentional fouling late-game strategy, advanced stats (PER, True Shooting%, BPM, VORP, RAPTOR, on-off net rating), three-point revolution history (Curry effect, corner three value), position-less basketball trend, NBA draft lottery odds, salary cap and max contracts, Olympics basketball Dream Team history, global player pipeline'],
['id' => 'mlb_baseball', 'category' => 'sports', 'topic' => 'Baseball rules, analytics, and history',
'desc' => 'nine-inning structure, universal DH (2022), batting order philosophy (leadoff OBP, 3-4-5 heart, platoon splits), pitch types (four-seam, two-seam/sinker, cutter, slider, curveball 12-to-6 vs 11-to-5, changeup — circle/palm/vulcan), Statcast metrics (exit velocity, launch angle, spin rate, expected batting average), shift ban (2023), opener and bulk reliever strategy, baseball WAR components, steroid era and Mitchell Report, Negro Leagues history, integration (Jackie Robinson 1947), farm system and prospect pipeline, international signing rules, umpire evaluation system'],
['id' => 'soccer_rules', 'category' => 'sports', 'topic' => 'Soccer tactics and world football culture',
'desc' => 'offside law nuance (attacker interfering with play at moment of pass), advantage clause, VAR review criteria (clear and obvious error, factual/subjective matters), tactical evolution (4-4-2 to 4-2-3-1 dominance to 4-3-3/3-5-2), pressing intensity metrics (PPDA), xG (expected goals) and xA (expected assists), Opta and StatsBomb data, UEFA Champions League format, FIFA World Cup 2026 expansion to 48 teams and US/Canada/Mexico hosting, women\'s game growth (NWSL, WSL, European investment), player valuation and transfer windows, Financial Fair Play rules, South American football culture (ultras, Copa Libertadores)'],
['id' => 'combat_sports', 'category' => 'sports', 'topic' => 'MMA, boxing, and wrestling',
'desc' => 'UFC weight classes (115 strawweight through 265 heavyweight), MMA scoring criteria (effective striking, effective grappling, aggression, octagon control), striking arts (boxing combinations, muay thai — elbows/knees/clinch, kickboxing leg kicks), grappling foundations (wrestling: single leg/double leg/trip; BJJ: guard positions — closed/open/half/butterfly/spider/lasso, submissions — rear naked choke/triangle choke/armbar/heel hook), boxing 10-must scoring system, pound-for-pound rankings methodology, historical champions by era (Ali/Foreman/Frazier; Tyson era; Mayweather defensive mastery; Khabib grappling dominance; Jon Jones elite all-around), WADA testing in combat sports'],
['id' => 'golf_deep', 'category' => 'sports', 'topic' => 'Golf — technique, rules, and strategy',
'desc' => 'club fitting basics (shaft flex, loft, lie angle), shot shapes (draw — right-to-left for right-hander; fade — left-to-right; hook/slice as exaggerated versions), course management (playing to your miss, laying up vs going for it risk-reward, reading greens — grain, slope, speed), handicap index calculation (lowest 8 of last 20 differentials), Stableford vs stroke play vs match play formats, shotgun starts vs wave starts, PGA Tour mechanics (FedEx Cup points, top-125 exempt status, LIV Golf disruption and merger), major championships prestige ranking debate, Augusta National history (Masters traditions — green jacket, pimento cheese, Par 3 contest), equipment regulations (groove restrictions, MOI limits, anchored putting ban)'],
['id' => 'esports_deep', 'category' => 'sports', 'topic' => 'Esports industry and competitive gaming',
'desc' => 'esports revenue streams (~$1.8B global: media rights, sponsorship, mergers/acquisitions, merchandise, tickets), title-specific ecosystems (League of Legends: Riot Games structure, LCS/LEC/LCK/LPL regional leagues, Worlds format; CS:GO/CS2: Valve Major system, third-party ESL/BLAST tournaments; Dota 2: Valve Pro Circuit, TI $40M+ prize pool; Valorant: franchised VCT; Fortnite: FNCS open qualifiers), team organizational structure (players, head coach, analyst, performance coach, psychologist), streaming as career path (Twitch rev share, YouTube Gaming, Kick), burnout research (wrist/hand injuries, eye strain, isolation), Korean developmental structure influence, Chinese investment in esports'],
['id' => 'tennis_deep', 'category' => 'sports', 'topic' => 'Tennis technique, rules, and tour',
'desc' => 'scoring system (15/30/40/deuce/advantage/game; 6 games = set, tiebreak at 6-6 except Wimbledon final set; 3 or 5 sets depending on tournament), serve motion (toss placement, trophy position, pronation, kick serve vs flat vs slice), return of serve positioning and split-step timing, rally tactics (crosscourt percentages vs down-the-line risk, approach shot selection, net approaches and volley technique), surface differences (clay: high bounce/slow suits baseline grinders; grass: low bounce/fast suits serve-volleyers; hard: medium and varied by court), grand slam records (Djokovic 24, Nadal 22 Roland Garros dominance, Federer grass mastery, Serena Williams 23 Open Era), Davis Cup and Billie Jean King Cup team competition, ATP/WTA ranking point system'],
['id' => 'world_cuisines2', 'category' => 'cooking', 'topic' => 'Global cuisine exploration',
'desc' => 'French classical mother sauces (béchamel/velouté/espagnole/hollandaise/tomat — derivatives of each), Italian regional variation (North: risotto Milanese/ossobuco/pesto Genovese/carbonara egg-only rule; South: pizza Napoletana DOC rules, eggplant parmigiana), Japanese knife skills (santoku vs yanagiba vs deba purposes, honbazuke sharpening on water stone), Indian spice blooming in ghee (whole spices first, ground second), mole negro complexity (30+ ingredients, multiple chili types, chocolate without sweetness), Ethiopian injera fermentation (teff flour, 3-day ferment, communal mesob serving), Peruvian cuisine rise (ceviche — leche de tigre curing; lomo saltado — Chinese-Peruvian fusion; causa; anticuchos)'],
['id' => 'whiskey_deep', 'category' => 'cooking', 'topic' => 'Whiskey — bourbon, Scotch, and world whisky',
'desc' => 'bourbon legal requirements (51%+ corn mash bill, new charred oak barrels only, distilled to no more than 160 proof, barreled at no more than 125 proof, bottled at minimum 80 proof, made in USA — Kentucky not legally required), straight bourbon (minimum 2 years, no added color/flavor/blending), wheated bourbon (substituting wheat for rye — Pappy, Maker\'s Mark softer profile), high-rye bourbon (spicier — Four Roses, Bulleit), Tennessee whiskey difference (Lincoln County Process — charcoal filtering before aging, Jack Daniel\'s and George Dickel), Scotch regions (Speyside: fruit-forward Glenfarclas/Macallan; Islay: peaty phenolic — Laphroaig/Ardbeg/Lagavulin, measured in PPM; Highland: diverse; Lowland: light triple-distilled; Campbeltown: briny), Irish whiskey (triple distillation lightness, pot still style unique to Ireland), Japanese whisky (Yamazaki/Hakushu/Nikka, blending craftsmanship, shortage crisis)'],
['id' => 'cocktails2', 'category' => 'cooking', 'topic' => 'Classic cocktails and home bartending',
'desc' => 'essential home bar setup (bourbon/rye, gin, rum, tequila/mezcal, vodka, triple sec/Cointreau, sweet vermouth, dry vermouth, Campari/Aperol, Angostura bitters, Peychaud\'s, simple syrup, citrus), technique (muddling — gentle pressure for herbs/fruit, vigorous for harder produce; shaking — with ice 10-15 seconds dilutes and chills, use for citrus/egg white drinks; stirring — 30-40 rotations for spirit-only drinks, keeps clear; straining — Hawthorne vs julep vs fine mesh double strain; fat-washing fats with spirits then freezing), seasonal batched cocktails for entertaining, Prohibition era cocktail history (why sours developed — masking bad spirits), Tiki culture and Trader Vic\'s origin, Negroni variations (Boulevardier substitutes bourbon, Americano adds soda)'],
['id' => 'fermentation', 'category' => 'cooking', 'topic' => 'Fermentation — science and practice',
'desc' => 'fermentation categories (lacto-fermentation: vegetables using Lactobacillus in salt brine — kimchi, sauerkraut, pickles, no vinegar; alcohol fermentation: yeast converts sugars to ethanol and CO2; acetic acid fermentation: bacteria converts ethanol to acetic acid — vinegar and kombucha second ferment; miso/soy sauce: koji mold Aspergillus oryzae enzymatic breakdown; cheese: bacterial acidification plus rennet coagulation), sourdough starter maintenance (hydration ratio, feeding schedule, float test for readiness, rye acceleration), kimchi troubleshooting (brine ratio 2-3% by weight, temperature affects speed, white film kahm yeast vs mold identification), kombucha SCOBY care, water kefir vs milk kefir differences, mead making basics (honey ratio for dry vs sweet, yeast nutrients, degassing)'],
['id' => 'home_diy2', 'category' => 'home', 'topic' => 'DIY home repairs and upgrades',
'desc' => 'toilet repair (flapper replacement — check seat type before buying, fill valve replacement, running toilet diagnosis — food coloring dye test for flapper leak, float adjustment for fill height), faucet repair (cartridge vs ball vs ceramic disc types, shutoff valve location, handle removal varies by manufacturer, seat wrench for older faucets), garbage disposal reset and unjamming (Allen wrench hex key in bottom, reset button on bottom, never hands inside), light fixture replacement (shut off breaker, verify with non-contact tester, wire matching — black-to-black/white-to-white/bare-to-bare, using wire nuts properly), installing dimmer switches (load type compatibility — LED vs incandescent dimmers), weatherstripping types (V-strip for sides, door sweep for bottom, foam tape vs felt durability)'],
['id' => 'declutter', 'category' => 'home', 'topic' => 'Organization, minimalism, and home systems',
'desc' => 'KonMari method (category order: clothing/books/papers/komono/sentimental, joy-testing, vertical folding), Swedish death cleaning concept (Margareta Magnusson — organizing for those who will sort through your things), one-in-one-out rule, digital decluttering (photo backup systems — 3-2-1 rule: 3 copies/2 media types/1 offsite, unsubscribe vs filter vs folder email management, password manager setup), paper management system (inbox/pending/action/archive, scanning to PDF, what to keep originals — deed/title/Social Security card/birth certificate), garage organization zones (seasonal rotation, ceiling storage, pegboard for tools), closet organization principles (group by category, color, frequency of use, double hang for short items), storage unit decision framework (annual cost vs item replacement cost)'],
['id' => 'personal_style', 'category' => 'home', 'topic' => 'Personal style and wardrobe building',
'desc' => 'capsule wardrobe concept (30-37 items per season — Courtney Carver Project 333), color palette identification (warm vs cool undertones — vein color/silver-gold jewelry test, skin tone descriptors: fair/light/medium/olive/tan/deep), body shape dressing (inverted triangle: add volume below; pear: structured shoulders/A-line; rectangle: create curves with belts/peplum; hourglass: emphasize waist; apple: empire waist/A-line), fabric quality indicators (thread count for cotton, S-number for wool, denier for synthetics), suit fit checkpoints (shoulder seam, jacket length, trouser break), dress code interpretation (black tie/creative black tie/cocktail/business formal/business casual/smart casual/casual), sustainable fashion metrics (cost-per-wear calculation, natural fiber benefits vs synthetic performance)'],
['id' => 'meditation', 'category' => 'wellness', 'topic' => 'Meditation and mindfulness practices',
'desc' => 'types of meditation (focused attention: breath as anchor, wandering mind recognition and return without judgment; open monitoring: choiceless awareness of all arising phenomena; loving-kindness/metta: generating warmth toward self/loved ones/neutral people/difficult people/all beings; body scan: progressive attention from feet to head; NSDR/yoga nidra: non-sleep deep rest protocol; mantra-based: TM uses personalized mantra, Zen counting breaths, Buddhist chanting), neuroscience of meditation (default mode network quieting in experienced meditators, amygdala reactivity reduction, cortical thickening in attention areas per Sara Lazar Harvard study), MBSR program structure (Jon Kabat-Zinn 8-week, body scan + gentle yoga + sitting meditation), apps comparison (Headspace vs Calm vs Waking Up vs Insight Timer), retreat formats (Vipassana 10-day silent), common obstacles (sleepiness/agitation/doubt/restlessness/hindrances)'],
['id' => 'yoga_stretch', 'category' => 'wellness', 'topic' => 'Yoga, stretching, and mobility work',
'desc' => 'yoga styles (Hatha: foundational, holds longer; Vinyasa: flowing breath-synchronized movement; Ashtanga: fixed sequence, more athletic; Yin: passive holds 3-5 minutes for connective tissue; Restorative: supported with props for nervous system; Bikram/hot yoga: 26-pose sequence at 105°F; Kundalini: breathwork, chanting, kriyas), major pose families (standing balance: warrior series, tree, eagle; forward folds: seated/standing hamstring stretch; backbends: cobra/upward dog/wheel; inversions: headstand/shoulder stand/legs up wall; twists: supine and seated; hip openers: pigeon, lizard, butterfly), flexibility vs mobility distinction (flexibility is passive range, mobility is active control with strength), foam rolling technique (perpendicular to muscle fiber direction, 30-60 seconds per area, avoid rolling directly on joints), stretching timing (static post-workout, dynamic pre-workout)'],
['id' => 'spirituality', 'category' => 'wellness', 'topic' => 'Spirituality, religion, and meaning-making',
'desc' => 'distinction between spirituality and religion (organized doctrine vs personal search), psychological benefits of religious practice (community, meaning, mortality salience buffering, better health outcomes in studies — frequency of attendance correlates), secular alternatives to religious community (Sunday Assembly, ethical culture societies, meditation communities), Viktor Frankl logotherapy (Man\'s Search for Meaning — finding purpose in suffering, will to meaning), positive psychology and meaning (Seligman PERMA model: Positive emotion/Engagement/Relationships/Meaning/Achievement), death and dying psychology (Kübler-Ross five stages — not linear; terror management theory — mortality salience and meaning systems; hospice philosophy), near-death experience research (AWARE study, common elements: tunnel/light/life review/peace, skeptical vs spiritual interpretations), new age beliefs vs scientific evidence (astrology, crystal healing, manifestation law of attraction)'],
['id' => 'anger_emotion', 'category' => 'wellness', 'topic' => 'Emotional intelligence and anger management',
'desc' => 'emotions vs feelings distinction (emotions: physiological response; feelings: subjective interpretation), Plutchik\'s wheel of emotions (8 primary: joy/sadness/anger/fear/anticipation/surprise/trust/disgust + combinations), emotional granularity (ability to distinguish subtle emotional states associated with better outcomes), anger physiology (amygdala hijack — cortisol and adrenaline release, prefrontal cortex offline, 20-minute cortisol clearance time), anger management techniques (STOP acronym, 10-second pause before responding, diaphragmatic breathing to activate parasympathetic, physical exercise for cortisol burn-off, journaling for processing, reframing cognitive restructuring), passive-aggressive behavior patterns and roots, emotional flooding in couples (John Gottman — heart rate over 100 BPM, self-soothing 20+ minute break), emotional intelligence components (Mayer/Salovey/Caruso four-branch model vs Goleman\'s competency model)'],
['id' => 'blockchain', 'category' => 'technology', 'topic' => 'Blockchain, cryptocurrency, and Web3',
'desc' => 'blockchain data structure (chain of blocks each containing hash of previous, transaction data, timestamp, Merkle tree of transactions), consensus mechanisms (Proof of Work: miners compete to solve hash puzzle, energy-intensive, 51% attack vulnerability; Proof of Stake: validators staked as collateral, Ethereum\'s merge to PoS September 2022, energy reduction 99.9%), Bitcoin specifics (21 million cap, halving every 210,000 blocks, UTXO model, Lightning Network for micropayments), Ethereum smart contracts (Solidity language, EVM, gas fees, ERC-20 token standard, ERC-721 NFT standard), DeFi (decentralized finance: liquidity pools, yield farming, AMMs, impermanent loss), NFTs use cases and speculation, CBDC (central bank digital currencies — e-CNY, digital euro), regulatory landscape (SEC vs CFTC jurisdiction, securities classification debate, FTX collapse lessons)'],
['id' => 'iot_devices', 'category' => 'technology', 'topic' => 'Internet of Things and smart home technology',
'desc' => 'IoT architecture (edge devices → gateways → cloud, MQTT protocol for lightweight pub/sub messaging), communication protocols (Zigbee: mesh network, low power, requires hub; Z-Wave: mesh, proprietary, better range; Wi-Fi: high bandwidth but power hungry; Thread/Matter: new open standard, local control without cloud), smart home platforms (Amazon Alexa ecosystem, Google Home, Apple HomeKit privacy-focused local processing, Samsung SmartThings, Home Assistant for open-source local control), security concerns (default credential attacks, firmware update gaps, network segmentation via IoT VLAN, local vs cloud processing privacy), industrial IoT applications (predictive maintenance sensors, smart grid, precision agriculture), wearables (health monitoring accuracy limitations — optical heart rate vs chest strap, SpO2 accuracy in darker skin tones, sleep stage detection algorithm differences)'],
['id' => 'data_science', 'category' => 'technology', 'topic' => 'Data science and analytics',
'desc' => 'data pipeline stages (collection → storage → cleaning → analysis → visualization → decision), data types (structured: SQL databases; semi-structured: JSON/XML/CSV; unstructured: text/images/video), data cleaning steps (handling missing values — deletion/imputation/flagging; outlier detection — IQR method/z-score/DBSCAN; duplicate removal; data type validation; string standardization), exploratory data analysis (summary statistics, distribution visualization — histogram/box plot/violin; correlation heatmap; pair plots), regression types (linear for continuous, logistic for binary, ridge/lasso for regularization), classification algorithms (decision tree, random forest ensemble, gradient boosting XGBoost, SVM), clustering (k-means elbow method, hierarchical, DBSCAN for arbitrary shapes), SQL for data analysts (joins — inner/left/right/full/cross, window functions — ROW_NUMBER/RANK/LAG/LEAD, CTEs, aggregation)'],
['id' => 'robotics', 'category' => 'technology', 'topic' => 'Robotics and automation',
'desc' => 'robot types (articulated arms: 6-DOF industrial robots — FANUC/KUKA/ABB, delta robots for high-speed pick-and-place, SCARA for planar assembly, collaborative robots/cobots — force-limited for human interaction), sensors (encoders for position, LiDAR for 3D mapping, cameras for vision, force/torque sensors for touch), actuators (DC servo motors, stepper motors, hydraulic for heavy load, pneumatic for speed), kinematics (forward kinematics: joint angles → end effector position; inverse kinematics: desired position → required joint angles — multiple solutions), ROS (Robot Operating System) architecture, SLAM (Simultaneous Localization and Mapping), industrial automation ROI and displacement concerns, autonomous mobile robots in warehouses (Amazon Kiva systems), drone autonomy levels, surgical robots (da Vinci system, haptic feedback limitations)'],
['id' => 'us_housing', 'category' => 'national', 'topic' => 'US housing crisis and affordability',
'desc' => 'housing supply shortage causes (zoning restrictions — single-family-only zoning in 75% of residential land in many cities, NIMBYism, permitting delays, construction cost increases, labor shortages), demand factors (remote work migration to secondary markets, population growth in Sun Belt, demographic wave of millennials in prime buying years), rent burden (30% of income standard, severely cost-burdened at 50%+, share of renters cost-burdened rising), homelessness crisis (Housing First evidence vs treatment-first debate, permanent supportive housing cost vs shelter cost, LA and SF policy failures), solutions debated (upzoning — Minneapolis 2040 plan, ADU legalization, inclusionary zoning tradeoffs, construction defect litigation reform, manufactured housing modernization, federal voucher expansion)'],
['id' => 'us_energy', 'category' => 'national', 'topic' => 'US energy policy and grid security',
'desc' => 'US electricity grid structure (Eastern Interconnection, Western Interconnection, Texas ERCOT — reason for isolation and vulnerability exposed by Uri), energy mix evolution (coal decline: 55% to 19% since 2000; natural gas rise: 33%; wind and solar growth: combined 13%; nuclear: 19% of generation but constant baseline), inflation Reduction Act provisions (production tax credit extension for wind/solar, investment tax credit for new nuclear, electric vehicle tax credits, home efficiency rebates), transmission bottleneck as renewable buildout barrier (permitting reform needed), energy storage role (4-hour lithium-ion vs longer duration alternatives — iron-air, flow batteries, pumped hydro siting challenges), LNG export growth and European energy security after Russia invasion, FERC jurisdiction vs state utility regulation'],
['id' => 'asia_economy', 'category' => 'world', 'topic' => 'Asian economic giants — Japan, Korea, China',
'desc' => 'Japan: lost decades (1990 asset bubble collapse, deflation trap, Bank of Japan yield curve control, Abenomics three arrows — monetary stimulus/fiscal stimulus/structural reform, demographic crisis and immigration resistance, anime and soft power, robotics leadership compensating for labor shortage), South Korea: chaebol conglomerate model (Samsung/Hyundai/LG dominance and corruption issues), K-culture global wave (K-pop idol system production, Korean cinema Parasite Oscar, Korean food global spread), DRAM memory semiconductor dominance (Samsung and SK Hynix 70%+ of global market), China: economic growth model shift (export-led to domestic consumption target, Xi\'s common prosperity campaign reining in Alibaba/Tencent, real estate crisis — Evergrande contagion, youth unemployment 20%+, demographic cliff from one-child policy)'],
['id' => 'latin_deep', 'category' => 'world', 'topic' => 'Latin America — history, politics, and culture',
'desc' => 'colonial legacy (Spanish colonial administrative structure — viceroyalties, encomienda labor system, racial caste system castas, Catholic Church land ownership), independence wave 1810-1826 (Bolivar, San Martin, Hidalgo in Mexico), post-independence instability (caudillo strongman tradition, US Monroe Doctrine interference, banana republic term origin — United Fruit Company in Guatemala), 20th century Cold War proxy battles (Cuban Revolution and Bay of Pigs, Chilean coup 1973 and Pinochet backed by US, Nicaragua Sandinistas, El Salvador civil war, dirty wars in Argentina and Brazil), pink tide (Chávez petro-populism in Venezuela, Lula in Brazil, Morales in Bolivia, progressive governments 2000s), current landscape (Bukele in El Salvador, Milei in Argentina, Boric in Chile, Petro in Colombia, Maduro\'s continued authoritarian rule), migration drivers'],
];
/* ── load active topics from database ── */
$BATCHES = JarvisDB::query(
"SELECT topic_id AS id, category, topic_name AS topic, description AS `desc`
FROM kb_generator_topics WHERE active=1 ORDER BY id ASC"
);
if (empty($BATCHES)) {
log_line('ERROR: No active topics in kb_generator_topics table. Add topics via the JARVIS admin panel.');
exit(1);
}
log_line('Loaded ' . count($BATCHES) . ' active topics from database.');
/* ── ROTATION ENGINE: process BATCH_SIZE topics per run, cycling through all ── */
define('BATCH_SIZE', 25);
+265
View File
@@ -616,6 +616,57 @@ if ($action) {
}
j(['lines'=>$out, 'next_line'=>$total]);
// ── KB GENERATOR TOPICS ─────────────────────────────────────────────
case 'kb_topics':
$where = ['1=1']; $params = [];
if (!empty($_GET['q'])) {
$q2 = '%'.$_GET['q'].'%';
$where[] = '(topic_name LIKE ? OR topic_id LIKE ? OR category LIKE ? OR description LIKE ?)';
$params = array_merge($params, [$q2,$q2,$q2,$q2]);
}
if (isset($_GET['cat']) && $_GET['cat'] !== '') { $where[] = 'category=?'; $params[] = $_GET['cat']; }
if (isset($_GET['active']) && $_GET['active'] !== '') { $where[] = 'active=?'; $params[] = (int)$_GET['active']; }
$topics = JarvisDB::query(
'SELECT id,topic_id,category,topic_name,description,active,run_count,last_run_at
FROM kb_generator_topics WHERE '.implode(' AND ',$where).' ORDER BY category,topic_name',
$params
);
$catRows = JarvisDB::query('SELECT DISTINCT category FROM kb_generator_topics ORDER BY category');
j(['topics'=>$topics, 'categories'=>array_column($catRows,'category')]);
case 'kb_topic_save':
$id = (int)($_POST['id'] ?? 0);
$tid = preg_replace('/[^a-z0-9_]/', '_', strtolower(trim($_POST['topic_id'] ?? '')));
$cat = trim($_POST['category'] ?? '');
$name = trim($_POST['topic_name'] ?? '');
$desc = trim($_POST['description'] ?? '');
$act = (int)!empty($_POST['active']);
if (!$tid||!$cat||!$name||!$desc) bad('All fields required');
if ($id) {
JarvisDB::execute(
'UPDATE kb_generator_topics SET topic_id=?,category=?,topic_name=?,description=?,active=?,updated_at=NOW() WHERE id=?',
[$tid,$cat,$name,$desc,$act,$id]
);
j(['ok'=>true,'msg'=>'Topic updated']);
} else {
JarvisDB::execute(
'INSERT INTO kb_generator_topics (topic_id,category,topic_name,description,active) VALUES (?,?,?,?,?)',
[$tid,$cat,$name,$desc,$act]
);
j(['ok'=>true,'msg'=>'Topic created']);
}
case 'kb_topic_delete':
$id = (int)($_POST['id'] ?? 0); if (!$id) bad('Missing id');
JarvisDB::execute('DELETE FROM kb_generator_topics WHERE id=?', [$id]);
j(['ok'=>true]);
case 'kb_topic_toggle':
$id = (int)($_POST['id'] ?? 0); if (!$id) bad('Missing id');
JarvisDB::execute('UPDATE kb_generator_topics SET active=NOT active, updated_at=NOW() WHERE id=?', [$id]);
$row = JarvisDB::single('SELECT active FROM kb_generator_topics WHERE id=?', [$id]);
j(['ok'=>true,'active'=>(bool)$row['active']]);
case 'arc_setup_log':
$logFile = '/var/log/jarvis/arc-setup.log';
$since = max(0, (int)($_GET['since'] ?? 0));
@@ -1498,6 +1549,7 @@ select.filter-sel:focus{border-color:var(--cyan)}
<button class="btn btn-sm btn-green" onclick="intentModal()">+ ADD INTENT</button>
<button class="btn btn-sm btn-yellow" onclick="intentTestModal()">TEST PATTERN</button>
<button class="btn btn-sm" onclick="loadIntents()">REFRESH</button>
<button class="btn btn-sm" style="border-color:#7f5fff;color:#7f5fff" onclick="openTopicsManager()">&#9881; MANAGE TOPICS</button>
<button class="btn btn-sm" style="border-color:#00d4ff;color:#00d4ff" onclick="runIntentGenerator()">&#9654; RUN GENERATOR</button>
</div>
</div>
@@ -2386,6 +2438,219 @@ async function runIntentGenerator() {
setTimeout(pollLog, 2000);
}
let _topicsData = [];
let _topicsCats = [];
async function openTopicsManager() {
const modalHtml = `
<div style="font-family:var(--mono);font-size:0.72rem">
<div id="tm-view-list">
<div style="display:flex;gap:8px;margin-bottom:8px;align-items:center;flex-wrap:wrap">
<input id="tm-search" type="text" placeholder="Search topics…" style="flex:1;min-width:140px;background:var(--bg2);border:1px solid var(--border);color:var(--fg);padding:5px 8px;font-size:0.7rem;border-radius:3px;font-family:inherit" oninput="tmFilter()">
<select id="tm-cat-filter" style="background:var(--bg2);border:1px solid var(--border);color:var(--fg);padding:5px 8px;font-size:0.7rem;border-radius:3px;font-family:inherit" onchange="tmFilter()">
<option value="">ALL CATEGORIES</option>
</select>
<select id="tm-active-filter" style="background:var(--bg2);border:1px solid var(--border);color:var(--fg);padding:5px 8px;font-size:0.7rem;border-radius:3px;font-family:inherit" onchange="tmFilter()">
<option value="">ALL STATUS</option>
<option value="1">ACTIVE</option>
<option value="0">DISABLED</option>
</select>
<button class="btn btn-sm btn-green" onclick="tmEditTopic(null)">+ ADD</button>
</div>
<div id="tm-stats" style="color:var(--text-dim);font-size:0.6rem;margin-bottom:6px;letter-spacing:0.5px"></div>
<div id="tm-list" style="max-height:370px;overflow-y:auto"><div class="loading">LOADING…</div></div>
</div>
<div id="tm-view-edit" style="display:none">
<div style="margin-bottom:12px">
<button class="btn btn-sm" onclick="tmShowList()">&#8592; BACK</button>
<span id="tm-edit-title" style="color:var(--cyan);margin-left:12px;font-size:0.65rem;letter-spacing:1px"></span>
</div>
<div style="display:grid;gap:8px">
<input type="hidden" id="tm-edit-id">
<div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">
<label style="font-size:0.6rem;color:var(--text-dim)">TOPIC ID (slug)
<input id="tm-edit-tid" type="text" placeholder="e.g. math_arith" style="width:100%;margin-top:3px;background:var(--bg2);border:1px solid var(--border);color:var(--fg);padding:5px 8px;font-size:0.7rem;border-radius:3px;font-family:inherit;box-sizing:border-box">
</label>
<label style="font-size:0.6rem;color:var(--text-dim)">CATEGORY
<input id="tm-edit-cat" type="text" placeholder="e.g. mathematics" list="tm-cat-dl" style="width:100%;margin-top:3px;background:var(--bg2);border:1px solid var(--border);color:var(--fg);padding:5px 8px;font-size:0.7rem;border-radius:3px;font-family:inherit;box-sizing:border-box">
<datalist id="tm-cat-dl"></datalist>
</label>
</div>
<label style="font-size:0.6rem;color:var(--text-dim)">TOPIC NAME
<input id="tm-edit-name" type="text" placeholder="e.g. Arithmetic and number sense" style="width:100%;margin-top:3px;background:var(--bg2);border:1px solid var(--border);color:var(--fg);padding:5px 8px;font-size:0.7rem;border-radius:3px;font-family:inherit;box-sizing:border-box">
</label>
<label style="font-size:0.6rem;color:var(--text-dim)">DESCRIPTION (subtopics to cover comma-separated)
<textarea id="tm-edit-desc" rows="5" placeholder="e.g. fractions, decimals, order of operations, prime numbers…" style="width:100%;margin-top:3px;background:var(--bg2);border:1px solid var(--border);color:var(--fg);padding:5px 8px;font-size:0.7rem;border-radius:3px;font-family:inherit;resize:vertical;box-sizing:border-box"></textarea>
</label>
<label style="font-size:0.6rem;color:var(--text-dim);display:flex;align-items:center;gap:6px;cursor:pointer">
<input id="tm-edit-active" type="checkbox" checked style="cursor:pointer"> ACTIVE (included in rotation)
</label>
</div>
</div>
</div>`;
openModal('&#9881; KB TOPIC MANAGER', modalHtml, null, null);
const saveBtn = document.getElementById('modalSave');
const closeBtn = document.getElementById('modalClose');
saveBtn.textContent = 'SAVE TOPIC';
saveBtn.style.display = 'none';
saveBtn.onclick = tmSaveTopic;
closeBtn.onclick = closeModal;
await tmLoadTopics();
}
async function tmLoadTopics() {
const res = await api('kb_topics');
_topicsData = res?.topics || [];
_topicsCats = res?.categories || [];
const catSel = document.getElementById('tm-cat-filter');
if (catSel) {
const cur = catSel.value;
while (catSel.options.length > 1) catSel.remove(1);
_topicsCats.forEach(c => catSel.add(new Option(c.toUpperCase(), c)));
if (cur) catSel.value = cur;
}
const dl = document.getElementById('tm-cat-dl');
if (dl) { dl.innerHTML = ''; _topicsCats.forEach(c => { const o = document.createElement('option'); o.value=c; dl.appendChild(o); }); }
tmFilter();
}
function tmFilter() {
const q = (document.getElementById('tm-search')?.value || '').toLowerCase();
const cat = document.getElementById('tm-cat-filter')?.value || '';
const active = document.getElementById('tm-active-filter')?.value;
const rows = _topicsData.filter(t => {
if (cat && t.category !== cat) return false;
if (active !== '' && active !== null && active !== undefined && String(t.active) !== String(active)) return false;
if (q && !`${t.topic_name} ${t.topic_id} ${t.category} ${t.description}`.toLowerCase().includes(q)) return false;
return true;
});
const total = _topicsData.length;
const activeCount = _topicsData.filter(t => t.active == 1).length;
const statsEl = document.getElementById('tm-stats');
if (statsEl) statsEl.innerHTML =
`<span style="color:var(--cyan)">${total} topics</span> &nbsp;|&nbsp; ` +
`<span style="color:var(--green)">${activeCount} active</span> &nbsp;|&nbsp; ` +
`<span style="color:var(--yellow)">${total-activeCount} disabled</span>` +
(rows.length < total ? ` &nbsp;|&nbsp; <span style="color:var(--text-dim)">${rows.length} shown</span>` : '');
const listEl = document.getElementById('tm-list');
if (!listEl) return;
if (!rows.length) {
listEl.innerHTML = '<div style="color:var(--text-dim);padding:20px;text-align:center">No topics match filter</div>';
return;
}
listEl.innerHTML = `<table style="width:100%;border-collapse:collapse">
<thead><tr style="color:var(--cyan);font-size:0.58rem;border-bottom:1px solid var(--border)">
<th style="padding:4px 6px;text-align:left;font-weight:normal">TOPIC ID</th>
<th style="padding:4px 6px;text-align:left;font-weight:normal">CATEGORY</th>
<th style="padding:4px 6px;text-align:left;font-weight:normal">TOPIC NAME</th>
<th style="padding:4px 6px;text-align:center;font-weight:normal">ON</th>
<th style="padding:4px 6px;text-align:center;font-weight:normal">RUNS</th>
<th style="padding:4px 6px;text-align:right;font-weight:normal">ACTIONS</th>
</tr></thead>
<tbody>${rows.map(t => `
<tr style="border-bottom:1px solid rgba(255,255,255,0.03);font-size:0.65rem">
<td style="padding:4px 6px;color:var(--text-dim);font-size:0.57rem">${tmEsc(t.topic_id)}</td>
<td style="padding:4px 6px"><span style="background:var(--bg2);padding:1px 5px;border-radius:2px;font-size:0.57rem;white-space:nowrap">${tmEsc(t.category)}</span></td>
<td style="padding:4px 6px;max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${tmEsc(t.description)}">${tmEsc(t.topic_name)}</td>
<td style="padding:4px 6px;text-align:center">
<input type="checkbox" ${t.active==1?'checked':''} onchange="tmToggle(${t.id},this)" style="cursor:pointer;accent-color:var(--green)">
</td>
<td style="padding:4px 6px;text-align:center;color:var(--text-dim);font-size:0.6rem">${t.run_count||0}</td>
<td style="padding:4px 6px;text-align:right;white-space:nowrap">
<button class="btn btn-sm btn-yellow" style="padding:2px 7px;font-size:0.58rem" onclick="tmEditTopic(${t.id})">EDIT</button>
<button class="btn btn-sm btn-red" style="padding:2px 7px;font-size:0.58rem;margin-left:3px" onclick="tmDelete(${t.id},${JSON.stringify(t.topic_name)})">DEL</button>
</td>
</tr>`).join('')}
</tbody></table>`;
}
function tmShowList() {
document.getElementById('tm-view-list').style.display = '';
document.getElementById('tm-view-edit').style.display = 'none';
document.getElementById('modalSave').style.display = 'none';
}
function tmEditTopic(id) {
document.getElementById('tm-view-list').style.display = 'none';
document.getElementById('tm-view-edit').style.display = '';
document.getElementById('modalSave').style.display = '';
const tidEl = document.getElementById('tm-edit-tid');
if (id) {
const t = _topicsData.find(x => x.id == id);
if (!t) return;
document.getElementById('tm-edit-title').textContent = 'EDIT TOPIC: ' + t.topic_id;
document.getElementById('tm-edit-id').value = t.id;
tidEl.value = t.topic_id;
tidEl.readOnly = true;
tidEl.style.opacity = '0.6';
document.getElementById('tm-edit-cat').value = t.category;
document.getElementById('tm-edit-name').value = t.topic_name;
document.getElementById('tm-edit-desc').value = t.description;
document.getElementById('tm-edit-active').checked = t.active == 1;
} else {
document.getElementById('tm-edit-title').textContent = 'ADD NEW TOPIC';
document.getElementById('tm-edit-id').value = '';
tidEl.value = '';
tidEl.readOnly = false;
tidEl.style.opacity = '1';
document.getElementById('tm-edit-cat').value = '';
document.getElementById('tm-edit-name').value = '';
document.getElementById('tm-edit-desc').value = '';
document.getElementById('tm-edit-active').checked = true;
}
}
async function tmSaveTopic() {
const id = document.getElementById('tm-edit-id').value;
const data = {
id: id ? parseInt(id) : 0,
topic_id: document.getElementById('tm-edit-tid').value.trim(),
category: document.getElementById('tm-edit-cat').value.trim(),
topic_name: document.getElementById('tm-edit-name').value.trim(),
description: document.getElementById('tm-edit-desc').value.trim(),
active: document.getElementById('tm-edit-active').checked ? 1 : 0,
};
if (!data.topic_id || !data.category || !data.topic_name || !data.description) {
toast('All fields are required', 'err'); return;
}
apiPost('kb_topic_save', data, async (res) => {
toast(res?.msg || 'Saved', 'ok');
tmShowList();
await tmLoadTopics();
});
}
async function tmToggle(id, el) {
apiPost('kb_topic_toggle', {id}, (res) => {
const t = _topicsData.find(x => x.id == id);
if (t) t.active = res.active ? 1 : 0;
tmFilter();
});
}
async function tmDelete(id, name) {
if (!confirm('Delete topic "' + name + '"?\nThis cannot be undone.')) return;
apiPost('kb_topic_delete', {id}, async () => {
toast('Topic deleted', 'ok');
await tmLoadTopics();
});
}
function tmEsc(s) {
return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
async function arcSetup() {
const modalHtml = `