@thanh01.pmt/curriculum-kit 1.0.13 → 1.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -12,7 +12,6 @@ import { createClient } from '@supabase/supabase-js';
12
12
  import { fileURLToPath } from 'url';
13
13
  import { jsonrepair } from 'jsonrepair';
14
14
  import { Octokit } from '@octokit/rest';
15
- import { defineHook, getStepMetadata, RetryableError, sleep } from 'workflow';
16
15
 
17
16
  var __defProp = Object.defineProperty;
18
17
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -13515,11 +13514,11 @@ var DeterministicPipelineRunner = class {
13515
13514
  // src/services/prefillService.ts
13516
13515
  init_streamRunner();
13517
13516
  var DEFAULT_STREAM_IDLE_MS = 45e3;
13518
- var DEFAULT_STREAM_TOTAL_MS = 3e5;
13517
+ var DEFAULT_STREAM_TOTAL_MS = 42e4;
13519
13518
  var LAYER_TOTAL_BUDGET_MS = {
13520
- 1: 18e4,
13521
- 2: 36e4,
13522
- 3: 36e4
13519
+ 1: 42e4,
13520
+ 2: 42e4,
13521
+ 3: 42e4
13523
13522
  };
13524
13523
  function resolveStreamBudget(layer, opts) {
13525
13524
  const envIdle = Number(process.env.WIZARD_PREFILL_IDLE_TIMEOUT_MS);
@@ -13586,29 +13585,111 @@ function createStreamAbortSignal(budget) {
13586
13585
  }
13587
13586
  };
13588
13587
  }
13588
+ function closeTruncatedJson(candidate) {
13589
+ let inStr = false;
13590
+ let esc2 = false;
13591
+ const stack = [];
13592
+ for (let i = 0; i < candidate.length; i++) {
13593
+ const ch = candidate[i];
13594
+ if (esc2) {
13595
+ esc2 = false;
13596
+ continue;
13597
+ }
13598
+ if (inStr) {
13599
+ if (ch === "\\") esc2 = true;
13600
+ else if (ch === '"') inStr = false;
13601
+ continue;
13602
+ }
13603
+ if (ch === '"') inStr = true;
13604
+ else if (ch === "{" || ch === "[") stack.push(ch);
13605
+ else if (ch === "}" || ch === "]") stack.pop();
13606
+ }
13607
+ if (stack.length === 0 && !inStr) return null;
13608
+ let out = candidate;
13609
+ out = out.replace(/,\s*$/, "");
13610
+ if (inStr) {
13611
+ out = out.replace(/\\+$/, "");
13612
+ out += '"';
13613
+ }
13614
+ while (stack.length > 0) {
13615
+ out += stack.pop() === "{" ? "}" : "]";
13616
+ }
13617
+ return out;
13618
+ }
13619
+ function stripLlmJsonWrappers(rawText) {
13620
+ let cleaned = rawText.replace(/<think>[\s\S]*?<\/think>/gi, "").replace(/```json\s*/gi, "").replace(/```\s*/g, "").trim();
13621
+ const firstBrace = cleaned.indexOf("{");
13622
+ if (firstBrace > 0) {
13623
+ cleaned = cleaned.slice(firstBrace);
13624
+ }
13625
+ return cleaned.trim();
13626
+ }
13589
13627
  function safeParseJson(rawText) {
13590
13628
  if (!rawText) return null;
13591
- const cleaned = rawText.replace(/```json\s*/gi, "").replace(/```\s*/g, "").trim();
13629
+ const cleaned = stripLlmJsonWrappers(rawText);
13630
+ if (!cleaned) return null;
13592
13631
  try {
13593
13632
  return JSON.parse(cleaned);
13594
13633
  } catch {
13595
- const firstBrace = cleaned.indexOf("{");
13634
+ }
13635
+ const firstBrace = cleaned.indexOf("{");
13636
+ if (firstBrace === -1) return null;
13637
+ const buildCandidates = () => {
13638
+ const list = [];
13639
+ const closed = closeTruncatedJson(cleaned.slice(firstBrace));
13640
+ if (closed) list.push(closed);
13596
13641
  const lastBrace = cleaned.lastIndexOf("}");
13597
- if (firstBrace !== -1 && lastBrace !== -1 && lastBrace > firstBrace) {
13598
- const candidate = cleaned.slice(firstBrace, lastBrace + 1);
13599
- try {
13600
- return JSON.parse(candidate);
13601
- } catch {
13642
+ if (lastBrace > firstBrace) {
13643
+ list.push(cleaned.slice(firstBrace, lastBrace + 1));
13644
+ }
13645
+ return list;
13646
+ };
13647
+ for (const candidate of buildCandidates()) {
13648
+ try {
13649
+ return JSON.parse(candidate);
13650
+ } catch {
13651
+ }
13652
+ try {
13653
+ return JSON.parse(jsonrepair(candidate));
13654
+ } catch {
13655
+ }
13656
+ }
13657
+ let depth = 0;
13658
+ let inStr = false;
13659
+ let esc2 = false;
13660
+ for (let i = firstBrace; i < cleaned.length; i++) {
13661
+ const ch = cleaned[i];
13662
+ if (esc2) {
13663
+ esc2 = false;
13664
+ continue;
13665
+ }
13666
+ if (inStr) {
13667
+ if (ch === "\\") esc2 = true;
13668
+ else if (ch === '"') inStr = false;
13669
+ continue;
13670
+ }
13671
+ if (ch === '"') inStr = true;
13672
+ else if (ch === "{") depth++;
13673
+ else if (ch === "}") {
13674
+ depth--;
13675
+ if (depth === 0) {
13676
+ const candidate = cleaned.slice(firstBrace, i + 1);
13602
13677
  try {
13603
- const repaired = jsonrepair(candidate);
13604
- return JSON.parse(repaired);
13678
+ return JSON.parse(candidate);
13679
+ } catch {
13680
+ }
13681
+ try {
13682
+ return JSON.parse(jsonrepair(candidate));
13605
13683
  } catch {
13606
- return null;
13607
13684
  }
13608
13685
  }
13609
13686
  }
13610
- return null;
13611
13687
  }
13688
+ try {
13689
+ return JSON.parse(jsonrepair(cleaned));
13690
+ } catch {
13691
+ }
13692
+ return null;
13612
13693
  }
13613
13694
  async function streamLLMWithFallback(systemPrompt, userPrompt, apiKeys = {}, onChunk, preferredModel, preferredProvider, budget) {
13614
13695
  const alibabaKey = apiKeys.alibaba || apiKeys.dashscope || process.env.ALIBABA_API_KEY || process.env.DASHSCOPE_API_KEY;
@@ -14661,1014 +14742,640 @@ template_contract: "artifact-template-v1"
14661
14742
  timestamp: dateStr
14662
14743
  };
14663
14744
  }
14664
- async function withRateLimitBackoff(options) {
14665
- let attempt = 1;
14666
- try {
14667
- const meta = getStepMetadata();
14668
- if (meta && typeof meta.attempt === "number") {
14669
- attempt = meta.attempt;
14670
- }
14671
- } catch {
14672
- }
14673
- try {
14674
- return await options.fn();
14675
- } catch (error) {
14676
- const errorMessage = error?.message || String(error);
14677
- const status = error?.status || error?.statusCode || error?.response?.status;
14678
- const isRateLimited = status === 429 || errorMessage.includes("429") || errorMessage.toLowerCase().includes("rate limit") || errorMessage.toLowerCase().includes("resource exhausted") || errorMessage.toLowerCase().includes("quota exceeded");
14679
- const isTransientError = status === 500 || status === 502 || status === 503 || status === 504 || errorMessage.includes("fetch failed") || errorMessage.includes("ECONNRESET") || errorMessage.includes("ETIMEDOUT") || errorMessage.includes("socket hang up");
14680
- if (isRateLimited || isTransientError) {
14681
- const retryAfterSeconds = Math.min(120, Math.pow(2, attempt) * 2);
14682
- const reason = isRateLimited ? "Rate limit exceeded (429)" : `Transient server error (${status || "network"})`;
14683
- throw new RetryableError(`[${options.stepName}] ${reason}. Retrying attempt ${attempt + 1}...`, {
14684
- retryAfter: `${retryAfterSeconds}s`
14745
+
14746
+ // src/index.ts
14747
+ init_errors();
14748
+
14749
+ // src/evaluators/deterministicStructuralLinter.ts
14750
+ var DeterministicStructuralLinter = class {
14751
+ /**
14752
+ * Validates structural invariants across a complete lesson bundle.
14753
+ */
14754
+ static lintBundle(input) {
14755
+ const { lesson, quiz, activity, slides, codeLab } = input;
14756
+ const findings = [];
14757
+ const strengths = [];
14758
+ let score = 100;
14759
+ const baseLessonId = lesson.lessonId;
14760
+ const baseLanguage = lesson.language;
14761
+ if (!lesson.title || lesson.title.trim().length === 0) {
14762
+ score -= 20;
14763
+ findings.push({
14764
+ id: "struct_missing_lesson_title",
14765
+ dimension: "CROSS_ARTIFACT_ZERO_DRIFT",
14766
+ severity: "CRITICAL",
14767
+ title: "Missing Lesson Title",
14768
+ description: "Lesson plan has an empty or whitespace title.",
14769
+ remediationAdvice: "Provide a non-empty lesson title."
14685
14770
  });
14686
14771
  }
14687
- throw error;
14688
- }
14689
- }
14690
-
14691
- // src/workflow/steps/lessonSteps.ts
14692
- async function generateMasterLessonStep(input) {
14693
- "use step";
14694
- console.log(` \u23F3 [Step: Master Lesson] Generating 5E Master Lesson Plan for "${input.milestone.name}"...`);
14695
- const t0 = Date.now();
14696
- const res = await withRateLimitBackoff({
14697
- stepName: `generate-master-lesson-${input.milestone.id || "L01"}`,
14698
- fn: async () => {
14699
- return generateLessonMasterFlow({
14700
- milestone: input.milestone,
14701
- language: input.language,
14702
- topic: input.topic,
14703
- targetAudience: input.targetAudience,
14704
- contextContinuity: input.contextContinuity,
14705
- standardsContext: input.standardsContext,
14706
- modelOptions: input.modelOptions
14772
+ if (!lesson.learningObjectives || lesson.learningObjectives.length === 0) {
14773
+ score -= 25;
14774
+ findings.push({
14775
+ id: "struct_empty_learning_objectives",
14776
+ dimension: "CONSTRUCTIVE_ALIGNMENT",
14777
+ severity: "CRITICAL",
14778
+ title: "Empty Learning Objectives Array",
14779
+ description: "Lesson plan contains 0 learning objectives.",
14780
+ remediationAdvice: "Declare at least 2 structured Learning Objectives in the schema."
14707
14781
  });
14708
14782
  }
14709
- });
14710
- console.log(` \u2705 [Step: Master Lesson] Done in ${((Date.now() - t0) / 1e3).toFixed(1)}s (Title: "${res.title}")`);
14711
- return res;
14712
- }
14713
- async function judgeMasterLessonStep(input) {
14714
- "use step";
14715
- console.log(` \u2696\uFE0F [Step: Quality Judge] Auditing Master Lesson pedagogical quality & language adherence...`);
14716
- const t0 = Date.now();
14717
- const res = await withRateLimitBackoff({
14718
- stepName: `judge-master-lesson-${input.lessonId}`,
14719
- fn: async () => {
14720
- return auditCurriculumQualityFlow({
14721
- targetArtifactType: "LESSON",
14722
- lessonId: input.lessonId,
14723
- expectedLanguage: input.language,
14724
- targetObjectives: input.targetObjectives,
14725
- generatedContentJson: JSON.stringify(input.lesson, null, 2),
14726
- standardStatements: input.standardStatements,
14727
- modelOptions: input.modelOptions
14783
+ if (!lesson.sections || lesson.sections.length === 0) {
14784
+ score -= 25;
14785
+ findings.push({
14786
+ id: "struct_empty_lesson_sections",
14787
+ dimension: "5E_INSTRUCTIONAL_FIDELITY",
14788
+ severity: "CRITICAL",
14789
+ title: "Empty Lesson Sections Array",
14790
+ description: "Lesson plan contains no instructional sections.",
14791
+ remediationAdvice: "Provide structured lesson flow sections."
14728
14792
  });
14729
14793
  }
14730
- });
14731
- console.log(` \u2705 [Step: Quality Judge] Done in ${((Date.now() - t0) / 1e3).toFixed(1)}s (Verdict: ${res.overallVerdict}, Score: ${res.totalScore}/100)`);
14732
- return res;
14733
- }
14734
- async function repairMasterLessonStep(input) {
14735
- "use step";
14736
- console.log(` \u{1F6E0}\uFE0F [Step: Auto-Repair] Repairing Master Lesson based on Judge feedback...`);
14737
- const repairFeedback = `
14738
- PREVIOUS AUDIT VERDICT: ${input.auditReport.overallVerdict} (Score: ${input.auditReport.totalScore}/100)
14739
- Detected Issues:
14740
- ${input.auditReport.criteria.filter((c) => !c.passed).map((c) => `- [${c.name}] ${c.feedback}`).join("\n")}
14741
- Actionable Repairs:
14742
- ${input.auditReport.actionableRepairPrompts.map((p) => `* ${p}`).join("\n")}
14743
- Language Adherence Required: "${input.language}"
14744
- `.trim();
14745
- return withRateLimitBackoff({
14746
- stepName: `repair-master-lesson-${input.milestone.id || "L01"}`,
14747
- fn: async () => {
14748
- return generateLessonMasterFlow({
14749
- milestone: input.milestone,
14750
- language: input.language,
14751
- topic: input.topic,
14752
- targetAudience: input.targetAudience,
14753
- contextContinuity: repairFeedback,
14754
- standardsContext: input.standardsContext,
14755
- modelOptions: input.modelOptions
14794
+ if (quiz && quiz.quizId !== baseLessonId && !quiz.quizId.includes(baseLessonId)) {
14795
+ score -= 15;
14796
+ findings.push({
14797
+ id: "struct_quiz_id_mismatch",
14798
+ dimension: "CROSS_ARTIFACT_ZERO_DRIFT",
14799
+ severity: "MAJOR",
14800
+ title: "Quiz ID Contract Mismatch",
14801
+ description: `Quiz ID "${quiz.quizId}" does not match Lesson ID "${baseLessonId}".`,
14802
+ remediationAdvice: `Sync Quiz quizId to "${baseLessonId}".`,
14803
+ affectedElement: quiz.quizId
14756
14804
  });
14757
14805
  }
14758
- });
14759
- }
14760
-
14761
- // src/workflow/steps/satelliteSteps.ts
14762
- async function generateActivityStep(options) {
14763
- "use step";
14764
- console.log(` \u23F3 [Step: Activity Lab] Generating hands-on ACT.md...`);
14765
- const t0 = Date.now();
14766
- const res = await withRateLimitBackoff({
14767
- stepName: `generate-act-${options.lesson.lessonId}`,
14768
- fn: async () => generateActivityFlow(options)
14769
- });
14770
- console.log(` \u2705 [Step: Activity Lab] Done in ${((Date.now() - t0) / 1e3).toFixed(1)}s (Title: "${res.title}")`);
14771
- return res;
14772
- }
14773
- async function generateCodeLabStep(options) {
14774
- "use step";
14775
- console.log(` \u23F3 [Step: Code Lab] Generating starter & solution code LAB.md...`);
14776
- const t0 = Date.now();
14777
- const res = await withRateLimitBackoff({
14778
- stepName: `generate-lab-${options.lesson.lessonId}`,
14779
- fn: async () => generateCodeLabFlow(options)
14780
- });
14781
- console.log(` \u2705 [Step: Code Lab] Done in ${((Date.now() - t0) / 1e3).toFixed(1)}s (Title: "${res.title}")`);
14782
- return res;
14783
- }
14784
- async function generateSelfLabStep(options) {
14785
- "use step";
14786
- console.log(` \u23F3 [Step: Self-Lab] Generating SELF_LAB.md with Progressive Hints...`);
14787
- const t0 = Date.now();
14788
- const res = await withRateLimitBackoff({
14789
- stepName: `generate-self-lab-${options.milestone.id || "L01"}`,
14790
- fn: async () => generateSelfLabFlow(options)
14791
- });
14792
- console.log(` \u2705 [Step: Self-Lab] Done in ${((Date.now() - t0) / 1e3).toFixed(1)}s (Challenges: 3 tiers Bronze/Silver/Gold)`);
14793
- return res;
14794
- }
14795
- async function generateDiagnosticQuizStep(options) {
14796
- "use step";
14797
- console.log(` \u23F3 [Step: Diagnostic Quiz] Generating QUIZ.json Bloom Assessment...`);
14798
- const t0 = Date.now();
14799
- const res = await withRateLimitBackoff({
14800
- stepName: `generate-quiz-${options.milestone.id || "L01"}`,
14801
- fn: async () => generateDiagnosticQuizFlow(options)
14802
- });
14803
- console.log(` \u2705 [Step: Diagnostic Quiz] Done in ${((Date.now() - t0) / 1e3).toFixed(1)}s (Questions: ${res.questions.length})`);
14804
- return res;
14805
- }
14806
- async function generateSlidesStep(options) {
14807
- "use step";
14808
- console.log(` \u23F3 [Step: Slides] Generating Marp presentation SLIDE.md...`);
14809
- const t0 = Date.now();
14810
- const res = await withRateLimitBackoff({
14811
- stepName: `generate-slides-${options.lesson.lessonId}`,
14812
- fn: async () => generateSlidesFlow(options)
14813
- });
14814
- console.log(` \u2705 [Step: Slides] Done in ${((Date.now() - t0) / 1e3).toFixed(1)}s (Slides: ${res.slides.length})`);
14815
- return res;
14816
- }
14817
- async function generateHandoutStep(options) {
14818
- "use step";
14819
- console.log(` \u23F3 [Step: Handout] Generating 5-Second Rule HANDOUT.md...`);
14820
- const t0 = Date.now();
14821
- const res = await withRateLimitBackoff({
14822
- stepName: `generate-handout-${options.lesson.lessonId}`,
14823
- fn: async () => generateHandoutFlow(options)
14824
- });
14825
- console.log(` \u2705 [Step: Handout] Done in ${((Date.now() - t0) / 1e3).toFixed(1)}s (Title: "${res.title}")`);
14826
- return res;
14827
- }
14828
- async function generateWorksheetStep(options) {
14829
- "use step";
14830
- return withRateLimitBackoff({
14831
- stepName: `generate-worksheet-${options.lesson.lessonId}`,
14832
- fn: async () => generateWorksheetFlow(options)
14833
- });
14834
- }
14835
- async function generateTeacherGuideStep(options) {
14836
- "use step";
14837
- return withRateLimitBackoff({
14838
- stepName: `generate-teacher-guide-${options.lesson.lessonId}`,
14839
- fn: async () => generateTeacherGuideFlow(options)
14840
- });
14841
- }
14842
- async function generateExtensionStep(options) {
14843
- "use step";
14844
- return withRateLimitBackoff({
14845
- stepName: `generate-extension-${options.lesson.lessonId}`,
14846
- fn: async () => generateExtensionFlow(options)
14847
- });
14848
- }
14849
-
14850
- // src/workflow/steps/satelliteJudgeStep.ts
14851
- async function judgeSatelliteStep(input) {
14852
- "use step";
14853
- const t0 = Date.now();
14854
- console.log(" \u{1F9D1}\u200D\u2696\uFE0F [Step: Satellite Judge] " + input.artifactType + " (" + input.artifactId + ")...");
14855
- return withRateLimitBackoff({
14856
- stepName: "judge-satellite-" + input.artifactType + "-" + input.artifactId,
14857
- fn: async () => {
14858
- return auditCurriculumQualityFlow({
14859
- targetArtifactType: input.artifactType,
14860
- lessonId: input.artifactId,
14861
- expectedLanguage: input.language,
14862
- targetObjectives: input.targetObjectives,
14863
- generatedContentJson: JSON.stringify(input.artifact),
14864
- standardStatements: input.standardStatements,
14865
- modelOptions: input.modelOptions
14806
+ if (activity && activity.lessonId !== baseLessonId) {
14807
+ score -= 15;
14808
+ findings.push({
14809
+ id: "struct_act_id_mismatch",
14810
+ dimension: "CROSS_ARTIFACT_ZERO_DRIFT",
14811
+ severity: "MAJOR",
14812
+ title: "Activity Lesson ID Contract Mismatch",
14813
+ description: `Activity lessonId "${activity.lessonId}" does not match Lesson ID "${baseLessonId}".`,
14814
+ remediationAdvice: `Sync Activity lessonId to "${baseLessonId}".`,
14815
+ affectedElement: activity.lessonId
14866
14816
  });
14867
14817
  }
14868
- }).then((res) => {
14869
- console.log(" \u2705 [Satellite Judge] " + input.artifactType + " \u2192 " + res.overallVerdict + " (" + res.totalScore + "/100) in " + ((Date.now() - t0) / 1e3).toFixed(1) + "s");
14870
- return res;
14871
- });
14872
- }
14873
-
14874
- // src/workflow/steps/publishSteps.ts
14875
- async function saveMilestoneToWorkspaceStep(input) {
14876
- "use step";
14877
- const manager = new LocalWorkspaceManager(input.baseWorkspaceDir);
14878
- const savedFiles = [];
14879
- const lessonMd = serializeLessonToMarkdown(input.lesson);
14880
- const p1 = await manager.saveArtifact(input.jobId, input.milestoneSlug, "LESSON_5E.md", lessonMd, "LESSON");
14881
- savedFiles.push(p1);
14882
- if (input.activity) {
14883
- const actMd = serializeActivityToMarkdown(input.activity);
14884
- const p2 = await manager.saveArtifact(input.jobId, input.milestoneSlug, "ACT.md", actMd, "ACT");
14885
- savedFiles.push(p2);
14886
- }
14887
- if (input.codeLab) {
14888
- const labContent = serializeCodeLabToMarkdown(input.codeLab);
14889
- const p3 = await manager.saveArtifact(input.jobId, input.milestoneSlug, "LAB.md", labContent, "LAB");
14890
- savedFiles.push(p3);
14891
- }
14892
- if (input.selfLab) {
14893
- const selfLabMd = serializeSelfLabToMarkdown(input.selfLab);
14894
- const p4 = await manager.saveArtifact(input.jobId, input.milestoneSlug, "SELF_LAB.md", selfLabMd, "SELF_LAB");
14895
- savedFiles.push(p4);
14896
- }
14897
- if (input.quiz) {
14898
- const quizMd = serializeDiagnosticQuizToMarkdown(input.quiz);
14899
- const p5a = await manager.saveArtifact(input.jobId, input.milestoneSlug, "QUIZ.md", quizMd, "QUIZ_MD");
14900
- const p5b = await manager.saveArtifact(
14901
- input.jobId,
14902
- input.milestoneSlug,
14903
- "QUIZ.json",
14904
- JSON.stringify(input.quiz, null, 2),
14905
- "QUIZ_JSON"
14906
- );
14907
- savedFiles.push(p5a, p5b);
14908
- }
14909
- if (input.slides) {
14910
- const slidesContent = `---
14911
- marp: true
14912
- theme: default
14913
- paginate: true
14914
- ---
14915
-
14916
- # ${input.slides.title}
14917
-
14918
- ---
14919
-
14920
- ${input.slides.slides.map((s) => `## Slide ${s.slideNumber}: ${s.title}
14921
-
14922
- ${s.bulletPoints.map((b) => `- ${b}`).join("\n")}${s.codeSnippet ? `
14923
-
14924
- \`\`\`
14925
- ${s.codeSnippet}
14926
- \`\`\`` : ""}
14927
-
14928
- <!-- Presenter Notes: ${s.presenterNotes || ""} -->`).join("\n\n---\n\n")}
14929
- `.trim();
14930
- const p6 = await manager.saveArtifact(input.jobId, input.milestoneSlug, "SLIDE.md", slidesContent, "SLIDES");
14931
- savedFiles.push(p6);
14932
- }
14933
- if (input.handout) {
14934
- const handoutMd = serializeHandoutToMarkdown(input.handout);
14935
- const p7 = await manager.saveArtifact(input.jobId, input.milestoneSlug, "HANDOUT.md", handoutMd, "HANDOUT");
14936
- savedFiles.push(p7);
14937
- }
14938
- if (input.cheatSheetMarkdown) {
14939
- const p8 = await manager.saveArtifact(
14940
- input.jobId,
14941
- input.milestoneSlug,
14942
- "CHEAT_SHEET.md",
14943
- input.cheatSheetMarkdown,
14944
- "CHEAT_SHEET"
14945
- );
14946
- savedFiles.push(p8);
14947
- }
14948
- await manager.markMilestoneCompleted(input.jobId);
14949
- return {
14950
- milestoneSlug: input.milestoneSlug,
14951
- savedFiles
14952
- };
14953
- }
14954
- async function publishToGitStep(options) {
14955
- "use step";
14956
- return publishToGitHub(options);
14957
- }
14958
- async function publishToSupabaseStep(options) {
14959
- "use step";
14960
- return publishToSupabase(options);
14961
- }
14962
- var approvalPayloadSchema = z.object({
14963
- approved: z.boolean().describe("Whether the human reviewer approves the generated curriculum/lesson"),
14964
- reviewerName: z.string().optional().describe("Name or ID of the reviewer"),
14965
- feedback: z.string().optional().describe("Actionable feedback or required changes if rejected"),
14966
- timestamp: z.string().optional().describe("ISO timestamp of the approval action")
14967
- });
14968
- var lessonApprovalHook = defineHook();
14969
- function approvalHookToken(projectId, lessonId, artifactType) {
14970
- return `approval:${projectId}:${lessonId}:${artifactType}`;
14971
- }
14972
-
14973
- // src/standards/standardsCoverageGate.ts
14974
- function resolveStatementRef(ref, packs) {
14975
- const [head, ...rest] = ref.split(":");
14976
- const candidatePacks = rest.length > 0 ? packs.filter((p) => p.manifest.id === head) : packs;
14977
- const statementId = rest.length > 0 ? rest.join(":") : ref;
14978
- for (const p of candidatePacks) {
14979
- if (p.statements.some((s) => s.id === statementId)) return { pack: p, statementId };
14980
- }
14981
- return null;
14982
- }
14983
- function evaluateStandardsCoverage(input) {
14984
- const rows = [];
14985
- const aoToLo = /* @__PURE__ */ new Map();
14986
- for (const ao of input.assessmentObjectives ?? []) aoToLo.set(ao.aoCode, ao.alignedLO);
14987
- const loToRefs = /* @__PURE__ */ new Map();
14988
- for (const lo of input.objectives) {
14989
- loToRefs.set(lo.code, new Set(lo.standardRefs ?? []));
14990
- }
14991
- const taughtLOs = /* @__PURE__ */ new Set();
14992
- for (const act of input.activities ?? []) for (const lo of act.lo) taughtLOs.add(lo);
14993
- const assessedLOs = /* @__PURE__ */ new Set();
14994
- for (const q of input.quizQuestions) {
14995
- if (q.alignedLO) assessedLOs.add(q.alignedLO);
14996
- if (q.alignedAO) {
14997
- const lo = aoToLo.get(q.alignedAO);
14998
- if (lo) assessedLOs.add(lo);
14818
+ if (slides && slides.lessonId !== baseLessonId) {
14819
+ score -= 15;
14820
+ findings.push({
14821
+ id: "struct_slides_id_mismatch",
14822
+ dimension: "CROSS_ARTIFACT_ZERO_DRIFT",
14823
+ severity: "MAJOR",
14824
+ title: "Slide Deck Lesson ID Contract Mismatch",
14825
+ description: `Slide deck lessonId "${slides.lessonId}" does not match Lesson ID "${baseLessonId}".`,
14826
+ remediationAdvice: `Sync Slide deck lessonId to "${baseLessonId}".`,
14827
+ affectedElement: slides.lessonId
14828
+ });
14999
14829
  }
15000
- }
15001
- for (const pack of input.packs) {
15002
- const mappingByStatement = /* @__PURE__ */ new Map();
15003
- for (const m of pack.mappings ?? []) {
15004
- const prev = mappingByStatement.get(m.statementId);
15005
- if (!prev || prev !== "covers" && m.kind === "covers" || prev === "extends" && m.kind !== "extends") {
15006
- mappingByStatement.set(m.statementId, m.kind);
14830
+ const satellites = [
14831
+ { type: "QUIZ", lang: quiz?.language },
14832
+ { type: "ACT", lang: activity?.language },
14833
+ { type: "SLIDE", lang: slides?.language }
14834
+ ];
14835
+ for (const sat of satellites) {
14836
+ if (sat.lang && sat.lang.toLowerCase() !== baseLanguage.toLowerCase()) {
14837
+ score -= 25;
14838
+ findings.push({
14839
+ id: `struct_language_mismatch_${sat.type}`,
14840
+ dimension: "CROSS_ARTIFACT_ZERO_DRIFT",
14841
+ severity: "CRITICAL",
14842
+ title: `Language Policy Inconsistency in ${sat.type}`,
14843
+ description: `Master Lesson is in "${baseLanguage}" but ${sat.type} is declared in "${sat.lang}".`,
14844
+ remediationAdvice: `Set ${sat.type} language to "${baseLanguage}".`
14845
+ });
15007
14846
  }
15008
14847
  }
15009
- for (const statement of pack.statements) {
15010
- const refFull = `${pack.manifest.id}:${statement.id}`;
15011
- const issues = [];
15012
- const los = input.objectives.filter((lo) => (lo.standardRefs ?? []).some((r) => r === statement.id || r === refFull)).map((lo) => lo.code);
15013
- const kind = mappingByStatement.get(statement.id);
15014
- const hasMapping = kind !== void 0;
15015
- const isComplianceRelevant = kind === "covers";
15016
- const hasActivity = los.some((lo) => taughtLOs.has(lo));
15017
- const hasAssessment = los.some((lo) => assessedLOs.has(lo));
15018
- let status;
15019
- if (!hasMapping) status = "UNMAPPED";
15020
- else if (!isComplianceRelevant) status = "PARTIAL";
15021
- else if (los.length > 0 && hasActivity && hasAssessment) status = "COVERED";
15022
- else status = "UNCOVERED";
15023
- if (status === "UNCOVERED") {
15024
- if (los.length === 0) issues.push("No learning objective anchors this statement (missing standardRefs).");
15025
- else {
15026
- if (!hasActivity) issues.push(`Anchored LO(s) ${los.join(", ")} have no activity in lesson flow.`);
15027
- if (!hasAssessment) issues.push(`Anchored LO(s) ${los.join(", ")} are not measured by any quiz question.`);
15028
- }
14848
+ if (quiz && quiz.questions) {
14849
+ for (let i = 0; i < quiz.questions.length; i++) {
14850
+ const q = quiz.questions[i];
14851
+ const qId = q.id || `Q${i + 1}`;
14852
+ const options = q.options || [];
14853
+ if (options.length < 4) {
14854
+ score -= 10;
14855
+ findings.push({
14856
+ id: `struct_quiz_option_count_${qId}`,
14857
+ dimension: "MISCONCEPTION_RIGOR",
14858
+ severity: "MAJOR",
14859
+ title: `Structural Option Count Error in ${qId}`,
14860
+ description: `Question ${qId} has ${options.length} options (standard schema requires 4).`,
14861
+ remediationAdvice: "Ensure each question has 4 options (A, B, C, D).",
14862
+ affectedElement: qId
14863
+ });
14864
+ }
14865
+ const correctCount = options.filter((o) => o.isCorrect).length;
14866
+ if (correctCount !== 1) {
14867
+ score -= 20;
14868
+ findings.push({
14869
+ id: `struct_quiz_key_count_${qId}`,
14870
+ dimension: "MISCONCEPTION_RIGOR",
14871
+ severity: "CRITICAL",
14872
+ title: `Key Assignment Error in ${qId}`,
14873
+ description: `Question ${qId} has ${correctCount} correct options (must be exactly 1).`,
14874
+ remediationAdvice: "Set `isCorrect: true` on exactly 1 option.",
14875
+ affectedElement: qId
14876
+ });
14877
+ }
15029
14878
  }
15030
- rows.push({
15031
- packId: pack.manifest.id,
15032
- statementId: statement.id,
15033
- statementText: Object.values(statement.texts)[0] ?? "",
15034
- status,
15035
- objectives: los,
15036
- hasActivity,
15037
- hasAssessment,
15038
- issues
15039
- });
15040
14879
  }
15041
- }
15042
- for (const lo of input.objectives) {
15043
- for (const r of lo.standardRefs ?? []) {
15044
- if (!resolveStatementRef(r, input.packs)) {
15045
- rows.push({
15046
- packId: "(unresolved)",
15047
- statementId: r,
15048
- statementText: "",
15049
- status: "UNCOVERED",
15050
- objectives: [lo.code],
15051
- hasActivity: false,
15052
- hasAssessment: false,
15053
- issues: [`standardRef "${r}" does not exist in any adopted pack \u2014 likely a hallucinated or stale ID`]
14880
+ if (activity?.materialsBOM?.hardware && activity.materialsBOM.hardware.length > 0) {
14881
+ const hwText = activity.materialsBOM.hardware.join(" ").toLowerCase();
14882
+ const hasLED = hwText.includes("led");
14883
+ const hasResistor = hwText.includes("\u0111i\u1EC7n tr\u1EDF") || hwText.includes("resistor") || hwText.includes("220") || hwText.includes("330") || hwText.includes("1k");
14884
+ if (hasLED && !hasResistor) {
14885
+ score -= 20;
14886
+ findings.push({
14887
+ id: "struct_hardware_unsafe_led_no_resistor",
14888
+ dimension: "TECHNICAL_AUTHENTICITY",
14889
+ severity: "CRITICAL",
14890
+ title: "Unsafe Circuit BOM: LED without Current-Limiting Resistor",
14891
+ description: "Hardware BOM includes LED without a 220\u03A9-1k\u03A9 resistor, causing circuit overload.",
14892
+ remediationAdvice: "Add a 220\u03A9 current-limiting resistor to the hardware materials list."
15054
14893
  });
15055
14894
  }
15056
14895
  }
15057
- }
15058
- const complianceRows = rows.filter((r) => r.status !== "UNMAPPED" && r.status !== "PARTIAL");
15059
- const covered = complianceRows.filter((r) => r.status === "COVERED").length;
15060
- const coveragePct = complianceRows.length === 0 ? 100 : Math.round(covered / complianceRows.length * 100);
15061
- const unresolvedCount = rows.filter((r) => r.packId === "(unresolved)").length;
15062
- const verdict = unresolvedCount > 0 || coveragePct < 60 ? "FAIL" : coveragePct < 100 ? "WARN" : "PASS";
15063
- const lines = [
15064
- "# Standards Coverage Report",
15065
- "",
15066
- `- Verdict: **${verdict}**`,
15067
- `- Compliance coverage: **${coveragePct}%** (${covered}/${complianceRows.length} "covers" statements fully taught + assessed)`,
15068
- `- Unresolved standardRefs: ${unresolvedCount}`,
15069
- "",
15070
- "| Pack | Statement | Status | LOs | Activity | Assessment |",
15071
- "|---|---|---|---|---|---|",
15072
- ...rows.map(
15073
- (r) => `|${r.packId}|${r.statementId}|${r.status}|${r.objectives.join(", ") || "\u2014"}|${r.hasActivity ? "\u2713" : "\u2717"}|${r.hasAssessment ? "\u2713" : "\u2717"}|`
15074
- )
15075
- ];
15076
- const issueLines = rows.filter((r) => r.issues.length > 0).flatMap((r) => r.issues.map((i) => `- [${r.packId}:${r.statementId}] ${i}`));
15077
- if (issueLines.length > 0) lines.push("", "## Issues", ...issueLines);
15078
- return {
15079
- verdict,
15080
- coveragePct,
15081
- rows,
15082
- summary: `Standards coverage ${coveragePct}% \u2014 verdict ${verdict}`,
15083
- rawMarkdownReport: lines.join("\n")
15084
- };
15085
- }
15086
- var StandardsRegistryAdapter = class {
15087
- client;
15088
- constructor(config = {}) {
15089
- if (config.client) {
15090
- this.client = config.client;
15091
- return;
15092
- }
15093
- const url = config.supabaseUrl || process.env.NEXT_PUBLIC_SUPABASE_URL || process.env.SUPABASE_URL || "";
15094
- const key = config.supabaseServiceRoleKey || process.env.SUPABASE_SERVICE_ROLE_KEY || config.supabaseAnonKey || process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || "";
15095
- if (!url || !key) {
15096
- throw new Error("StandardsRegistryAdapter: Supabase URL/key missing (pass client or env).");
15097
- }
15098
- this.client = createClient(url, key);
15099
- }
15100
- // ─── Intake (write path — service role) ───────────────────────────────────
15101
- /** Persist a schema-validated pack as a new framework (status=draft). */
15102
- async importPack(pack, opts) {
15103
- const parsed = FrameworkPackSchema.safeParse(pack);
15104
- if (!parsed.success) {
15105
- throw new Error("importPack: pack failed schema validation: " + parsed.error.issues.map((i) => i.path.join(".") + ": " + i.message).join("; "));
15106
- }
15107
- const p = parsed.data;
15108
- const { data: fw, error: fwErr } = await this.client.from("standards_frameworks").insert({
15109
- pack_id: p.manifest.id,
15110
- content_version: p.manifest.contentVersion,
15111
- name: p.manifest.name,
15112
- spec_version: p.manifest.specVersion,
15113
- subject: p.manifest.subject,
15114
- languages: p.manifest.languages,
15115
- grade_model: p.manifest.gradeModel,
15116
- provenance: p.manifest.provenance,
15117
- trust: p.manifest.trust,
15118
- status: "draft",
15119
- organization_code: opts?.organizationCode ?? (p.manifest.trust === "verified" ? null : p.manifest.provenance.importedBy?.replace(/^org:/, "") || null),
15120
- original_file_path: opts?.originalFilePath ?? null,
15121
- created_by: opts?.createdBy ?? null
15122
- }).select("id").single();
15123
- if (fwErr) throw new Error("importPack: framework insert failed: " + fwErr.message);
15124
- const frameworkId = fw.id;
15125
- const statementRows = p.statements.map((s) => ({
15126
- framework_id: frameworkId,
15127
- statement_id: s.id,
15128
- parent_statement_id: s.parentId ?? null,
15129
- grade_min: s.gradeBand[0],
15130
- grade_max: s.gradeBand[1],
15131
- texts: s.texts,
15132
- classifications: s.classifications ?? [],
15133
- bloom_hint: s.bloomHint ?? null,
15134
- keywords: s.keywords ?? [],
15135
- source_ref: s.sourceRef ?? null,
15136
- provenance: s.provenance
15137
- }));
15138
- const { error: stErr, count: stCount } = await this.client.from("standards_statements").insert(statementRows, { count: "exact" });
15139
- if (stErr) throw new Error("importPack: statement insert failed: " + stErr.message);
15140
- let mappingCount = 0;
15141
- if (p.mappings && p.mappings.length > 0) {
15142
- const mappingRows = p.mappings.map((m) => ({
15143
- framework_id: frameworkId,
15144
- statement_id: m.statementId,
15145
- target_ref: m.targetRef,
15146
- kind: m.kind,
15147
- confidence: m.confidence,
15148
- provenance: m.provenance
15149
- }));
15150
- const { error: mpErr, count: mpCount } = await this.client.from("standards_mappings").insert(mappingRows, { count: "exact" });
15151
- if (mpErr) throw new Error("importPack: mapping insert failed: " + mpErr.message);
15152
- mappingCount = mpCount ?? mappingRows.length;
14896
+ score = Math.max(0, Math.min(100, score));
14897
+ const passed = score >= 80 && !findings.some((f) => f.severity === "CRITICAL");
14898
+ if (passed) {
14899
+ strengths.push("Deterministic structure, ID contracts, and schema invariants strictly verified.");
15153
14900
  }
15154
- return { frameworkDbId: frameworkId, statementsInserted: stCount ?? statementRows.length, mappingsInserted: mappingCount };
15155
- }
15156
- /** Activate a draft framework (immutable version is now live). */
15157
- async activatePack(frameworkDbId) {
15158
- const { error } = await this.client.from("standards_frameworks").update({ status: "active" }).eq("id", frameworkDbId).eq("status", "draft");
15159
- if (error) throw new Error("activatePack failed: " + error.message);
15160
- }
15161
- async deprecatePack(frameworkDbId) {
15162
- const { error } = await this.client.from("standards_frameworks").update({ status: "deprecated" }).eq("id", frameworkDbId);
15163
- if (error) throw new Error("deprecatePack failed: " + error.message);
15164
- }
15165
- async adoptPack(frameworkDbId, organizationCode, adoptedBy) {
15166
- const { error } = await this.client.from("standards_org_adoptions").upsert(
15167
- { framework_id: frameworkDbId, organization_code: organizationCode, adopted_by: adoptedBy ?? null },
15168
- { onConflict: "organization_code,framework_id" }
15169
- );
15170
- if (error) throw new Error("adoptPack failed: " + error.message);
14901
+ return {
14902
+ passed,
14903
+ structuralScore: score,
14904
+ findings,
14905
+ strengths
14906
+ };
15171
14907
  }
15172
- // ─── Runtime (read path — generation) ─────────────────────────────────────
14908
+ };
14909
+
14910
+ // src/evaluators/academicAuditor.ts
14911
+ var AcademicAuditor = class {
15173
14912
  /**
15174
- * Load all packs usable by an org: platform packs (verified, org IS NULL) +
15175
- * org packs + org adoptions. Hydrated into the same FrameworkPack shape the
15176
- * in-memory Phase-1 components consume (injector / coverage gate / judge).
14913
+ * Evaluates a complete lesson bundle.
14914
+ * Step 1 (Deterministic): Fast structural, contract, schema, and safety linting.
14915
+ * Step 2 (Semantic LLM-as-a-Judge): Deep pedagogical, cognitive (Bloom), and misconception analysis with live frontier LLM.
15177
14916
  */
15178
- async loadPacksForOrg(organizationCode) {
15179
- let query = this.client.from("standards_frameworks").select("*, standards_org_adoptions(organization_code)").eq("status", "active");
15180
- const { data: frameworks, error } = await query;
15181
- if (error) throw new Error("loadPacksForOrg: " + error.message);
15182
- const visible = (frameworks ?? []).filter((f) => {
15183
- const own = f.organization_code && organizationCode && f.organization_code === organizationCode;
15184
- const global = !f.organization_code;
15185
- const adopted = organizationCode && (f.standards_org_adoptions ?? []).some((a) => a.organization_code === organizationCode);
15186
- return global || own || adopted;
14917
+ static async auditLessonBundle(input) {
14918
+ const { lesson, quiz, activity, slides, codeLab, modelOptions, executeLLMJudge = true } = input;
14919
+ const structuralResult = DeterministicStructuralLinter.lintBundle({
14920
+ lesson,
14921
+ quiz,
14922
+ activity,
14923
+ slides,
14924
+ codeLab
15187
14925
  });
15188
- if (visible.length === 0) return [];
15189
- const ids = visible.map((f) => f.id);
15190
- const [{ data: statements, error: stErr }, { data: mappings, error: mpErr }, { data: overrides, error: ovErr }] = await Promise.all([
15191
- this.client.from("standards_statements").select("*").in("framework_id", ids),
15192
- this.client.from("standards_mappings").select("*").in("framework_id", ids),
15193
- this.client.from("standards_mapping_overrides").select("*").in("framework_id", ids)
15194
- ]);
15195
- if (stErr) throw new Error("loadPacksForOrg statements: " + stErr.message);
15196
- const overridesByFw = /* @__PURE__ */ new Map();
15197
- for (const o of overrides ?? []) {
15198
- const list = overridesByFw.get(o.framework_id) ?? [];
15199
- list.push(o);
15200
- overridesByFw.set(o.framework_id, list);
15201
- }
15202
- return visible.map((f) => {
15203
- const stmts = (statements ?? []).filter((s) => s.framework_id === f.id).map((s) => ({
15204
- id: s.statement_id,
15205
- parentId: s.parent_statement_id ?? void 0,
15206
- gradeBand: [s.grade_min, s.grade_max],
15207
- texts: s.texts,
15208
- classifications: s.classifications ?? [],
15209
- bloomHint: s.bloom_hint ?? void 0,
15210
- keywords: s.keywords ?? [],
15211
- sourceRef: s.source_ref ?? void 0,
15212
- provenance: s.provenance ?? { method: "imported" }
15213
- }));
15214
- const ov = overridesByFw.get(f.id) ?? [];
15215
- const retired = new Set(ov.filter((o) => o.kind === "retired").map((o) => o.statement_id + "|" + o.target_ref));
15216
- const embedded = (mappings ?? []).filter((m) => m.framework_id === f.id).map((m) => ({
15217
- statementId: m.statement_id,
15218
- targetRef: m.target_ref,
15219
- kind: m.kind,
15220
- confidence: Number(m.confidence),
15221
- provenance: m.provenance ?? { method: "imported" }
15222
- }));
15223
- const overlay = ov.filter((o) => o.kind !== "retired").map((o) => ({
15224
- statementId: o.statement_id,
15225
- targetRef: o.target_ref,
15226
- kind: o.kind,
15227
- confidence: Number(o.confidence),
15228
- provenance: { method: "human", reviewedBy: o.created_by ?? "overlay", note: o.note ?? void 0 }
15229
- }));
15230
- const bridge = /* @__PURE__ */ new Map();
15231
- for (const m of embedded) bridge.set(m.statementId + "|" + m.targetRef, m);
15232
- for (const m of overlay) bridge.set(m.statementId + "|" + m.targetRef, m);
15233
- const finalMappings = [...bridge.values()].filter((m) => !retired.has(m.statementId + "|" + m.targetRef));
15234
- const hydrated = FrameworkPackSchema.safeParse({
15235
- manifest: {
15236
- id: f.pack_id,
15237
- name: f.name,
15238
- specVersion: f.spec_version || "1.0",
15239
- contentVersion: f.content_version,
15240
- subject: f.subject,
15241
- languages: f.languages,
15242
- gradeModel: f.grade_model,
15243
- provenance: f.provenance,
15244
- trust: f.trust
15245
- },
15246
- statements: stmts,
15247
- mappings: finalMappings
15248
- });
15249
- if (!hydrated.success) {
15250
- throw new Error('loadPacksForOrg: hydrated pack "' + f.pack_id + '" failed schema: ' + hydrated.error.issues[0]?.message);
15251
- }
15252
- return { ...hydrated.data, dbId: f.id, status: f.status, organizationCode: f.organization_code ?? null };
15253
- });
15254
- }
15255
- };
15256
-
15257
- // src/workflow/workflows/milestoneWorkflow.ts
15258
- async function generateMilestoneWorkflow(input) {
15259
- "use workflow";
15260
- const language = input.language || "vi";
15261
- const milestoneId = input.milestone.id || input.milestone.concept_code || "L01";
15262
- const slugPrefix = /^\d+$/.test(milestoneId) ? `M${milestoneId.padStart(2, "0")}` : milestoneId;
15263
- const milestoneSlug = `${slugPrefix}_${(input.milestone.name || "milestone").toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "")}`;
15264
- const bundleTier = input.bundleTier || "minimum";
15265
- const gates = resolveGateSettings(input.gateSettings);
15266
- const techStack = input.techStack || input.milestone.tech_keywords || ["General Technology"];
15267
- console.log(" \u{1F6A6} [Gate] LESSON: " + gates.LESSON + " | ACT: " + gates.ACT + " | QUIZ: " + gates.QUIZ);
15268
- const targetObjectives = (input.milestone.learning_objectives || []).map((lo) => ({
15269
- code: lo.code,
15270
- description: lo.description || lo.name || "",
15271
- bloomLevel: lo.bloom_level || "understand"
15272
- }));
15273
- const packs = input.standardsPacks ?? [];
15274
- const { block: standardsContext, selected: selectedStatements } = buildStandardsContext({
15275
- packs,
15276
- gradeBand: input.milestone.grade_band ?? [6, 12],
15277
- topicText: [input.topic, input.milestone.name, input.milestone.description, ...input.milestone.tech_keywords || []].filter(Boolean).join(" "),
15278
- conceptCodes: (input.milestone.concept_code || "").split(",").map((c) => c.trim()).filter(Boolean),
15279
- language
15280
- });
15281
- const standardStatements = {};
15282
- for (const s of selectedStatements) {
15283
- standardStatements[s.packId + ":" + s.statement.id] = Object.values(s.statement.texts)[0] || "";
15284
- }
15285
- if (selectedStatements.length > 0) {
15286
- console.log(" \u{1F4D0} [Standards] Grounded with " + selectedStatements.length + " verbatim statement(s) from " + new Set(selectedStatements.map((s) => s.packId)).size + " pack(s)");
15287
- }
15288
- let lesson = await generateMasterLessonStep({
15289
- milestone: input.milestone,
15290
- language,
15291
- topic: input.topic,
15292
- targetAudience: input.targetAudience,
15293
- standardsContext: standardsContext || void 0,
15294
- modelOptions: input.modelOptions
15295
- });
15296
- let auditReport;
15297
- const lessonGate = gateModeFor(gates, "LESSON");
15298
- if (lessonGate === "LLM_JUDGE") {
15299
- auditReport = await judgeMasterLessonStep({
15300
- lessonId: milestoneId,
15301
- lesson,
15302
- language,
15303
- targetObjectives,
15304
- standardStatements: Object.keys(standardStatements).length > 0 ? standardStatements : void 0,
15305
- modelOptions: input.modelOptions
15306
- });
15307
- if (auditReport.overallVerdict === "FAIL" || auditReport.overallVerdict === "NEEDS_REVISION") {
15308
- lesson = await repairMasterLessonStep({
15309
- milestone: input.milestone,
15310
- language,
15311
- topic: input.topic,
15312
- targetAudience: input.targetAudience,
15313
- auditReport,
15314
- standardsContext: standardsContext || void 0,
15315
- modelOptions: input.modelOptions
15316
- });
15317
- }
15318
- } else if (lessonGate === "HITL") {
15319
- const hookToken = "gate:lesson:" + milestoneId;
15320
- console.log(" \u23F8 [Gate] LESSON awaiting HUMAN review (HITL) \u2014 hook " + hookToken);
15321
- const workflowPkg = await import('workflow');
15322
- const createHook = workflowPkg.createHook;
15323
- const hook = createHook({ token: hookToken });
15324
- const review = await hook;
15325
- console.log(" \u2705 [Gate] Human verdict: " + (review.approved ? "APPROVED" : "REJECTED") + (review.feedback ? " \u2014 " + review.feedback : ""));
15326
- if (!review.approved) {
15327
- const repairReport = {
15328
- overallVerdict: "NEEDS_REVISION",
15329
- totalScore: 0,
15330
- languageAdherencePassed: true,
15331
- criteria: [],
15332
- actionableRepairPrompts: review.feedback ? [review.feedback] : ["S\u1EEDa theo ph\u1EA3n h\u1ED3i c\u1EE7a ng\u01B0\u1EDDi duy\u1EC7t"]
15333
- };
15334
- lesson = await repairMasterLessonStep({
15335
- milestone: input.milestone,
15336
- language,
15337
- topic: input.topic,
15338
- targetAudience: input.targetAudience,
15339
- auditReport: repairReport,
15340
- standardsContext: standardsContext || void 0,
15341
- modelOptions: input.modelOptions
15342
- });
15343
- const hook2 = createHook({ token: hookToken + ":v2" });
15344
- const review2 = await hook2;
15345
- console.log(" \u2705 [Gate] Human verdict (v2): " + (review2.approved ? "APPROVED" : "REJECTED"));
15346
- if (!review2.approved) {
15347
- console.log(" \u{1F6D1} [Gate] LESSON rejected twice \u2014 satellites & save BLOCKED");
15348
- return {
15349
- milestoneId,
15350
- milestoneSlug,
15351
- status: "FAILED",
15352
- gateBlocked: { artifactType: "LESSON", reason: "HITL_REJECTED_V2", feedback: review2.feedback },
15353
- artifacts: void 0
15354
- };
15355
- }
15356
- }
15357
- }
15358
- const [activity, selfLab, quiz, slides, handout] = await Promise.all([
15359
- generateActivityStep({ lesson, language, modelOptions: input.modelOptions }),
15360
- generateSelfLabStep({ milestone: input.milestone, language, targetTechStack: techStack, modelOptions: input.modelOptions }),
15361
- generateDiagnosticQuizStep({ milestone: input.milestone, language, modelOptions: input.modelOptions }),
15362
- generateSlidesStep({ lesson, language, modelOptions: input.modelOptions }),
15363
- generateHandoutStep({ lesson, language, modelOptions: input.modelOptions })
15364
- ]);
15365
- const codeLab = await generateCodeLabStep({
15366
- lesson,
15367
- activity,
15368
- language,
15369
- targetTechStack: techStack,
15370
- modelOptions: input.modelOptions
15371
- });
15372
- const satelliteReports = {};
15373
- const satelliteCandidates = [
15374
- { type: "ACT", id: "ACT_" + milestoneId, artifact: activity },
15375
- { type: "QUIZ", id: "QUIZ_" + milestoneId, artifact: quiz },
15376
- { type: "SLIDE", id: "SLIDE_" + milestoneId, artifact: slides },
15377
- { type: "HANDOUT", id: "HANDOUT_" + milestoneId, artifact: handout },
15378
- { type: "CODE", id: "CODE_" + milestoneId, artifact: codeLab }
15379
- ];
15380
- const toJudge = satelliteCandidates.filter((c) => c.artifact && gateModeFor(gates, c.type) === "LLM_JUDGE");
15381
- if (toJudge.length > 0) {
15382
- const reports = await Promise.all(
15383
- toJudge.map(
15384
- (c) => judgeSatelliteStep({
15385
- artifactType: c.type,
15386
- artifactId: c.id,
15387
- artifact: c.artifact,
15388
- language,
15389
- targetObjectives,
15390
- standardStatements: Object.keys(standardStatements).length > 0 ? standardStatements : void 0,
15391
- modelOptions: input.modelOptions
15392
- }).catch((err) => {
15393
- console.warn(" \u26A0 [Gate] satellite judge failed for " + c.type + ": " + err.message);
15394
- return void 0;
15395
- })
15396
- )
15397
- );
15398
- for (let i = 0; i < toJudge.length; i++) {
15399
- const r = reports[i];
15400
- if (r) satelliteReports[toJudge[i].type] = r;
15401
- }
15402
- }
15403
- let worksheet;
15404
- let teacherGuide;
15405
- let extension;
15406
- if (bundleTier === "full") {
15407
- [worksheet, teacherGuide, extension] = await Promise.all([
15408
- generateWorksheetStep({ lesson, language, modelOptions: input.modelOptions }),
15409
- generateTeacherGuideStep({ lesson, activity, language, modelOptions: input.modelOptions }),
15410
- generateExtensionStep({ lesson, activity, language, modelOptions: input.modelOptions })
15411
- ]);
15412
- }
15413
- let standardsCoverage;
15414
- if (packs.length > 0) {
15415
- standardsCoverage = evaluateStandardsCoverage({
15416
- packs,
15417
- objectives: (lesson.learningObjectives || []).map((lo) => ({
15418
- code: lo.code,
15419
- standardRefs: lo.standardRefs,
15420
- conceptRefs: lo.conceptRefs
15421
- })),
15422
- // NOTE: ActivityLab has no structured LO linkage yet — activity coverage rows are derived
15423
- // from LO→quiz paths inside the gate. Wire ACT.loRefs in a future schema revision.
15424
- activities: [],
15425
- quizQuestions: (quiz?.questions || []).map((q) => ({ alignedLO: q.alignedLO, alignedAO: q.alignedAO })),
15426
- assessmentObjectives: quiz?.assessmentObjectives?.map((ao) => ({ aoCode: ao.aoCode, alignedLO: ao.alignedLO }))
15427
- });
15428
- console.log(" \u{1F4D0} [Standards Coverage] " + standardsCoverage.summary);
15429
- const enforce = input.enforceStandardsCoverage ?? true;
15430
- if (enforce && standardsCoverage.verdict === "FAIL") {
15431
- console.error(" \u26D4 [Standards Coverage] HARD BLOCK \u2014 " + standardsCoverage.summary);
15432
- console.error(standardsCoverage.rawMarkdownReport.split("\n").filter((l) => l.startsWith("- [")).slice(0, 10).join("\n"));
15433
- return {
15434
- milestoneId,
15435
- milestoneSlug,
15436
- status: "FAILED",
15437
- savedResult: { workspaceDir: "", files: [] },
15438
- judgeReport: auditReport,
15439
- standardsCoverage,
15440
- artifacts: { lesson, activity, codeLab, selfLab, quiz, slides, handout, worksheet, teacherGuide, extension }
15441
- };
15442
- }
15443
- }
15444
- const savedResult = await saveMilestoneToWorkspaceStep({
15445
- jobId: input.jobId,
15446
- milestoneSlug,
15447
- lesson,
15448
- activity,
15449
- codeLab,
15450
- selfLab,
15451
- quiz,
15452
- slides,
15453
- handout,
15454
- baseWorkspaceDir: input.baseWorkspaceDir
15455
- });
15456
- return {
15457
- milestoneId,
15458
- milestoneSlug,
15459
- status: "SUCCESS",
15460
- savedResult,
15461
- judgeReport: auditReport,
15462
- satelliteJudgeReports: Object.keys(satelliteReports).length > 0 ? satelliteReports : void 0,
15463
- gatesResolved: gates,
15464
- standardsCoverage,
15465
- artifacts: {
15466
- lesson,
15467
- activity,
15468
- codeLab,
15469
- selfLab,
15470
- quiz,
15471
- slides,
15472
- handout,
15473
- worksheet,
15474
- teacherGuide,
15475
- extension
15476
- }
15477
- };
15478
- }
15479
- async function generateRoadmapWorkflow(input) {
15480
- "use workflow";
15481
- const jobId = input.jobId || `job_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`;
15482
- const language = input.language || input.roadmap.target_language || "vi";
15483
- const topic = input.roadmap.topic || input.roadmap.goal || "General Curriculum";
15484
- const courseTitle = input.roadmap.title || `Curriculum: ${topic}`;
15485
- const batchSize = input.batchSize || 2;
15486
- const milestones = input.roadmap.milestones || [];
15487
- const workspaceManager = new LocalWorkspaceManager(input.baseWorkspaceDir);
15488
- const workspaceDir = await workspaceManager.initJobWorkspace(jobId, {
15489
- courseTitle,
15490
- topic,
15491
- language,
15492
- totalMilestones: milestones.length
15493
- });
15494
- const milestoneOutcomes = [];
15495
- for (let i = 0; i < milestones.length; i += batchSize) {
15496
- const batch = milestones.slice(i, i + batchSize);
15497
- const batchSettled = await Promise.allSettled(
15498
- batch.map(
15499
- (milestone) => generateMilestoneWorkflow({
15500
- jobId,
15501
- milestone,
15502
- language,
15503
- topic,
15504
- targetAudience: input.roadmap.target_audience,
15505
- techStack: input.roadmap.tech_stack || milestone.tech_keywords,
15506
- bundleTier: input.bundleTier,
15507
- gateSettings: input.gateSettings,
15508
- baseWorkspaceDir: input.baseWorkspaceDir,
15509
- modelOptions: input.modelOptions
15510
- })
15511
- )
15512
- );
15513
- for (const [idx, outcome] of batchSettled.entries()) {
15514
- const targetMilestone = batch[idx];
15515
- const mId = targetMilestone.id || targetMilestone.concept_code || `M${i + idx + 1}`;
15516
- if (outcome.status === "fulfilled") {
15517
- milestoneOutcomes.push({
15518
- milestoneId: mId,
15519
- status: "FULFILLED",
15520
- result: outcome.value
14926
+ const allFindings = [...structuralResult.findings];
14927
+ const strengths = [...structuralResult.strengths];
14928
+ let semanticScore = null;
14929
+ let semanticVerdict = "PASS";
14930
+ if (executeLLMJudge) {
14931
+ try {
14932
+ const judgeReport = await auditCurriculumQualityFlow({
14933
+ targetArtifactType: "LESSON_BUNDLE",
14934
+ lessonId: lesson.lessonId,
14935
+ expectedLanguage: lesson.language,
14936
+ targetObjectives: (lesson.learningObjectives || []).map((lo) => ({
14937
+ code: lo.code,
14938
+ description: lo.description,
14939
+ bloomLevel: lo.bloomLevel
14940
+ })),
14941
+ generatedContentJson: JSON.stringify({ lesson, quiz, activity, slides, codeLab }),
14942
+ modelOptions
15521
14943
  });
15522
- } else {
15523
- milestoneOutcomes.push({
15524
- milestoneId: mId,
15525
- status: "REJECTED",
15526
- error: outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason)
14944
+ semanticScore = judgeReport.totalScore;
14945
+ semanticVerdict = judgeReport.overallVerdict;
14946
+ for (const criterion of judgeReport.criteria) {
14947
+ if (!criterion.passed) {
14948
+ allFindings.push({
14949
+ id: `llm_judge_${criterion.name.toLowerCase().replace(/\s+/g, "_")}`,
14950
+ dimension: "CONSTRUCTIVE_ALIGNMENT",
14951
+ severity: criterion.score < 50 ? "CRITICAL" : "MAJOR",
14952
+ title: `LLM-as-Judge Finding: ${criterion.name}`,
14953
+ description: criterion.feedback,
14954
+ remediationAdvice: judgeReport.actionableRepairPrompts.join("; ") || "Refine prompt context."
14955
+ });
14956
+ } else {
14957
+ strengths.push(`[LLM-Judge] ${criterion.name}: ${criterion.feedback}`);
14958
+ }
14959
+ }
14960
+ } catch (err) {
14961
+ semanticScore = null;
14962
+ semanticVerdict = "FAIL";
14963
+ allFindings.push({
14964
+ id: "llm_judge_connection_error",
14965
+ dimension: "CONSTRUCTIVE_ALIGNMENT",
14966
+ severity: "MINOR",
14967
+ title: "LLM-as-Judge Skipped / Fallback",
14968
+ description: `Semantic inference error: ${err.message || String(err)}`,
14969
+ remediationAdvice: "Check API credentials for LLM-as-Judge."
15527
14970
  });
15528
14971
  }
15529
14972
  }
15530
- if (i + batchSize < milestones.length) {
15531
- await sleep("2s");
14973
+ const criticalCount = allFindings.filter((f) => f.severity === "CRITICAL").length;
14974
+ const overallScore = executeLLMJudge && semanticScore !== null ? Math.round(structuralResult.structuralScore * 0.4 + semanticScore * 0.6) : structuralResult.structuralScore;
14975
+ const passed = structuralResult.passed && criticalCount === 0 && (executeLLMJudge ? semanticVerdict === "PASS" : true);
14976
+ let verdict = "REJECTED";
14977
+ if (overallScore >= 90 && criticalCount === 0) {
14978
+ verdict = "EXEMPLARY";
14979
+ } else if (overallScore >= 75 && criticalCount === 0) {
14980
+ verdict = "ACADEMICALLY_SOUND";
14981
+ } else if (overallScore >= 60) {
14982
+ verdict = "NEEDS_PEDAGOGICAL_REFINEMENT";
15532
14983
  }
14984
+ const summary = passed ? `\u2705 Lesson Bundle "${lesson.title}" (${lesson.lessonId}) passes academic & structural verification with score ${overallScore}/100 (${verdict}).` : `\u26A0\uFE0F Lesson Bundle "${lesson.title}" requires revision (${overallScore}/100 - ${verdict}). Found ${allFindings.length} finding(s) with ${criticalCount} critical blocker(s).`;
14985
+ const actionablePromptGuidance = allFindings.map(
14986
+ (f, idx) => `[${f.dimension}] ${idx + 1}. ${f.title}: ${f.remediationAdvice}`
14987
+ );
14988
+ const computeDimScore = (dimFindings2) => {
14989
+ const hasCritical = dimFindings2.some((f) => f.severity === "CRITICAL");
14990
+ const majorCount = dimFindings2.filter((f) => f.severity === "MAJOR").length;
14991
+ const minorCount = dimFindings2.filter((f) => f.severity === "MINOR").length;
14992
+ let dimScore = 100 - (hasCritical ? 40 : 0) - majorCount * 15 - minorCount * 5;
14993
+ dimScore = Math.max(0, Math.min(100, dimScore));
14994
+ return { score: dimScore, passed: dimScore >= 75 && !hasCritical };
14995
+ };
14996
+ const dimFindings = {
14997
+ constructiveAlignment: allFindings.filter((f) => f.dimension === "CONSTRUCTIVE_ALIGNMENT"),
14998
+ bloomProgression: allFindings.filter((f) => f.dimension === "BLOOM_PROGRESSION"),
14999
+ fiveEFidelity: allFindings.filter((f) => f.dimension === "5E_INSTRUCTIONAL_FIDELITY"),
15000
+ misconceptionRigor: allFindings.filter((f) => f.dimension === "MISCONCEPTION_RIGOR"),
15001
+ technicalAuthenticity: allFindings.filter((f) => f.dimension === "TECHNICAL_AUTHENTICITY")
15002
+ };
15003
+ const dimScores = Object.fromEntries(
15004
+ Object.entries(dimFindings).map(([k, v]) => [k, computeDimScore(v)])
15005
+ );
15006
+ return {
15007
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
15008
+ targetId: lesson.lessonId,
15009
+ targetType: "BUNDLE",
15010
+ overallScore,
15011
+ passed,
15012
+ verdict,
15013
+ summary,
15014
+ dimensionScores: {
15015
+ constructiveAlignment: {
15016
+ score: dimScores.constructiveAlignment.score,
15017
+ weight: 0.2,
15018
+ passed: dimScores.constructiveAlignment.passed,
15019
+ strengths: dimScores.constructiveAlignment.passed ? ["Constructive alignment verified."] : [],
15020
+ findings: dimFindings.constructiveAlignment
15021
+ },
15022
+ bloomProgression: {
15023
+ score: dimScores.bloomProgression.score,
15024
+ weight: 0.2,
15025
+ passed: dimScores.bloomProgression.passed,
15026
+ strengths: dimScores.bloomProgression.passed ? ["Bloom taxonomy progression verified."] : [],
15027
+ findings: dimFindings.bloomProgression
15028
+ },
15029
+ fiveEFidelity: {
15030
+ score: dimScores.fiveEFidelity.score,
15031
+ weight: 0.15,
15032
+ passed: dimScores.fiveEFidelity.passed,
15033
+ strengths: dimScores.fiveEFidelity.passed ? ["5E instructional fidelity verified."] : [],
15034
+ findings: dimFindings.fiveEFidelity
15035
+ },
15036
+ misconceptionRigor: {
15037
+ score: dimScores.misconceptionRigor.score,
15038
+ weight: 0.2,
15039
+ passed: dimScores.misconceptionRigor.passed,
15040
+ strengths: dimScores.misconceptionRigor.passed ? ["Misconception rigor verified."] : [],
15041
+ findings: dimFindings.misconceptionRigor
15042
+ },
15043
+ technicalAuthenticity: {
15044
+ score: dimScores.technicalAuthenticity.score,
15045
+ weight: 0.15,
15046
+ passed: dimScores.technicalAuthenticity.passed,
15047
+ strengths: dimScores.technicalAuthenticity.passed ? ["Technical authenticity verified."] : [],
15048
+ findings: dimFindings.technicalAuthenticity
15049
+ },
15050
+ crossArtifactZeroDrift: {
15051
+ score: structuralResult.structuralScore,
15052
+ weight: 0.1,
15053
+ passed: structuralResult.passed,
15054
+ strengths: structuralResult.passed ? ["Cross-artifact zero drift verified."] : [],
15055
+ findings: allFindings.filter((f) => f.dimension === "CROSS_ARTIFACT_ZERO_DRIFT")
15056
+ }
15057
+ },
15058
+ criticalFindingsCount: criticalCount,
15059
+ allFindings,
15060
+ actionablePromptGuidance
15061
+ };
15533
15062
  }
15534
- const successfulMilestones = milestoneOutcomes.filter((m) => m.status === "FULFILLED").length;
15535
- const failedMilestones = milestoneOutcomes.filter((m) => m.status === "REJECTED").length;
15536
- let gitPublishResult = void 0;
15537
- let supabasePublishResult = void 0;
15538
- if (input.gitPublishOptions) {
15539
- gitPublishResult = await publishToGitStep({
15540
- jobId,
15541
- localJobDir: workspaceDir,
15542
- ...input.gitPublishOptions
15543
- });
15544
- }
15545
- if (input.supabasePublishOptions) {
15546
- supabasePublishResult = await publishToSupabaseStep({
15547
- jobId,
15548
- courseTitle,
15549
- topic,
15550
- language,
15551
- milestones: milestoneOutcomes.filter((m) => m.status === "FULFILLED" && m.result).map((m) => ({
15552
- milestoneId: m.milestoneId,
15553
- milestoneName: m.result.savedResult.milestoneSlug,
15554
- lessonSlug: m.result.savedResult.milestoneSlug
15555
- })),
15556
- ...input.supabasePublishOptions
15557
- });
15558
- }
15559
- return {
15560
- jobId,
15561
- courseTitle,
15562
- topic,
15563
- language,
15564
- totalMilestones: milestones.length,
15565
- successfulMilestones,
15566
- failedMilestones,
15567
- results: milestoneOutcomes,
15568
- gitPublishResult,
15569
- supabasePublishResult,
15570
- workspaceDir
15571
- };
15572
- }
15063
+ };
15573
15064
 
15574
- // src/workflow/workflows/singleArtifactWorkflow.ts
15575
- async function executeSingleArtifactStep(request) {
15576
- "use step";
15577
- const t0 = Date.now();
15578
- console.log(` \u23F3 [Step: Single Artifact] Generating ${request.artifactType.toUpperCase()} for "${request.topic.slice(0, 35)}"...`);
15579
- const res = await withRateLimitBackoff({
15580
- stepName: `generate-single-artifact-${request.artifactType}-${(request.topic || "topic").slice(0, 20)}`,
15581
- fn: async () => generateSingleArtifact(request)
15582
- });
15583
- console.log(` \u2705 [Step: Single Artifact] Done in ${((Date.now() - t0) / 1e3).toFixed(1)}s (File: "${res.filename}")`);
15584
- return res;
15585
- }
15586
- async function generateSingleArtifactWorkflow(request) {
15587
- "use workflow";
15588
- return executeSingleArtifactStep(request);
15589
- }
15590
-
15591
- // src/index.ts
15592
- init_errors();
15593
-
15594
- // src/evaluators/deterministicStructuralLinter.ts
15595
- var DeterministicStructuralLinter = class {
15065
+ // src/evaluators/bloomTaxonomyEvaluator.ts
15066
+ var BLOOM_ACTION_VERBS = {
15067
+ remember: [
15068
+ "list",
15069
+ "define",
15070
+ "recall",
15071
+ "state",
15072
+ "name",
15073
+ "identify",
15074
+ "label",
15075
+ "recognize",
15076
+ "li\u1EC7t k\xEA",
15077
+ "\u0111\u1ECBnh ngh\u0129a",
15078
+ "g\u1ECDi t\xEAn",
15079
+ "nh\u1EADn di\u1EC7n",
15080
+ "ch\u1EC9 ra",
15081
+ "nh\u1EAFc l\u1EA1i",
15082
+ "ghi nh\u1EDB"
15083
+ ],
15084
+ understand: [
15085
+ "explain",
15086
+ "describe",
15087
+ "summarize",
15088
+ "classify",
15089
+ "interpret",
15090
+ "predict",
15091
+ "trace",
15092
+ "paraphrase",
15093
+ "gi\u1EA3i th\xEDch",
15094
+ "m\xF4 t\u1EA3",
15095
+ "t\xF3m t\u1EAFt",
15096
+ "ph\xE2n lo\u1EA1i",
15097
+ "di\u1EC5n gi\u1EA3i",
15098
+ "d\u1EF1 \u0111o\xE1n",
15099
+ "l\u1EA7n theo",
15100
+ "hi\u1EC3u"
15101
+ ],
15102
+ apply: [
15103
+ "implement",
15104
+ "execute",
15105
+ "calculate",
15106
+ "solve",
15107
+ "construct",
15108
+ "debug",
15109
+ "modify",
15110
+ "build",
15111
+ "\xE1p d\u1EE5ng",
15112
+ "th\u1EF1c thi",
15113
+ "t\xEDnh to\xE1n",
15114
+ "gi\u1EA3i quy\u1EBFt",
15115
+ "x\xE2y d\u1EF1ng",
15116
+ "s\u1EEDa l\u1ED7i",
15117
+ "l\u1EAFp \u0111\u1EB7t",
15118
+ "vi\u1EBFt m\xE3",
15119
+ "l\u1EADp tr\xECnh"
15120
+ ],
15121
+ analyze: [
15122
+ "compare",
15123
+ "contrast",
15124
+ "decompose",
15125
+ "differentiate",
15126
+ "troubleshoot",
15127
+ "diagnose",
15128
+ "deconstruct",
15129
+ "so s\xE1nh",
15130
+ "\u0111\u1ED1i chi\u1EBFu",
15131
+ "ph\xE2n t\xEDch",
15132
+ "ph\xE2n r\xE3",
15133
+ "ch\u1EA9n \u0111o\xE1n",
15134
+ "t\xECm nguy\xEAn nh\xE2n g\u1ED1c",
15135
+ "b\xF3c t\xE1ch"
15136
+ ],
15137
+ evaluate: [
15138
+ "justify",
15139
+ "critique",
15140
+ "assess",
15141
+ "defend",
15142
+ "argue",
15143
+ "benchmark",
15144
+ "prioritize",
15145
+ "\u0111\xE1nh gi\xE1",
15146
+ "bi\u1EC7n minh",
15147
+ "ph\xEA ph\xE1n",
15148
+ "th\u1EA9m \u0111\u1ECBnh",
15149
+ "b\u1EA3o v\u1EC7 quan \u0111i\u1EC3m",
15150
+ "l\u1EF1a ch\u1ECDn t\u1ED1i \u01B0u"
15151
+ ],
15152
+ create: [
15153
+ "design",
15154
+ "synthesize",
15155
+ "architect",
15156
+ "formulate",
15157
+ "invent",
15158
+ "devise",
15159
+ "author",
15160
+ "thi\u1EBFt k\u1EBF",
15161
+ "t\u1ED5ng h\u1EE3p",
15162
+ "s\xE1ng t\u1EA1o",
15163
+ "ki\u1EBFn tr\xFAc",
15164
+ "ph\xE1t minh",
15165
+ "ho\xE0n thi\u1EC7n \u0111\u1ED3 \xE1n"
15166
+ ]
15167
+ };
15168
+ var RECALL_PATTERNS = [
15169
+ /^(?:chức năng chính của|định nghĩa của|cú pháp của|lệnh nào là|what is the definition of|which keyword|what does .* stand for)/i,
15170
+ /(?:là gì\?|được gọi là gì\?|có ý nghĩa gì\?)/i
15171
+ ];
15172
+ var BloomTaxonomyEvaluator = class {
15596
15173
  /**
15597
- * Validates structural invariants across a complete lesson bundle.
15174
+ * Audits a LessonPlan for Bloom taxonomy fidelity and cognitive scaffolding.
15598
15175
  */
15599
- static lintBundle(input) {
15600
- const { lesson, quiz, activity, slides, codeLab } = input;
15176
+ static evaluateLesson(lesson) {
15601
15177
  const findings = [];
15602
15178
  const strengths = [];
15603
15179
  let score = 100;
15604
- const baseLessonId = lesson.lessonId;
15605
- const baseLanguage = lesson.language;
15606
- if (!lesson.title || lesson.title.trim().length === 0) {
15607
- score -= 20;
15608
- findings.push({
15609
- id: "struct_missing_lesson_title",
15610
- dimension: "CROSS_ARTIFACT_ZERO_DRIFT",
15611
- severity: "CRITICAL",
15612
- title: "Missing Lesson Title",
15613
- description: "Lesson plan has an empty or whitespace title.",
15614
- remediationAdvice: "Provide a non-empty lesson title."
15615
- });
15180
+ const los = lesson.learningObjectives || [];
15181
+ if (los.length === 0) {
15182
+ return {
15183
+ score: 0,
15184
+ weight: 0.2,
15185
+ passed: false,
15186
+ strengths: [],
15187
+ findings: [
15188
+ {
15189
+ id: "bloom_missing_los",
15190
+ dimension: "BLOOM_PROGRESSION",
15191
+ severity: "CRITICAL",
15192
+ title: "Missing Learning Objectives",
15193
+ description: "The lesson plan contains zero declared Learning Objectives.",
15194
+ remediationAdvice: "Add 2-4 clearly articulated LOs with Bloom levels and observable success criteria."
15195
+ }
15196
+ ]
15197
+ };
15616
15198
  }
15617
- if (!lesson.learningObjectives || lesson.learningObjectives.length === 0) {
15618
- score -= 25;
15619
- findings.push({
15620
- id: "struct_empty_learning_objectives",
15621
- dimension: "CONSTRUCTIVE_ALIGNMENT",
15622
- severity: "CRITICAL",
15623
- title: "Empty Learning Objectives Array",
15624
- description: "Lesson plan contains 0 learning objectives.",
15625
- remediationAdvice: "Declare at least 2 structured Learning Objectives in the schema."
15626
- });
15199
+ for (const lo of los) {
15200
+ const declaredLevel = (lo.bloomLevel || "").toLowerCase();
15201
+ const text = `${lo.name || ""} ${lo.description || ""} ${lo.successCriteria || ""}`.toLowerCase();
15202
+ const isRecallPattern = RECALL_PATTERNS.some((p) => p.test(text));
15203
+ if (isRecallPattern && (declaredLevel === "apply" || declaredLevel === "analyze" || declaredLevel === "evaluate")) {
15204
+ score -= 15;
15205
+ findings.push({
15206
+ id: `bloom_inflation_${lo.code}`,
15207
+ dimension: "BLOOM_PROGRESSION",
15208
+ severity: "MAJOR",
15209
+ title: `Bloom Level Inflation in LO "${lo.code}"`,
15210
+ description: `LO is tagged as "${lo.bloomLevel}" but its phrasing reflects low-level Recall ("${lo.description}").`,
15211
+ remediationAdvice: `Rewrite the objective using authentic "${declaredLevel}" active verbs (e.g. build, debug, compare, diagnose) with an explicit application context.`,
15212
+ affectedElement: lo.code
15213
+ });
15214
+ }
15215
+ if (!lo.successCriteria || lo.successCriteria.trim().length < 15) {
15216
+ score -= 10;
15217
+ findings.push({
15218
+ id: `bloom_unmeasurable_criteria_${lo.code}`,
15219
+ dimension: "BLOOM_PROGRESSION",
15220
+ severity: "MINOR",
15221
+ title: `Vague Success Criteria in LO "${lo.code}"`,
15222
+ description: `Success criteria "${lo.successCriteria || ""}" is too brief to provide objective student evidence.`,
15223
+ remediationAdvice: 'Specify concrete, observable evidence (e.g. "LED blinks with 1s period without circuit shorting").',
15224
+ affectedElement: lo.code
15225
+ });
15226
+ } else {
15227
+ strengths.push(`LO "${lo.code}" defines concrete observable student evidence.`);
15228
+ }
15627
15229
  }
15628
- if (!lesson.sections || lesson.sections.length === 0) {
15629
- score -= 25;
15230
+ const diff = lesson.differentiation;
15231
+ if (diff) {
15232
+ if (!diff.bronzeTier || !diff.silverTier || !diff.goldTier) {
15233
+ score -= 15;
15234
+ findings.push({
15235
+ id: "bloom_incomplete_differentiation",
15236
+ dimension: "BLOOM_PROGRESSION",
15237
+ severity: "MAJOR",
15238
+ title: "Incomplete 3-Tier Scaffolding",
15239
+ description: "Differentiation must provide distinct Bronze (Foundation), Silver (Application), and Gold (Extension) challenges.",
15240
+ remediationAdvice: "Define all 3 tiers with increasing cognitive demands (Remember/Understand -> Apply -> Analyze/Create)."
15241
+ });
15242
+ } else {
15243
+ strengths.push("Complete 3-tier scaffolding (Bronze -> Silver -> Gold) present in Lesson Plan.");
15244
+ }
15245
+ } else {
15246
+ score -= 20;
15630
15247
  findings.push({
15631
- id: "struct_empty_lesson_sections",
15632
- dimension: "5E_INSTRUCTIONAL_FIDELITY",
15248
+ id: "bloom_missing_differentiation",
15249
+ dimension: "BLOOM_PROGRESSION",
15633
15250
  severity: "CRITICAL",
15634
- title: "Empty Lesson Sections Array",
15635
- description: "Lesson plan contains no instructional sections.",
15636
- remediationAdvice: "Provide structured lesson flow sections."
15251
+ title: "Missing Differentiation Scaffolding",
15252
+ description: "Lesson plan lacks differentiation tiers.",
15253
+ remediationAdvice: "Provide tiered practice instructions for varied learner paces."
15637
15254
  });
15638
15255
  }
15639
- if (quiz && quiz.quizId !== baseLessonId && !quiz.quizId.includes(baseLessonId)) {
15640
- score -= 15;
15256
+ score = Math.max(0, Math.min(100, score));
15257
+ return {
15258
+ score,
15259
+ weight: 0.2,
15260
+ passed: score >= 75 && !findings.some((f) => f.severity === "CRITICAL"),
15261
+ strengths,
15262
+ findings
15263
+ };
15264
+ }
15265
+ /**
15266
+ * Audits a Diagnostic Quiz for true cognitive depth matching declared Bloom levels.
15267
+ */
15268
+ static evaluateQuiz(quiz) {
15269
+ const findings = [];
15270
+ const strengths = [];
15271
+ let score = 100;
15272
+ const questions = quiz.questions || [];
15273
+ if (questions.length < 3) {
15274
+ score -= 30;
15641
15275
  findings.push({
15642
- id: "struct_quiz_id_mismatch",
15643
- dimension: "CROSS_ARTIFACT_ZERO_DRIFT",
15276
+ id: "bloom_quiz_too_short",
15277
+ dimension: "BLOOM_PROGRESSION",
15644
15278
  severity: "MAJOR",
15645
- title: "Quiz ID Contract Mismatch",
15646
- description: `Quiz ID "${quiz.quizId}" does not match Lesson ID "${baseLessonId}".`,
15647
- remediationAdvice: `Sync Quiz quizId to "${baseLessonId}".`,
15648
- affectedElement: quiz.quizId
15279
+ title: "Insufficient Question Pool",
15280
+ description: `Quiz only contains ${questions.length} questions. Minimum diagnostic threshold is 3 questions.`,
15281
+ remediationAdvice: "Generate at least 3-5 diagnostic questions covering foundational through analytical depth."
15649
15282
  });
15650
15283
  }
15651
- if (activity && activity.lessonId !== baseLessonId) {
15652
- score -= 15;
15653
- findings.push({
15654
- id: "struct_act_id_mismatch",
15655
- dimension: "CROSS_ARTIFACT_ZERO_DRIFT",
15284
+ let understandCount = 0;
15285
+ let applyCount = 0;
15286
+ let analyzeCount = 0;
15287
+ for (let i = 0; i < questions.length; i++) {
15288
+ const q = questions[i];
15289
+ const qId = q.id || `Q${i + 1}`;
15290
+ const declaredBloom = (q.bloomLevel || "").toLowerCase();
15291
+ const stem = q.scenarioOrStem || "";
15292
+ if (declaredBloom === "understand") understandCount++;
15293
+ if (declaredBloom === "apply") applyCount++;
15294
+ if (declaredBloom === "analyze" || declaredBloom === "evaluate") analyzeCount++;
15295
+ const isRecall = RECALL_PATTERNS.some((p) => p.test(stem));
15296
+ if (isRecall && (declaredBloom === "apply" || declaredBloom === "analyze")) {
15297
+ score -= 15;
15298
+ findings.push({
15299
+ id: `bloom_quiz_misclassification_${qId}`,
15300
+ dimension: "BLOOM_PROGRESSION",
15301
+ severity: "MAJOR",
15302
+ title: `Cognitive Level Misclassification in ${qId}`,
15303
+ description: `Question stem "${stem.substring(0, 60)}..." is pure Recall/Definition, but is tagged as "${q.bloomLevel}".`,
15304
+ remediationAdvice: 'Either re-tag as "understand" or transform the stem into an authentic problem-solving scenario requiring code debugging or design decision.',
15305
+ affectedElement: qId
15306
+ });
15307
+ }
15308
+ if ((declaredBloom === "apply" || declaredBloom === "analyze") && !q.codeSnippet && !stem.includes("```") && !stem.includes("m\u1EA1ch")) {
15309
+ score -= 10;
15310
+ findings.push({
15311
+ id: `bloom_quiz_missing_code_context_${qId}`,
15312
+ dimension: "BLOOM_PROGRESSION",
15313
+ severity: "MINOR",
15314
+ title: `Missing Practical Context in High-Bloom Question ${qId}`,
15315
+ description: `Question ${qId} tagged as "${q.bloomLevel}" lacks concrete code or circuit context to evaluate hands-on execution.`,
15316
+ remediationAdvice: "Include an annotated code snippet or circuit state for students to trace, debug, or evaluate.",
15317
+ affectedElement: qId
15318
+ });
15319
+ }
15320
+ }
15321
+ if (questions.length > 0 && (understandCount > 0 || applyCount > 0)) {
15322
+ strengths.push(`Quiz features multi-level cognitive questions (Understand: ${understandCount}, Apply: ${applyCount}, Analyze: ${analyzeCount}).`);
15323
+ }
15324
+ score = Math.max(0, Math.min(100, score));
15325
+ return {
15326
+ score,
15327
+ weight: 0.2,
15328
+ passed: score >= 75 && !findings.some((f) => f.severity === "CRITICAL"),
15329
+ strengths,
15330
+ findings
15331
+ };
15332
+ }
15333
+ };
15334
+
15335
+ // src/evaluators/crossArtifactDriftEvaluator.ts
15336
+ var CrossArtifactDriftEvaluator = class {
15337
+ /**
15338
+ * Audits consistency, metadata synchronization, and zero-drift across all artifacts in a lesson bundle.
15339
+ */
15340
+ static evaluateBundle(lesson, quiz, activity, slides) {
15341
+ const findings = [];
15342
+ const strengths = [];
15343
+ let score = 100;
15344
+ const baseLessonId = lesson.lessonId;
15345
+ const baseLanguage = lesson.language;
15346
+ if (quiz && quiz.quizId && quiz.quizId !== baseLessonId && !quiz.quizId.includes(baseLessonId)) {
15347
+ score -= 15;
15348
+ findings.push({
15349
+ id: "drift_quiz_id_mismatch",
15350
+ dimension: "CROSS_ARTIFACT_ZERO_DRIFT",
15656
15351
  severity: "MAJOR",
15657
- title: "Activity Lesson ID Contract Mismatch",
15658
- description: `Activity lessonId "${activity.lessonId}" does not match Lesson ID "${baseLessonId}".`,
15659
- remediationAdvice: `Sync Activity lessonId to "${baseLessonId}".`,
15352
+ title: "Quiz ID Mismatch with Master Lesson",
15353
+ description: `Quiz ID "${quiz.quizId}" diverges from master Lesson ID "${baseLessonId}".`,
15354
+ remediationAdvice: `Align Quiz ID to "${baseLessonId}".`,
15355
+ affectedElement: quiz.quizId
15356
+ });
15357
+ }
15358
+ if (activity && activity.lessonId && activity.lessonId !== baseLessonId) {
15359
+ score -= 15;
15360
+ findings.push({
15361
+ id: "drift_act_id_mismatch",
15362
+ dimension: "CROSS_ARTIFACT_ZERO_DRIFT",
15363
+ severity: "MAJOR",
15364
+ title: "Activity Lesson ID Mismatch",
15365
+ description: `Activity lessonId "${activity.lessonId}" diverges from master Lesson ID "${baseLessonId}".`,
15366
+ remediationAdvice: `Align Activity lessonId to "${baseLessonId}".`,
15660
15367
  affectedElement: activity.lessonId
15661
15368
  });
15662
15369
  }
15663
- if (slides && slides.lessonId !== baseLessonId) {
15370
+ if (slides && slides.lessonId && slides.lessonId !== baseLessonId) {
15664
15371
  score -= 15;
15665
15372
  findings.push({
15666
- id: "struct_slides_id_mismatch",
15373
+ id: "drift_slides_id_mismatch",
15667
15374
  dimension: "CROSS_ARTIFACT_ZERO_DRIFT",
15668
15375
  severity: "MAJOR",
15669
- title: "Slide Deck Lesson ID Contract Mismatch",
15670
- description: `Slide deck lessonId "${slides.lessonId}" does not match Lesson ID "${baseLessonId}".`,
15671
- remediationAdvice: `Sync Slide deck lessonId to "${baseLessonId}".`,
15376
+ title: "Slide Deck Lesson ID Mismatch",
15377
+ description: `Slide deck lessonId "${slides.lessonId}" diverges from master Lesson ID "${baseLessonId}".`,
15378
+ remediationAdvice: `Align Slide deck lessonId to "${baseLessonId}".`,
15672
15379
  affectedElement: slides.lessonId
15673
15380
  });
15674
15381
  }
@@ -15681,589 +15388,377 @@ var DeterministicStructuralLinter = class {
15681
15388
  if (sat.lang && sat.lang.toLowerCase() !== baseLanguage.toLowerCase()) {
15682
15389
  score -= 25;
15683
15390
  findings.push({
15684
- id: `struct_language_mismatch_${sat.type}`,
15391
+ id: `drift_language_mismatch_${sat.type}`,
15685
15392
  dimension: "CROSS_ARTIFACT_ZERO_DRIFT",
15686
15393
  severity: "CRITICAL",
15687
- title: `Language Policy Inconsistency in ${sat.type}`,
15394
+ title: `Language Contamination in ${sat.type}`,
15688
15395
  description: `Master Lesson is in "${baseLanguage}" but ${sat.type} is declared in "${sat.lang}".`,
15689
- remediationAdvice: `Set ${sat.type} language to "${baseLanguage}".`
15396
+ remediationAdvice: `Regenerate ${sat.type} strictly in "${baseLanguage}".`
15690
15397
  });
15691
15398
  }
15692
15399
  }
15693
- if (quiz && quiz.questions) {
15694
- for (let i = 0; i < quiz.questions.length; i++) {
15695
- const q = quiz.questions[i];
15696
- const qId = q.id || `Q${i + 1}`;
15697
- const options = q.options || [];
15698
- if (options.length < 4) {
15699
- score -= 10;
15700
- findings.push({
15701
- id: `struct_quiz_option_count_${qId}`,
15702
- dimension: "MISCONCEPTION_RIGOR",
15703
- severity: "MAJOR",
15704
- title: `Structural Option Count Error in ${qId}`,
15705
- description: `Question ${qId} has ${options.length} options (standard schema requires 4).`,
15706
- remediationAdvice: "Ensure each question has 4 options (A, B, C, D).",
15707
- affectedElement: qId
15708
- });
15709
- }
15710
- const correctCount = options.filter((o) => o.isCorrect).length;
15711
- if (correctCount !== 1) {
15400
+ const sections = lesson.sections || [];
15401
+ const totalSectionMins = sections.reduce((sum, s) => sum + (s.durationMinutes || 0), 0);
15402
+ if (totalSectionMins > 0 && (totalSectionMins < 40 || totalSectionMins > 180)) {
15403
+ score -= 10;
15404
+ findings.push({
15405
+ id: "drift_unrealistic_lesson_duration",
15406
+ dimension: "CROSS_ARTIFACT_ZERO_DRIFT",
15407
+ severity: "MINOR",
15408
+ title: `Unrealistic Lesson Flow Total Duration (${totalSectionMins} mins)`,
15409
+ description: `Sum of 5E section durations is ${totalSectionMins} minutes. Standard K-12/College lessons span 45-120 minutes.`,
15410
+ remediationAdvice: "Adjust individual section timings so total duration matches standard classroom blocks (e.g. 60m or 90m)."
15411
+ });
15412
+ } else if (totalSectionMins > 0) {
15413
+ strengths.push(`Lesson section timings sum up to a realistic classroom block (${totalSectionMins} mins).`);
15414
+ }
15415
+ if (score >= 90) {
15416
+ strengths.push("Zero drift verified: IDs, language policies, and pedagogical contracts are strictly aligned across all artifacts.");
15417
+ }
15418
+ score = Math.max(0, Math.min(100, score));
15419
+ return {
15420
+ score,
15421
+ weight: 0.1,
15422
+ passed: score >= 75 && !findings.some((f) => f.severity === "CRITICAL"),
15423
+ strengths,
15424
+ findings
15425
+ };
15426
+ }
15427
+ };
15428
+
15429
+ // src/evaluators/constructiveAlignmentEvaluator.ts
15430
+ var ConstructiveAlignmentEvaluator = class {
15431
+ /**
15432
+ * Evaluates constructive alignment within a LessonPlan and across its satellite artifacts.
15433
+ */
15434
+ static evaluateLesson(lesson, quiz, activity) {
15435
+ const findings = [];
15436
+ const strengths = [];
15437
+ let score = 100;
15438
+ const los = lesson.learningObjectives || [];
15439
+ const sections = lesson.sections || [];
15440
+ const exitTicket = lesson.exitTicket;
15441
+ if (los.length === 0) {
15442
+ return {
15443
+ score: 0,
15444
+ weight: 0.2,
15445
+ passed: false,
15446
+ strengths: [],
15447
+ findings: [
15448
+ {
15449
+ id: "align_no_los",
15450
+ dimension: "CONSTRUCTIVE_ALIGNMENT",
15451
+ severity: "CRITICAL",
15452
+ title: "No Learning Objectives Defined",
15453
+ description: "Constructive alignment cannot be established without baseline LOs.",
15454
+ remediationAdvice: "Define at least 2 measurable Learning Objectives."
15455
+ }
15456
+ ]
15457
+ };
15458
+ }
15459
+ const combinedSectionText = sections.map((s) => `${s.title} ${s.teacherActions} ${s.studentActions} ${(s.analogies || []).join(" ")}`).join(" ").toLowerCase();
15460
+ for (const lo of los) {
15461
+ const loKeywords = (lo.name || lo.description || "").toLowerCase().split(/\s+/).filter((w) => w.length > 4);
15462
+ const hasCoverage = loKeywords.some((k) => combinedSectionText.includes(k));
15463
+ if (!hasCoverage && loKeywords.length > 0) {
15464
+ score -= 15;
15465
+ findings.push({
15466
+ id: `align_uncovered_lo_${lo.code}`,
15467
+ dimension: "CONSTRUCTIVE_ALIGNMENT",
15468
+ severity: "MAJOR",
15469
+ title: `Untaught Objective in Lesson Flow: "${lo.code}"`,
15470
+ description: `The LO "${lo.name || lo.code}" is declared in the objectives table but receives minimal coverage in the 5E lesson sections.`,
15471
+ remediationAdvice: `Add explicit Teacher Moves and Student Actions in the Explore/Explain sections addressing "${lo.name}".`,
15472
+ affectedElement: lo.code
15473
+ });
15474
+ }
15475
+ }
15476
+ if (!exitTicket || !exitTicket.questionStem || exitTicket.questionStem.trim().length < 15) {
15477
+ score -= 15;
15478
+ findings.push({
15479
+ id: "align_missing_exit_ticket",
15480
+ dimension: "CONSTRUCTIVE_ALIGNMENT",
15481
+ severity: "MAJOR",
15482
+ title: "Missing or Shallow Exit Ticket",
15483
+ description: "The lesson ends without a rigorous formative Exit Ticket to measure LO attainment before class dismissal.",
15484
+ remediationAdvice: "Include an Exit Ticket question matching the primary LO + a metacognitive reflection prompt."
15485
+ });
15486
+ } else {
15487
+ strengths.push("Formative Exit Ticket is properly anchored at the conclusion of the lesson.");
15488
+ }
15489
+ if (quiz) {
15490
+ const quizQuestions = quiz.questions || [];
15491
+ if (quizQuestions.length > 0) {
15492
+ const quizText = quizQuestions.map((q) => `${q.scenarioOrStem} ${(q.options || []).map((o) => o.text).join(" ")}`).join(" ").toLowerCase();
15493
+ const lessonTopicKeywords = (lesson.topic || lesson.title || "").toLowerCase().split(/\s+/).filter((w) => w.length > 3);
15494
+ const hasTopicMatch = lessonTopicKeywords.some((k) => quizText.includes(k));
15495
+ if (!hasTopicMatch && lessonTopicKeywords.length > 0) {
15712
15496
  score -= 20;
15713
15497
  findings.push({
15714
- id: `struct_quiz_key_count_${qId}`,
15715
- dimension: "MISCONCEPTION_RIGOR",
15498
+ id: "align_quiz_topic_divergence",
15499
+ dimension: "CONSTRUCTIVE_ALIGNMENT",
15716
15500
  severity: "CRITICAL",
15717
- title: `Key Assignment Error in ${qId}`,
15718
- description: `Question ${qId} has ${correctCount} correct options (must be exactly 1).`,
15719
- remediationAdvice: "Set `isCorrect: true` on exactly 1 option.",
15720
- affectedElement: qId
15501
+ title: "Quiz Topic Divergence from Lesson",
15502
+ description: `Quiz questions do not reflect the main topic "${lesson.topic}" of the master lesson.`,
15503
+ remediationAdvice: "Re-align quiz questions strictly to the core concepts taught in the lesson."
15721
15504
  });
15505
+ } else {
15506
+ strengths.push("Diagnostic Quiz questions tightly reflect the lesson topic and concepts.");
15722
15507
  }
15723
15508
  }
15724
15509
  }
15725
- if (activity?.materialsBOM?.hardware && activity.materialsBOM.hardware.length > 0) {
15726
- const hwText = activity.materialsBOM.hardware.join(" ").toLowerCase();
15727
- const hasLED = hwText.includes("led");
15728
- const hasResistor = hwText.includes("\u0111i\u1EC7n tr\u1EDF") || hwText.includes("resistor") || hwText.includes("220") || hwText.includes("330") || hwText.includes("1k");
15729
- if (hasLED && !hasResistor) {
15730
- score -= 20;
15510
+ if (activity) {
15511
+ const actObj = (activity.objective || "").toLowerCase();
15512
+ const lessonTitleLower = (lesson.title || "").toLowerCase();
15513
+ const hasActAlignment = los.some((lo) => actObj.includes((lo.name || "").toLowerCase()) || actObj.includes((lo.description || "").toLowerCase())) || actObj.includes(lessonTitleLower) || lessonTitleLower.split(/\s+/).some((w) => w.length > 4 && actObj.includes(w));
15514
+ if (!hasActAlignment && activity.objective) {
15515
+ score -= 15;
15731
15516
  findings.push({
15732
- id: "struct_hardware_unsafe_led_no_resistor",
15733
- dimension: "TECHNICAL_AUTHENTICITY",
15734
- severity: "CRITICAL",
15735
- title: "Unsafe Circuit BOM: LED without Current-Limiting Resistor",
15736
- description: "Hardware BOM includes LED without a 220\u03A9-1k\u03A9 resistor, causing circuit overload.",
15737
- remediationAdvice: "Add a 220\u03A9 current-limiting resistor to the hardware materials list."
15517
+ id: "align_act_objective_divergence",
15518
+ dimension: "CONSTRUCTIVE_ALIGNMENT",
15519
+ severity: "MAJOR",
15520
+ title: "Activity Objective Disconnected from Lesson Plan",
15521
+ description: `Activity objective "${activity.objective}" does not directly support the lesson LOs.`,
15522
+ remediationAdvice: "Ensure the Activity hands-on lab operationalizes the exact LOs specified in the Master Lesson."
15738
15523
  });
15524
+ } else {
15525
+ strengths.push("Activity lab objective directly operationalizes master lesson learning goals.");
15739
15526
  }
15740
15527
  }
15741
15528
  score = Math.max(0, Math.min(100, score));
15742
- const passed = score >= 80 && !findings.some((f) => f.severity === "CRITICAL");
15743
- if (passed) {
15744
- strengths.push("Deterministic structure, ID contracts, and schema invariants strictly verified.");
15745
- }
15746
15529
  return {
15747
- passed,
15748
- structuralScore: score,
15749
- findings,
15750
- strengths
15530
+ score,
15531
+ weight: 0.2,
15532
+ passed: score >= 75 && !findings.some((f) => f.severity === "CRITICAL"),
15533
+ strengths,
15534
+ findings
15751
15535
  };
15752
15536
  }
15753
15537
  };
15754
15538
 
15755
- // src/evaluators/academicAuditor.ts
15756
- var AcademicAuditor = class {
15539
+ // src/evaluators/fiveEInstructionalEvaluator.ts
15540
+ var FIVE_E_STAGES = [
15541
+ { key: "engage", label: "Engage (Kh\u1EDFi \u0111\u1ED9ng / M\xF3c neo)", regex: /(?:engage|khởi động|hook|mở đầu|anchor)/i },
15542
+ { key: "explore", label: "Explore (Kh\xE1m ph\xE1 / Tr\u1EA3i nghi\u1EC7m)", regex: /(?:explore|khám phá|trải nghiệm|thử nghiệm)/i },
15543
+ { key: "explain", label: "Explain (Gi\u1EA3i th\xEDch / H\xECnh th\xE0nh ki\u1EBFn th\u1EE9c)", regex: /(?:explain|giải thích|khái niệm|kiến thức cốt lõi)/i },
15544
+ { key: "elaborate", label: "Elaborate (V\u1EADn d\u1EE5ng / M\u1EDF r\u1ED9ng)", regex: /(?:elaborate|vận dụng|luyện tập|thực hành|áp dụng)/i },
15545
+ { key: "evaluate", label: "Evaluate (\u0110\xE1nh gi\xE1 / T\u1ED5ng k\u1EBFt)", regex: /(?:evaluate|đánh giá|tổng kết|wrap-up|exit ticket)/i }
15546
+ ];
15547
+ var FiveEInstructionalEvaluator = class {
15757
15548
  /**
15758
- * Evaluates a complete lesson bundle.
15759
- * Step 1 (Deterministic): Fast structural, contract, schema, and safety linting.
15760
- * Step 2 (Semantic LLM-as-a-Judge): Deep pedagogical, cognitive (Bloom), and misconception analysis with live frontier LLM.
15549
+ * Evaluates the pedagogical structure of a Lesson Plan against the 5E Inquiry Model.
15761
15550
  */
15762
- static async auditLessonBundle(input) {
15763
- const { lesson, quiz, activity, slides, codeLab, modelOptions, executeLLMJudge = true } = input;
15764
- const structuralResult = DeterministicStructuralLinter.lintBundle({
15765
- lesson,
15766
- quiz,
15767
- activity,
15768
- slides,
15769
- codeLab
15770
- });
15771
- const allFindings = [...structuralResult.findings];
15772
- const strengths = [...structuralResult.strengths];
15773
- let semanticScore = null;
15774
- let semanticVerdict = "PASS";
15775
- if (executeLLMJudge) {
15776
- try {
15777
- const judgeReport = await auditCurriculumQualityFlow({
15778
- targetArtifactType: "LESSON_BUNDLE",
15779
- lessonId: lesson.lessonId,
15780
- expectedLanguage: lesson.language,
15781
- targetObjectives: (lesson.learningObjectives || []).map((lo) => ({
15782
- code: lo.code,
15783
- description: lo.description,
15784
- bloomLevel: lo.bloomLevel
15785
- })),
15786
- generatedContentJson: JSON.stringify({ lesson, quiz, activity, slides, codeLab }),
15787
- modelOptions
15788
- });
15789
- semanticScore = judgeReport.totalScore;
15790
- semanticVerdict = judgeReport.overallVerdict;
15791
- for (const criterion of judgeReport.criteria) {
15792
- if (!criterion.passed) {
15793
- allFindings.push({
15794
- id: `llm_judge_${criterion.name.toLowerCase().replace(/\s+/g, "_")}`,
15795
- dimension: "CONSTRUCTIVE_ALIGNMENT",
15796
- severity: criterion.score < 50 ? "CRITICAL" : "MAJOR",
15797
- title: `LLM-as-Judge Finding: ${criterion.name}`,
15798
- description: criterion.feedback,
15799
- remediationAdvice: judgeReport.actionableRepairPrompts.join("; ") || "Refine prompt context."
15800
- });
15801
- } else {
15802
- strengths.push(`[LLM-Judge] ${criterion.name}: ${criterion.feedback}`);
15803
- }
15551
+ static evaluateLesson(lesson) {
15552
+ const findings = [];
15553
+ const strengths = [];
15554
+ let score = 100;
15555
+ if (!lesson.hookScenario || lesson.hookScenario.trim().length < 30) {
15556
+ score -= 20;
15557
+ findings.push({
15558
+ id: "5e_weak_hook",
15559
+ dimension: "5E_INSTRUCTIONAL_FIDELITY",
15560
+ severity: "MAJOR",
15561
+ title: "Shallow or Missing Real-World Hook",
15562
+ description: "The lesson lacks a compelling, high-stakes real-world scenario to trigger inquiry.",
15563
+ remediationAdvice: "Frame the lesson around an authentic engineering or domain problem (e.g. server crash, sensor failure, clinical anomaly)."
15564
+ });
15565
+ } else {
15566
+ strengths.push("Engaging real-world hook scenario sets high-stakes context for inquiry.");
15567
+ }
15568
+ if (!lesson.hookQuestions || lesson.hookQuestions.length < 2) {
15569
+ score -= 10;
15570
+ findings.push({
15571
+ id: "5e_insufficient_hook_questions",
15572
+ dimension: "5E_INSTRUCTIONAL_FIDELITY",
15573
+ severity: "MINOR",
15574
+ title: "Insufficient Inquiry Questions in Hook",
15575
+ description: "Need at least 2 open-ended inquiry questions in the Engage phase to activate prior mental models.",
15576
+ remediationAdvice: "Add 2-3 provocative questions challenging common student assumptions."
15577
+ });
15578
+ }
15579
+ const sections = lesson.sections || [];
15580
+ const coveredStages = /* @__PURE__ */ new Set();
15581
+ for (const section of sections) {
15582
+ for (const stage of FIVE_E_STAGES) {
15583
+ if (stage.regex.test(section.title)) {
15584
+ coveredStages.add(stage.key);
15804
15585
  }
15805
- } catch (err) {
15806
- semanticScore = null;
15807
- semanticVerdict = "FAIL";
15808
- allFindings.push({
15809
- id: "llm_judge_connection_error",
15810
- dimension: "CONSTRUCTIVE_ALIGNMENT",
15811
- severity: "MINOR",
15812
- title: "LLM-as-Judge Skipped / Fallback",
15813
- description: `Semantic inference error: ${err.message || String(err)}`,
15814
- remediationAdvice: "Check API credentials for LLM-as-Judge."
15815
- });
15816
15586
  }
15817
15587
  }
15818
- const criticalCount = allFindings.filter((f) => f.severity === "CRITICAL").length;
15819
- const overallScore = executeLLMJudge && semanticScore !== null ? Math.round(structuralResult.structuralScore * 0.4 + semanticScore * 0.6) : structuralResult.structuralScore;
15820
- const passed = structuralResult.passed && criticalCount === 0 && (executeLLMJudge ? semanticVerdict === "PASS" : true);
15821
- let verdict = "REJECTED";
15822
- if (overallScore >= 90 && criticalCount === 0) {
15823
- verdict = "EXEMPLARY";
15824
- } else if (overallScore >= 75 && criticalCount === 0) {
15825
- verdict = "ACADEMICALLY_SOUND";
15826
- } else if (overallScore >= 60) {
15827
- verdict = "NEEDS_PEDAGOGICAL_REFINEMENT";
15588
+ if (lesson.hookScenario) coveredStages.add("engage");
15589
+ if (lesson.exitTicket) coveredStages.add("evaluate");
15590
+ const missingStages = FIVE_E_STAGES.filter((s) => !coveredStages.has(s.key));
15591
+ if (missingStages.length > 0) {
15592
+ score -= missingStages.length * 10;
15593
+ findings.push({
15594
+ id: "5e_missing_phases",
15595
+ dimension: "5E_INSTRUCTIONAL_FIDELITY",
15596
+ severity: missingStages.length > 2 ? "CRITICAL" : "MAJOR",
15597
+ title: `Incomplete 5E Instructional Cycle (Missing ${missingStages.length} phase(s))`,
15598
+ description: `Lesson plan does not clearly demarcate: ${missingStages.map((s) => s.label).join(", ")}.`,
15599
+ remediationAdvice: "Ensure the lesson explicitly walks through Engage -> Explore -> Explain -> Elaborate -> Evaluate."
15600
+ });
15601
+ } else {
15602
+ strengths.push("Full 5E Instructional Cycle (Engage, Explore, Explain, Elaborate, Evaluate) is completely covered.");
15828
15603
  }
15829
- const summary = passed ? `\u2705 Lesson Bundle "${lesson.title}" (${lesson.lessonId}) passes academic & structural verification with score ${overallScore}/100 (${verdict}).` : `\u26A0\uFE0F Lesson Bundle "${lesson.title}" requires revision (${overallScore}/100 - ${verdict}). Found ${allFindings.length} finding(s) with ${criticalCount} critical blocker(s).`;
15830
- const actionablePromptGuidance = allFindings.map(
15831
- (f, idx) => `[${f.dimension}] ${idx + 1}. ${f.title}: ${f.remediationAdvice}`
15832
- );
15833
- const computeDimScore = (dimFindings2) => {
15834
- const hasCritical = dimFindings2.some((f) => f.severity === "CRITICAL");
15835
- const majorCount = dimFindings2.filter((f) => f.severity === "MAJOR").length;
15836
- const minorCount = dimFindings2.filter((f) => f.severity === "MINOR").length;
15837
- let dimScore = 100 - (hasCritical ? 40 : 0) - majorCount * 15 - minorCount * 5;
15838
- dimScore = Math.max(0, Math.min(100, dimScore));
15839
- return { score: dimScore, passed: dimScore >= 75 && !hasCritical };
15840
- };
15841
- const dimFindings = {
15842
- constructiveAlignment: allFindings.filter((f) => f.dimension === "CONSTRUCTIVE_ALIGNMENT"),
15843
- bloomProgression: allFindings.filter((f) => f.dimension === "BLOOM_PROGRESSION"),
15844
- fiveEFidelity: allFindings.filter((f) => f.dimension === "5E_INSTRUCTIONAL_FIDELITY"),
15845
- misconceptionRigor: allFindings.filter((f) => f.dimension === "MISCONCEPTION_RIGOR"),
15846
- technicalAuthenticity: allFindings.filter((f) => f.dimension === "TECHNICAL_AUTHENTICITY")
15847
- };
15848
- const dimScores = Object.fromEntries(
15849
- Object.entries(dimFindings).map(([k, v]) => [k, computeDimScore(v)])
15850
- );
15604
+ let passiveSections = 0;
15605
+ for (let i = 0; i < sections.length; i++) {
15606
+ const s = sections[i];
15607
+ const studentAct = (s.studentActions || "").trim().toLowerCase();
15608
+ if (studentAct.includes("nghe gi\u1EA3ng") || studentAct.includes("ch\xE9p b\xE0i") || studentAct.includes("listen passively") || studentAct.length < 10) {
15609
+ passiveSections++;
15610
+ }
15611
+ }
15612
+ if (passiveSections > 0 && sections.length > 0) {
15613
+ score -= passiveSections * 8;
15614
+ findings.push({
15615
+ id: "5e_passive_student_roles",
15616
+ dimension: "5E_INSTRUCTIONAL_FIDELITY",
15617
+ severity: "MAJOR",
15618
+ title: "Passive Student Roles Detected in Lesson Sections",
15619
+ description: `${passiveSections} section(s) assign passive roles (listening/copying) to students rather than active inquiry, pair-discussion, or hands-on experimentation.`,
15620
+ remediationAdvice: "Transform student actions into active tasks (e.g. Think-Pair-Share, code tracing, hypothesis testing, live bug hunting)."
15621
+ });
15622
+ } else if (sections.length > 0) {
15623
+ strengths.push("Student roles emphasize active learning and hands-on participation throughout.");
15624
+ }
15625
+ score = Math.max(0, Math.min(100, score));
15851
15626
  return {
15852
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
15853
- targetId: lesson.lessonId,
15854
- targetType: "BUNDLE",
15855
- overallScore,
15856
- passed,
15857
- verdict,
15858
- summary,
15859
- dimensionScores: {
15860
- constructiveAlignment: {
15861
- score: dimScores.constructiveAlignment.score,
15862
- weight: 0.2,
15863
- passed: dimScores.constructiveAlignment.passed,
15864
- strengths: dimScores.constructiveAlignment.passed ? ["Constructive alignment verified."] : [],
15865
- findings: dimFindings.constructiveAlignment
15866
- },
15867
- bloomProgression: {
15868
- score: dimScores.bloomProgression.score,
15869
- weight: 0.2,
15870
- passed: dimScores.bloomProgression.passed,
15871
- strengths: dimScores.bloomProgression.passed ? ["Bloom taxonomy progression verified."] : [],
15872
- findings: dimFindings.bloomProgression
15873
- },
15874
- fiveEFidelity: {
15875
- score: dimScores.fiveEFidelity.score,
15876
- weight: 0.15,
15877
- passed: dimScores.fiveEFidelity.passed,
15878
- strengths: dimScores.fiveEFidelity.passed ? ["5E instructional fidelity verified."] : [],
15879
- findings: dimFindings.fiveEFidelity
15880
- },
15881
- misconceptionRigor: {
15882
- score: dimScores.misconceptionRigor.score,
15883
- weight: 0.2,
15884
- passed: dimScores.misconceptionRigor.passed,
15885
- strengths: dimScores.misconceptionRigor.passed ? ["Misconception rigor verified."] : [],
15886
- findings: dimFindings.misconceptionRigor
15887
- },
15888
- technicalAuthenticity: {
15889
- score: dimScores.technicalAuthenticity.score,
15890
- weight: 0.15,
15891
- passed: dimScores.technicalAuthenticity.passed,
15892
- strengths: dimScores.technicalAuthenticity.passed ? ["Technical authenticity verified."] : [],
15893
- findings: dimFindings.technicalAuthenticity
15894
- },
15895
- crossArtifactZeroDrift: {
15896
- score: structuralResult.structuralScore,
15897
- weight: 0.1,
15898
- passed: structuralResult.passed,
15899
- strengths: structuralResult.passed ? ["Cross-artifact zero drift verified."] : [],
15900
- findings: allFindings.filter((f) => f.dimension === "CROSS_ARTIFACT_ZERO_DRIFT")
15901
- }
15902
- },
15903
- criticalFindingsCount: criticalCount,
15904
- allFindings,
15905
- actionablePromptGuidance
15627
+ score,
15628
+ weight: 0.15,
15629
+ passed: score >= 75 && !findings.some((f) => f.severity === "CRITICAL"),
15630
+ strengths,
15631
+ findings
15906
15632
  };
15907
15633
  }
15908
15634
  };
15909
15635
 
15910
- // src/evaluators/bloomTaxonomyEvaluator.ts
15911
- var BLOOM_ACTION_VERBS = {
15912
- remember: [
15913
- "list",
15914
- "define",
15915
- "recall",
15916
- "state",
15917
- "name",
15918
- "identify",
15919
- "label",
15920
- "recognize",
15921
- "li\u1EC7t k\xEA",
15922
- "\u0111\u1ECBnh ngh\u0129a",
15923
- "g\u1ECDi t\xEAn",
15924
- "nh\u1EADn di\u1EC7n",
15925
- "ch\u1EC9 ra",
15926
- "nh\u1EAFc l\u1EA1i",
15927
- "ghi nh\u1EDB"
15928
- ],
15929
- understand: [
15930
- "explain",
15931
- "describe",
15932
- "summarize",
15933
- "classify",
15934
- "interpret",
15935
- "predict",
15936
- "trace",
15937
- "paraphrase",
15938
- "gi\u1EA3i th\xEDch",
15939
- "m\xF4 t\u1EA3",
15940
- "t\xF3m t\u1EAFt",
15941
- "ph\xE2n lo\u1EA1i",
15942
- "di\u1EC5n gi\u1EA3i",
15943
- "d\u1EF1 \u0111o\xE1n",
15944
- "l\u1EA7n theo",
15945
- "hi\u1EC3u"
15946
- ],
15947
- apply: [
15948
- "implement",
15949
- "execute",
15950
- "calculate",
15951
- "solve",
15952
- "construct",
15953
- "debug",
15954
- "modify",
15955
- "build",
15956
- "\xE1p d\u1EE5ng",
15957
- "th\u1EF1c thi",
15958
- "t\xEDnh to\xE1n",
15959
- "gi\u1EA3i quy\u1EBFt",
15960
- "x\xE2y d\u1EF1ng",
15961
- "s\u1EEDa l\u1ED7i",
15962
- "l\u1EAFp \u0111\u1EB7t",
15963
- "vi\u1EBFt m\xE3",
15964
- "l\u1EADp tr\xECnh"
15965
- ],
15966
- analyze: [
15967
- "compare",
15968
- "contrast",
15969
- "decompose",
15970
- "differentiate",
15971
- "troubleshoot",
15972
- "diagnose",
15973
- "deconstruct",
15974
- "so s\xE1nh",
15975
- "\u0111\u1ED1i chi\u1EBFu",
15976
- "ph\xE2n t\xEDch",
15977
- "ph\xE2n r\xE3",
15978
- "ch\u1EA9n \u0111o\xE1n",
15979
- "t\xECm nguy\xEAn nh\xE2n g\u1ED1c",
15980
- "b\xF3c t\xE1ch"
15981
- ],
15982
- evaluate: [
15983
- "justify",
15984
- "critique",
15985
- "assess",
15986
- "defend",
15987
- "argue",
15988
- "benchmark",
15989
- "prioritize",
15990
- "\u0111\xE1nh gi\xE1",
15991
- "bi\u1EC7n minh",
15992
- "ph\xEA ph\xE1n",
15993
- "th\u1EA9m \u0111\u1ECBnh",
15994
- "b\u1EA3o v\u1EC7 quan \u0111i\u1EC3m",
15995
- "l\u1EF1a ch\u1ECDn t\u1ED1i \u01B0u"
15996
- ],
15997
- create: [
15998
- "design",
15999
- "synthesize",
16000
- "architect",
16001
- "formulate",
16002
- "invent",
16003
- "devise",
16004
- "author",
16005
- "thi\u1EBFt k\u1EBF",
16006
- "t\u1ED5ng h\u1EE3p",
16007
- "s\xE1ng t\u1EA1o",
16008
- "ki\u1EBFn tr\xFAc",
16009
- "ph\xE1t minh",
16010
- "ho\xE0n thi\u1EC7n \u0111\u1ED3 \xE1n"
16011
- ]
16012
- };
16013
- var RECALL_PATTERNS = [
16014
- /^(?:chức năng chính của|định nghĩa của|cú pháp của|lệnh nào là|what is the definition of|which keyword|what does .* stand for)/i,
16015
- /(?:là gì\?|được gọi là gì\?|có ý nghĩa gì\?)/i
15636
+ // src/evaluators/codeHardwareFeasibilityEvaluator.ts
15637
+ var VALID_MERMAID_STARTERS = [
15638
+ "graph",
15639
+ "flowchart",
15640
+ "sequencediagram",
15641
+ "statediagram",
15642
+ "classdiagram",
15643
+ "erdiagram",
15644
+ "gantt",
15645
+ "gitgraph"
16016
15646
  ];
16017
- var BloomTaxonomyEvaluator = class {
15647
+ var CodeHardwareFeasibilityEvaluator = class {
16018
15648
  /**
16019
- * Audits a LessonPlan for Bloom taxonomy fidelity and cognitive scaffolding.
15649
+ * Audits technical accuracy, code syntax sanity, and hardware circuit safety.
16020
15650
  */
16021
- static evaluateLesson(lesson) {
15651
+ static evaluateTechnicalFeasibility(lesson, codeLab, activity) {
16022
15652
  const findings = [];
16023
15653
  const strengths = [];
16024
15654
  let score = 100;
16025
- const los = lesson.learningObjectives || [];
16026
- if (los.length === 0) {
16027
- return {
16028
- score: 0,
16029
- weight: 0.2,
16030
- passed: false,
16031
- strengths: [],
16032
- findings: [
16033
- {
16034
- id: "bloom_missing_los",
16035
- dimension: "BLOOM_PROGRESSION",
16036
- severity: "CRITICAL",
16037
- title: "Missing Learning Objectives",
16038
- description: "The lesson plan contains zero declared Learning Objectives.",
16039
- remediationAdvice: "Add 2-4 clearly articulated LOs with Bloom levels and observable success criteria."
16040
- }
16041
- ]
16042
- };
16043
- }
16044
- for (const lo of los) {
16045
- const declaredLevel = (lo.bloomLevel || "").toLowerCase();
16046
- const text = `${lo.name || ""} ${lo.description || ""} ${lo.successCriteria || ""}`.toLowerCase();
16047
- const isRecallPattern = RECALL_PATTERNS.some((p) => p.test(text));
16048
- if (isRecallPattern && (declaredLevel === "apply" || declaredLevel === "analyze" || declaredLevel === "evaluate")) {
16049
- score -= 15;
15655
+ if (lesson?.guidedPractice) {
15656
+ const { codeSnippet, codeLanguage, mermaidDiagram } = lesson.guidedPractice;
15657
+ if (!codeSnippet || codeSnippet.trim().length < 15) {
15658
+ score -= 20;
16050
15659
  findings.push({
16051
- id: `bloom_inflation_${lo.code}`,
16052
- dimension: "BLOOM_PROGRESSION",
15660
+ id: "tech_empty_guided_code",
15661
+ dimension: "TECHNICAL_AUTHENTICITY",
16053
15662
  severity: "MAJOR",
16054
- title: `Bloom Level Inflation in LO "${lo.code}"`,
16055
- description: `LO is tagged as "${lo.bloomLevel}" but its phrasing reflects low-level Recall ("${lo.description}").`,
16056
- remediationAdvice: `Rewrite the objective using authentic "${declaredLevel}" active verbs (e.g. build, debug, compare, diagnose) with an explicit application context.`,
16057
- affectedElement: lo.code
15663
+ title: "Empty or Trivial Guided Practice Code",
15664
+ description: "Guided practice lacks runnable code snippet or domain calculation template.",
15665
+ remediationAdvice: "Provide a complete, runnable code example with explanatory line-by-line comments."
16058
15666
  });
15667
+ } else {
15668
+ if (codeLanguage?.toLowerCase() === "arduino" || codeLanguage?.toLowerCase() === "cpp" || codeSnippet.includes("pinMode")) {
15669
+ if (codeSnippet.includes("digitalWrite") && !codeSnippet.includes("pinMode") && !codeSnippet.includes("setup()")) {
15670
+ score -= 15;
15671
+ findings.push({
15672
+ id: "tech_arduino_missing_pinmode",
15673
+ dimension: "TECHNICAL_AUTHENTICITY",
15674
+ severity: "MAJOR",
15675
+ title: "Missing pinMode() Configuration in Arduino Code",
15676
+ description: "Code calls `digitalWrite()` without initializing the pin with `pinMode(pin, OUTPUT)`.",
15677
+ remediationAdvice: "Ensure `setup()` configures pin direction before writing digital states."
15678
+ });
15679
+ }
15680
+ if (codeSnippet.includes("delay(0)") || codeSnippet.includes("delay(-")) {
15681
+ score -= 15;
15682
+ findings.push({
15683
+ id: "tech_arduino_invalid_delay",
15684
+ dimension: "TECHNICAL_AUTHENTICITY",
15685
+ severity: "MAJOR",
15686
+ title: "Invalid delay() Parameter",
15687
+ description: "delay() duration must be a positive integer in milliseconds.",
15688
+ remediationAdvice: "Use realistic delay timings (e.g. 500ms, 1000ms)."
15689
+ });
15690
+ }
15691
+ }
15692
+ strengths.push("Guided practice features runnable code snippet with clear syntax.");
16059
15693
  }
16060
- if (!lo.successCriteria || lo.successCriteria.trim().length < 15) {
16061
- score -= 10;
15694
+ if (mermaidDiagram) {
15695
+ const cleanDiagram = mermaidDiagram.trim().toLowerCase();
15696
+ const isValidStarter = VALID_MERMAID_STARTERS.some((starter) => cleanDiagram.startsWith(starter));
15697
+ if (!isValidStarter) {
15698
+ score -= 15;
15699
+ findings.push({
15700
+ id: "tech_invalid_mermaid_syntax",
15701
+ dimension: "TECHNICAL_AUTHENTICITY",
15702
+ severity: "MAJOR",
15703
+ title: "Invalid Mermaid Diagram Syntax",
15704
+ description: `Mermaid diagram does not start with a valid declaration (e.g. "flowchart TD", "graph TD", "sequenceDiagram"). Got: "${mermaidDiagram.substring(0, 30)}..."`,
15705
+ remediationAdvice: "Format Mermaid diagrams starting with `flowchart TD` or `sequenceDiagram`."
15706
+ });
15707
+ } else {
15708
+ strengths.push("Valid Mermaid architectural diagram included.");
15709
+ }
15710
+ }
15711
+ }
15712
+ if (codeLab) {
15713
+ const starter = codeLab.starterCode?.content || "";
15714
+ const solution = codeLab.solutionCode?.content || "";
15715
+ if (starter.length < 20 || solution.length < 20) {
15716
+ score -= 25;
16062
15717
  findings.push({
16063
- id: `bloom_unmeasurable_criteria_${lo.code}`,
16064
- dimension: "BLOOM_PROGRESSION",
16065
- severity: "MINOR",
16066
- title: `Vague Success Criteria in LO "${lo.code}"`,
16067
- description: `Success criteria "${lo.successCriteria || ""}" is too brief to provide objective student evidence.`,
16068
- remediationAdvice: 'Specify concrete, observable evidence (e.g. "LED blinks with 1s period without circuit shorting").',
16069
- affectedElement: lo.code
15718
+ id: "tech_codelab_incomplete_codes",
15719
+ dimension: "TECHNICAL_AUTHENTICITY",
15720
+ severity: "CRITICAL",
15721
+ title: "Incomplete CodeLab Starter / Solution Code",
15722
+ description: "CodeLab must provide both scaffolding starter code and complete reference solution code.",
15723
+ remediationAdvice: "Populate `starterCode` with TODO markers and `solutionCode` with tested implementation."
16070
15724
  });
16071
15725
  } else {
16072
- strengths.push(`LO "${lo.code}" defines concrete observable student evidence.`);
15726
+ strengths.push("CodeLab provides complete starter skeleton and working solution code.");
16073
15727
  }
16074
- }
16075
- const diff = lesson.differentiation;
16076
- if (diff) {
16077
- if (!diff.bronzeTier || !diff.silverTier || !diff.goldTier) {
15728
+ if (!codeLab.testCases || codeLab.testCases.length === 0) {
16078
15729
  score -= 15;
16079
15730
  findings.push({
16080
- id: "bloom_incomplete_differentiation",
16081
- dimension: "BLOOM_PROGRESSION",
15731
+ id: "tech_codelab_missing_testcases",
15732
+ dimension: "TECHNICAL_AUTHENTICITY",
16082
15733
  severity: "MAJOR",
16083
- title: "Incomplete 3-Tier Scaffolding",
16084
- description: "Differentiation must provide distinct Bronze (Foundation), Silver (Application), and Gold (Extension) challenges.",
16085
- remediationAdvice: "Define all 3 tiers with increasing cognitive demands (Remember/Understand -> Apply -> Analyze/Create)."
15734
+ title: "Missing Automated Verification Test Cases",
15735
+ description: "CodeLab lacks test cases for students to self-verify their implementations.",
15736
+ remediationAdvice: "Add at least 2 concrete test cases with input and expected output assertions."
16086
15737
  });
16087
- } else {
16088
- strengths.push("Complete 3-tier scaffolding (Bronze -> Silver -> Gold) present in Lesson Plan.");
16089
15738
  }
16090
- } else {
16091
- score -= 20;
16092
- findings.push({
16093
- id: "bloom_missing_differentiation",
16094
- dimension: "BLOOM_PROGRESSION",
16095
- severity: "CRITICAL",
16096
- title: "Missing Differentiation Scaffolding",
16097
- description: "Lesson plan lacks differentiation tiers.",
16098
- remediationAdvice: "Provide tiered practice instructions for varied learner paces."
16099
- });
16100
15739
  }
16101
- score = Math.max(0, Math.min(100, score));
16102
- return {
16103
- score,
16104
- weight: 0.2,
16105
- passed: score >= 75 && !findings.some((f) => f.severity === "CRITICAL"),
16106
- strengths,
16107
- findings
16108
- };
16109
- }
16110
- /**
16111
- * Audits a Diagnostic Quiz for true cognitive depth matching declared Bloom levels.
16112
- */
16113
- static evaluateQuiz(quiz) {
16114
- const findings = [];
16115
- const strengths = [];
16116
- let score = 100;
16117
- const questions = quiz.questions || [];
16118
- if (questions.length < 3) {
16119
- score -= 30;
16120
- findings.push({
16121
- id: "bloom_quiz_too_short",
16122
- dimension: "BLOOM_PROGRESSION",
16123
- severity: "MAJOR",
16124
- title: "Insufficient Question Pool",
16125
- description: `Quiz only contains ${questions.length} questions. Minimum diagnostic threshold is 3 questions.`,
16126
- remediationAdvice: "Generate at least 3-5 diagnostic questions covering foundational through analytical depth."
16127
- });
16128
- }
16129
- let understandCount = 0;
16130
- let applyCount = 0;
16131
- let analyzeCount = 0;
16132
- for (let i = 0; i < questions.length; i++) {
16133
- const q = questions[i];
16134
- const qId = q.id || `Q${i + 1}`;
16135
- const declaredBloom = (q.bloomLevel || "").toLowerCase();
16136
- const stem = q.scenarioOrStem || "";
16137
- if (declaredBloom === "understand") understandCount++;
16138
- if (declaredBloom === "apply") applyCount++;
16139
- if (declaredBloom === "analyze" || declaredBloom === "evaluate") analyzeCount++;
16140
- const isRecall = RECALL_PATTERNS.some((p) => p.test(stem));
16141
- if (isRecall && (declaredBloom === "apply" || declaredBloom === "analyze")) {
16142
- score -= 15;
16143
- findings.push({
16144
- id: `bloom_quiz_misclassification_${qId}`,
16145
- dimension: "BLOOM_PROGRESSION",
16146
- severity: "MAJOR",
16147
- title: `Cognitive Level Misclassification in ${qId}`,
16148
- description: `Question stem "${stem.substring(0, 60)}..." is pure Recall/Definition, but is tagged as "${q.bloomLevel}".`,
16149
- remediationAdvice: 'Either re-tag as "understand" or transform the stem into an authentic problem-solving scenario requiring code debugging or design decision.',
16150
- affectedElement: qId
16151
- });
16152
- }
16153
- if ((declaredBloom === "apply" || declaredBloom === "analyze") && !q.codeSnippet && !stem.includes("```") && !stem.includes("m\u1EA1ch")) {
16154
- score -= 10;
16155
- findings.push({
16156
- id: `bloom_quiz_missing_code_context_${qId}`,
16157
- dimension: "BLOOM_PROGRESSION",
16158
- severity: "MINOR",
16159
- title: `Missing Practical Context in High-Bloom Question ${qId}`,
16160
- description: `Question ${qId} tagged as "${q.bloomLevel}" lacks concrete code or circuit context to evaluate hands-on execution.`,
16161
- remediationAdvice: "Include an annotated code snippet or circuit state for students to trace, debug, or evaluate.",
16162
- affectedElement: qId
16163
- });
16164
- }
16165
- }
16166
- if (questions.length > 0 && (understandCount > 0 || applyCount > 0)) {
16167
- strengths.push(`Quiz features multi-level cognitive questions (Understand: ${understandCount}, Apply: ${applyCount}, Analyze: ${analyzeCount}).`);
16168
- }
16169
- score = Math.max(0, Math.min(100, score));
16170
- return {
16171
- score,
16172
- weight: 0.2,
16173
- passed: score >= 75 && !findings.some((f) => f.severity === "CRITICAL"),
16174
- strengths,
16175
- findings
16176
- };
16177
- }
16178
- };
16179
-
16180
- // src/evaluators/crossArtifactDriftEvaluator.ts
16181
- var CrossArtifactDriftEvaluator = class {
16182
- /**
16183
- * Audits consistency, metadata synchronization, and zero-drift across all artifacts in a lesson bundle.
16184
- */
16185
- static evaluateBundle(lesson, quiz, activity, slides) {
16186
- const findings = [];
16187
- const strengths = [];
16188
- let score = 100;
16189
- const baseLessonId = lesson.lessonId;
16190
- const baseLanguage = lesson.language;
16191
- if (quiz && quiz.quizId && quiz.quizId !== baseLessonId && !quiz.quizId.includes(baseLessonId)) {
16192
- score -= 15;
16193
- findings.push({
16194
- id: "drift_quiz_id_mismatch",
16195
- dimension: "CROSS_ARTIFACT_ZERO_DRIFT",
16196
- severity: "MAJOR",
16197
- title: "Quiz ID Mismatch with Master Lesson",
16198
- description: `Quiz ID "${quiz.quizId}" diverges from master Lesson ID "${baseLessonId}".`,
16199
- remediationAdvice: `Align Quiz ID to "${baseLessonId}".`,
16200
- affectedElement: quiz.quizId
16201
- });
16202
- }
16203
- if (activity && activity.lessonId && activity.lessonId !== baseLessonId) {
16204
- score -= 15;
16205
- findings.push({
16206
- id: "drift_act_id_mismatch",
16207
- dimension: "CROSS_ARTIFACT_ZERO_DRIFT",
16208
- severity: "MAJOR",
16209
- title: "Activity Lesson ID Mismatch",
16210
- description: `Activity lessonId "${activity.lessonId}" diverges from master Lesson ID "${baseLessonId}".`,
16211
- remediationAdvice: `Align Activity lessonId to "${baseLessonId}".`,
16212
- affectedElement: activity.lessonId
16213
- });
16214
- }
16215
- if (slides && slides.lessonId && slides.lessonId !== baseLessonId) {
16216
- score -= 15;
16217
- findings.push({
16218
- id: "drift_slides_id_mismatch",
16219
- dimension: "CROSS_ARTIFACT_ZERO_DRIFT",
16220
- severity: "MAJOR",
16221
- title: "Slide Deck Lesson ID Mismatch",
16222
- description: `Slide deck lessonId "${slides.lessonId}" diverges from master Lesson ID "${baseLessonId}".`,
16223
- remediationAdvice: `Align Slide deck lessonId to "${baseLessonId}".`,
16224
- affectedElement: slides.lessonId
16225
- });
16226
- }
16227
- const satellites = [
16228
- { type: "QUIZ", lang: quiz?.language },
16229
- { type: "ACT", lang: activity?.language },
16230
- { type: "SLIDE", lang: slides?.language }
16231
- ];
16232
- for (const sat of satellites) {
16233
- if (sat.lang && sat.lang.toLowerCase() !== baseLanguage.toLowerCase()) {
16234
- score -= 25;
15740
+ if (activity?.materialsBOM?.hardware && activity.materialsBOM.hardware.length > 0) {
15741
+ const hwText = activity.materialsBOM.hardware.join(" ").toLowerCase();
15742
+ const hasLED = hwText.includes("led");
15743
+ const hasResistor = hwText.includes("\u0111i\u1EC7n tr\u1EDF") || hwText.includes("resistor") || hwText.includes("220") || hwText.includes("330") || hwText.includes("1k");
15744
+ if (hasLED && !hasResistor) {
15745
+ score -= 20;
16235
15746
  findings.push({
16236
- id: `drift_language_mismatch_${sat.type}`,
16237
- dimension: "CROSS_ARTIFACT_ZERO_DRIFT",
15747
+ id: "tech_hardware_unsafe_led_no_resistor",
15748
+ dimension: "TECHNICAL_AUTHENTICITY",
16238
15749
  severity: "CRITICAL",
16239
- title: `Language Contamination in ${sat.type}`,
16240
- description: `Master Lesson is in "${baseLanguage}" but ${sat.type} is declared in "${sat.lang}".`,
16241
- remediationAdvice: `Regenerate ${sat.type} strictly in "${baseLanguage}".`
15750
+ title: "Dangerous Hardware Circuit: LED without Current-Limiting Resistor",
15751
+ description: "Activity specifies an LED on breadboard/microcontroller without a 220\u03A9-1k\u03A9 current-limiting resistor, which causes electrical overload and burnout.",
15752
+ remediationAdvice: "Add a 220\u03A9 or 330\u03A9 current-limiting resistor to the hardware BOM."
16242
15753
  });
15754
+ } else if (hasLED && hasResistor) {
15755
+ strengths.push("Hardware BOM safely pairs LED with current-limiting resistor protection.");
16243
15756
  }
16244
15757
  }
16245
- const sections = lesson.sections || [];
16246
- const totalSectionMins = sections.reduce((sum, s) => sum + (s.durationMinutes || 0), 0);
16247
- if (totalSectionMins > 0 && (totalSectionMins < 40 || totalSectionMins > 180)) {
16248
- score -= 10;
16249
- findings.push({
16250
- id: "drift_unrealistic_lesson_duration",
16251
- dimension: "CROSS_ARTIFACT_ZERO_DRIFT",
16252
- severity: "MINOR",
16253
- title: `Unrealistic Lesson Flow Total Duration (${totalSectionMins} mins)`,
16254
- description: `Sum of 5E section durations is ${totalSectionMins} minutes. Standard K-12/College lessons span 45-120 minutes.`,
16255
- remediationAdvice: "Adjust individual section timings so total duration matches standard classroom blocks (e.g. 60m or 90m)."
16256
- });
16257
- } else if (totalSectionMins > 0) {
16258
- strengths.push(`Lesson section timings sum up to a realistic classroom block (${totalSectionMins} mins).`);
16259
- }
16260
- if (score >= 90) {
16261
- strengths.push("Zero drift verified: IDs, language policies, and pedagogical contracts are strictly aligned across all artifacts.");
16262
- }
16263
15758
  score = Math.max(0, Math.min(100, score));
16264
15759
  return {
16265
15760
  score,
16266
- weight: 0.1,
15761
+ weight: 0.15,
16267
15762
  passed: score >= 75 && !findings.some((f) => f.severity === "CRITICAL"),
16268
15763
  strengths,
16269
15764
  findings
@@ -16271,19 +15766,22 @@ var CrossArtifactDriftEvaluator = class {
16271
15766
  }
16272
15767
  };
16273
15768
 
16274
- // src/evaluators/constructiveAlignmentEvaluator.ts
16275
- var ConstructiveAlignmentEvaluator = class {
15769
+ // src/evaluators/misconceptionEvaluator.ts
15770
+ var LAZY_DISTRACTOR_PATTERNS = [
15771
+ /^(?:tất cả các đáp án trên đều (?:đúng|sai)|cả a,?\s*b,?\s*c đều (?:đúng|sai)|all of the above|none of the above)[\.\?!]?$/i,
15772
+ /^(?:không có đáp án nào đúng|không có chức năng|không làm gì cả|không ảnh hưởng)[\.\?!]?$/i,
15773
+ /^(?:đáp án khác|other)[\.\?!]?$/i
15774
+ ];
15775
+ var MisconceptionEvaluator = class {
16276
15776
  /**
16277
- * Evaluates constructive alignment within a LessonPlan and across its satellite artifacts.
15777
+ * Audits the psychometric and pedagogical rigor of diagnostic questions and their distractors.
16278
15778
  */
16279
- static evaluateLesson(lesson, quiz, activity) {
15779
+ static evaluateQuiz(quiz) {
16280
15780
  const findings = [];
16281
15781
  const strengths = [];
16282
15782
  let score = 100;
16283
- const los = lesson.learningObjectives || [];
16284
- const sections = lesson.sections || [];
16285
- const exitTicket = lesson.exitTicket;
16286
- if (los.length === 0) {
15783
+ const questions = quiz.questions || [];
15784
+ if (questions.length === 0) {
16287
15785
  return {
16288
15786
  score: 0,
16289
15787
  weight: 0.2,
@@ -16291,85 +15789,84 @@ var ConstructiveAlignmentEvaluator = class {
16291
15789
  strengths: [],
16292
15790
  findings: [
16293
15791
  {
16294
- id: "align_no_los",
16295
- dimension: "CONSTRUCTIVE_ALIGNMENT",
15792
+ id: "misconception_no_questions",
15793
+ dimension: "MISCONCEPTION_RIGOR",
16296
15794
  severity: "CRITICAL",
16297
- title: "No Learning Objectives Defined",
16298
- description: "Constructive alignment cannot be established without baseline LOs.",
16299
- remediationAdvice: "Define at least 2 measurable Learning Objectives."
15795
+ title: "Empty Question Bank",
15796
+ description: "No questions provided in quiz artifact.",
15797
+ remediationAdvice: "Generate diagnostic questions with deliberate misconception traps."
16300
15798
  }
16301
15799
  ]
16302
15800
  };
16303
15801
  }
16304
- const combinedSectionText = sections.map((s) => `${s.title} ${s.teacherActions} ${s.studentActions} ${(s.analogies || []).join(" ")}`).join(" ").toLowerCase();
16305
- for (const lo of los) {
16306
- const loKeywords = (lo.name || lo.description || "").toLowerCase().split(/\s+/).filter((w) => w.length > 4);
16307
- const hasCoverage = loKeywords.some((k) => combinedSectionText.includes(k));
16308
- if (!hasCoverage && loKeywords.length > 0) {
15802
+ let questionsWithFullExplanations = 0;
15803
+ for (let i = 0; i < questions.length; i++) {
15804
+ const q = questions[i];
15805
+ const qId = q.id || `Q${i + 1}`;
15806
+ const options = q.options || [];
15807
+ if (options.length < 4) {
16309
15808
  score -= 15;
16310
15809
  findings.push({
16311
- id: `align_uncovered_lo_${lo.code}`,
16312
- dimension: "CONSTRUCTIVE_ALIGNMENT",
15810
+ id: `misconception_few_options_${qId}`,
15811
+ dimension: "MISCONCEPTION_RIGOR",
16313
15812
  severity: "MAJOR",
16314
- title: `Untaught Objective in Lesson Flow: "${lo.code}"`,
16315
- description: `The LO "${lo.name || lo.code}" is declared in the objectives table but receives minimal coverage in the 5E lesson sections.`,
16316
- remediationAdvice: `Add explicit Teacher Moves and Student Actions in the Explore/Explain sections addressing "${lo.name}".`,
16317
- affectedElement: lo.code
15813
+ title: `Insufficient Distractors in ${qId}`,
15814
+ description: `Question ${qId} has only ${options.length} options. Standard diagnostic rigor requires 4 plausible choices (1 key + 3 diagnostic distractors).`,
15815
+ remediationAdvice: "Provide 4 full options (A, B, C, D) representing distinct cognitive states.",
15816
+ affectedElement: qId
16318
15817
  });
16319
15818
  }
16320
- }
16321
- if (!exitTicket || !exitTicket.questionStem || exitTicket.questionStem.trim().length < 15) {
16322
- score -= 15;
16323
- findings.push({
16324
- id: "align_missing_exit_ticket",
16325
- dimension: "CONSTRUCTIVE_ALIGNMENT",
16326
- severity: "MAJOR",
16327
- title: "Missing or Shallow Exit Ticket",
16328
- description: "The lesson ends without a rigorous formative Exit Ticket to measure LO attainment before class dismissal.",
16329
- remediationAdvice: "Include an Exit Ticket question matching the primary LO + a metacognitive reflection prompt."
16330
- });
16331
- } else {
16332
- strengths.push("Formative Exit Ticket is properly anchored at the conclusion of the lesson.");
16333
- }
16334
- if (quiz) {
16335
- const quizQuestions = quiz.questions || [];
16336
- if (quizQuestions.length > 0) {
16337
- const quizText = quizQuestions.map((q) => `${q.scenarioOrStem} ${(q.options || []).map((o) => o.text).join(" ")}`).join(" ").toLowerCase();
16338
- const lessonTopicKeywords = (lesson.topic || lesson.title || "").toLowerCase().split(/\s+/).filter((w) => w.length > 3);
16339
- const hasTopicMatch = lessonTopicKeywords.some((k) => quizText.includes(k));
16340
- if (!hasTopicMatch && lessonTopicKeywords.length > 0) {
16341
- score -= 20;
16342
- findings.push({
16343
- id: "align_quiz_topic_divergence",
16344
- dimension: "CONSTRUCTIVE_ALIGNMENT",
16345
- severity: "CRITICAL",
16346
- title: "Quiz Topic Divergence from Lesson",
16347
- description: `Quiz questions do not reflect the main topic "${lesson.topic}" of the master lesson.`,
16348
- remediationAdvice: "Re-align quiz questions strictly to the core concepts taught in the lesson."
16349
- });
16350
- } else {
16351
- strengths.push("Diagnostic Quiz questions tightly reflect the lesson topic and concepts.");
16352
- }
16353
- }
16354
- }
16355
- if (activity) {
16356
- const actObj = (activity.objective || "").toLowerCase();
16357
- const lessonTitleLower = (lesson.title || "").toLowerCase();
16358
- const hasActAlignment = los.some((lo) => actObj.includes((lo.name || "").toLowerCase()) || actObj.includes((lo.description || "").toLowerCase())) || actObj.includes(lessonTitleLower) || lessonTitleLower.split(/\s+/).some((w) => w.length > 4 && actObj.includes(w));
16359
- if (!hasActAlignment && activity.objective) {
16360
- score -= 15;
15819
+ const correctCount = options.filter((o) => o.isCorrect).length;
15820
+ if (correctCount !== 1) {
15821
+ score -= 25;
16361
15822
  findings.push({
16362
- id: "align_act_objective_divergence",
16363
- dimension: "CONSTRUCTIVE_ALIGNMENT",
16364
- severity: "MAJOR",
16365
- title: "Activity Objective Disconnected from Lesson Plan",
16366
- description: `Activity objective "${activity.objective}" does not directly support the lesson LOs.`,
16367
- remediationAdvice: "Ensure the Activity hands-on lab operationalizes the exact LOs specified in the Master Lesson."
15823
+ id: `misconception_invalid_correct_count_${qId}`,
15824
+ dimension: "MISCONCEPTION_RIGOR",
15825
+ severity: "CRITICAL",
15826
+ title: `Key Assignment Error in ${qId}`,
15827
+ description: `Question ${qId} has ${correctCount} correct options (must have exactly 1 true answer).`,
15828
+ remediationAdvice: "Set `isCorrect: true` on exactly one option and `isCorrect: false` on all distractors.",
15829
+ affectedElement: qId
15830
+ });
15831
+ }
15832
+ let missingExplanation = false;
15833
+ for (const opt of options) {
15834
+ const text = (opt.text || "").trim();
15835
+ const explanation = (opt.explanation || "").trim();
15836
+ if (LAZY_DISTRACTOR_PATTERNS.some((p) => p.test(text))) {
15837
+ score -= 10;
15838
+ findings.push({
15839
+ id: `misconception_lazy_distractor_${qId}_${opt.id}`,
15840
+ dimension: "MISCONCEPTION_RIGOR",
15841
+ severity: "MAJOR",
15842
+ title: `Low-Utility Distractor in ${qId} (${opt.id})`,
15843
+ description: `Option "${text}" is a generic/throwaway distractor ("All/None of the above" or "No effect") that does not diagnose student cognitive models.`,
15844
+ remediationAdvice: "Replace with an authentic student misconception (e.g. inverted logic, missing pullup, off-by-one boundary, unit confusion).",
15845
+ affectedElement: `${qId}.${opt.id}`
15846
+ });
15847
+ }
15848
+ if (!explanation || explanation.length < 20) {
15849
+ missingExplanation = true;
15850
+ }
15851
+ }
15852
+ if (missingExplanation) {
15853
+ score -= 10;
15854
+ findings.push({
15855
+ id: `misconception_shallow_explanation_${qId}`,
15856
+ dimension: "MISCONCEPTION_RIGOR",
15857
+ severity: "MAJOR",
15858
+ title: `Shallow Distractor Explanations in ${qId}`,
15859
+ description: `Question ${qId} lacks detailed pedagogical explanations for all options. Students and teachers cannot diagnose root causes without option-level rationale.`,
15860
+ remediationAdvice: "For EVERY option (A, B, C, D), explicitly write why the choice is correct or what mental misconception it represents.",
15861
+ affectedElement: qId
16368
15862
  });
16369
15863
  } else {
16370
- strengths.push("Activity lab objective directly operationalizes master lesson learning goals.");
15864
+ questionsWithFullExplanations++;
16371
15865
  }
16372
15866
  }
15867
+ if (questionsWithFullExplanations === questions.length && questions.length >= 3) {
15868
+ strengths.push("All quiz questions feature rigorous 4-option breakdown with comprehensive misconception analysis.");
15869
+ }
16373
15870
  score = Math.max(0, Math.min(100, score));
16374
15871
  return {
16375
15872
  score,
@@ -16381,345 +15878,287 @@ var ConstructiveAlignmentEvaluator = class {
16381
15878
  }
16382
15879
  };
16383
15880
 
16384
- // src/evaluators/fiveEInstructionalEvaluator.ts
16385
- var FIVE_E_STAGES = [
16386
- { key: "engage", label: "Engage (Kh\u1EDFi \u0111\u1ED9ng / M\xF3c neo)", regex: /(?:engage|khởi động|hook|mở đầu|anchor)/i },
16387
- { key: "explore", label: "Explore (Kh\xE1m ph\xE1 / Tr\u1EA3i nghi\u1EC7m)", regex: /(?:explore|khám phá|trải nghiệm|thử nghiệm)/i },
16388
- { key: "explain", label: "Explain (Gi\u1EA3i th\xEDch / H\xECnh th\xE0nh ki\u1EBFn th\u1EE9c)", regex: /(?:explain|giải thích|khái niệm|kiến thức cốt lõi)/i },
16389
- { key: "elaborate", label: "Elaborate (V\u1EADn d\u1EE5ng / M\u1EDF r\u1ED9ng)", regex: /(?:elaborate|vận dụng|luyện tập|thực hành|áp dụng)/i },
16390
- { key: "evaluate", label: "Evaluate (\u0110\xE1nh gi\xE1 / T\u1ED5ng k\u1EBFt)", regex: /(?:evaluate|đánh giá|tổng kết|wrap-up|exit ticket)/i }
16391
- ];
16392
- var FiveEInstructionalEvaluator = class {
16393
- /**
16394
- * Evaluates the pedagogical structure of a Lesson Plan against the 5E Inquiry Model.
16395
- */
16396
- static evaluateLesson(lesson) {
16397
- const findings = [];
16398
- const strengths = [];
16399
- let score = 100;
16400
- if (!lesson.hookScenario || lesson.hookScenario.trim().length < 30) {
16401
- score -= 20;
16402
- findings.push({
16403
- id: "5e_weak_hook",
16404
- dimension: "5E_INSTRUCTIONAL_FIDELITY",
16405
- severity: "MAJOR",
16406
- title: "Shallow or Missing Real-World Hook",
16407
- description: "The lesson lacks a compelling, high-stakes real-world scenario to trigger inquiry.",
16408
- remediationAdvice: "Frame the lesson around an authentic engineering or domain problem (e.g. server crash, sensor failure, clinical anomaly)."
16409
- });
16410
- } else {
16411
- strengths.push("Engaging real-world hook scenario sets high-stakes context for inquiry.");
15881
+ // src/standards/standardsCoverageGate.ts
15882
+ function resolveStatementRef(ref, packs) {
15883
+ const [head, ...rest] = ref.split(":");
15884
+ const candidatePacks = rest.length > 0 ? packs.filter((p) => p.manifest.id === head) : packs;
15885
+ const statementId = rest.length > 0 ? rest.join(":") : ref;
15886
+ for (const p of candidatePacks) {
15887
+ if (p.statements.some((s) => s.id === statementId)) return { pack: p, statementId };
15888
+ }
15889
+ return null;
15890
+ }
15891
+ function evaluateStandardsCoverage(input) {
15892
+ const rows = [];
15893
+ const aoToLo = /* @__PURE__ */ new Map();
15894
+ for (const ao of input.assessmentObjectives ?? []) aoToLo.set(ao.aoCode, ao.alignedLO);
15895
+ const loToRefs = /* @__PURE__ */ new Map();
15896
+ for (const lo of input.objectives) {
15897
+ loToRefs.set(lo.code, new Set(lo.standardRefs ?? []));
15898
+ }
15899
+ const taughtLOs = /* @__PURE__ */ new Set();
15900
+ for (const act of input.activities ?? []) for (const lo of act.lo) taughtLOs.add(lo);
15901
+ const assessedLOs = /* @__PURE__ */ new Set();
15902
+ for (const q of input.quizQuestions) {
15903
+ if (q.alignedLO) assessedLOs.add(q.alignedLO);
15904
+ if (q.alignedAO) {
15905
+ const lo = aoToLo.get(q.alignedAO);
15906
+ if (lo) assessedLOs.add(lo);
16412
15907
  }
16413
- if (!lesson.hookQuestions || lesson.hookQuestions.length < 2) {
16414
- score -= 10;
16415
- findings.push({
16416
- id: "5e_insufficient_hook_questions",
16417
- dimension: "5E_INSTRUCTIONAL_FIDELITY",
16418
- severity: "MINOR",
16419
- title: "Insufficient Inquiry Questions in Hook",
16420
- description: "Need at least 2 open-ended inquiry questions in the Engage phase to activate prior mental models.",
16421
- remediationAdvice: "Add 2-3 provocative questions challenging common student assumptions."
16422
- });
15908
+ }
15909
+ for (const pack of input.packs) {
15910
+ const mappingByStatement = /* @__PURE__ */ new Map();
15911
+ for (const m of pack.mappings ?? []) {
15912
+ const prev = mappingByStatement.get(m.statementId);
15913
+ if (!prev || prev !== "covers" && m.kind === "covers" || prev === "extends" && m.kind !== "extends") {
15914
+ mappingByStatement.set(m.statementId, m.kind);
15915
+ }
16423
15916
  }
16424
- const sections = lesson.sections || [];
16425
- const coveredStages = /* @__PURE__ */ new Set();
16426
- for (const section of sections) {
16427
- for (const stage of FIVE_E_STAGES) {
16428
- if (stage.regex.test(section.title)) {
16429
- coveredStages.add(stage.key);
15917
+ for (const statement of pack.statements) {
15918
+ const refFull = `${pack.manifest.id}:${statement.id}`;
15919
+ const issues = [];
15920
+ const los = input.objectives.filter((lo) => (lo.standardRefs ?? []).some((r) => r === statement.id || r === refFull)).map((lo) => lo.code);
15921
+ const kind = mappingByStatement.get(statement.id);
15922
+ const hasMapping = kind !== void 0;
15923
+ const isComplianceRelevant = kind === "covers";
15924
+ const hasActivity = los.some((lo) => taughtLOs.has(lo));
15925
+ const hasAssessment = los.some((lo) => assessedLOs.has(lo));
15926
+ let status;
15927
+ if (!hasMapping) status = "UNMAPPED";
15928
+ else if (!isComplianceRelevant) status = "PARTIAL";
15929
+ else if (los.length > 0 && hasActivity && hasAssessment) status = "COVERED";
15930
+ else status = "UNCOVERED";
15931
+ if (status === "UNCOVERED") {
15932
+ if (los.length === 0) issues.push("No learning objective anchors this statement (missing standardRefs).");
15933
+ else {
15934
+ if (!hasActivity) issues.push(`Anchored LO(s) ${los.join(", ")} have no activity in lesson flow.`);
15935
+ if (!hasAssessment) issues.push(`Anchored LO(s) ${los.join(", ")} are not measured by any quiz question.`);
16430
15936
  }
16431
15937
  }
16432
- }
16433
- if (lesson.hookScenario) coveredStages.add("engage");
16434
- if (lesson.exitTicket) coveredStages.add("evaluate");
16435
- const missingStages = FIVE_E_STAGES.filter((s) => !coveredStages.has(s.key));
16436
- if (missingStages.length > 0) {
16437
- score -= missingStages.length * 10;
16438
- findings.push({
16439
- id: "5e_missing_phases",
16440
- dimension: "5E_INSTRUCTIONAL_FIDELITY",
16441
- severity: missingStages.length > 2 ? "CRITICAL" : "MAJOR",
16442
- title: `Incomplete 5E Instructional Cycle (Missing ${missingStages.length} phase(s))`,
16443
- description: `Lesson plan does not clearly demarcate: ${missingStages.map((s) => s.label).join(", ")}.`,
16444
- remediationAdvice: "Ensure the lesson explicitly walks through Engage -> Explore -> Explain -> Elaborate -> Evaluate."
15938
+ rows.push({
15939
+ packId: pack.manifest.id,
15940
+ statementId: statement.id,
15941
+ statementText: Object.values(statement.texts)[0] ?? "",
15942
+ status,
15943
+ objectives: los,
15944
+ hasActivity,
15945
+ hasAssessment,
15946
+ issues
16445
15947
  });
16446
- } else {
16447
- strengths.push("Full 5E Instructional Cycle (Engage, Explore, Explain, Elaborate, Evaluate) is completely covered.");
16448
15948
  }
16449
- let passiveSections = 0;
16450
- for (let i = 0; i < sections.length; i++) {
16451
- const s = sections[i];
16452
- const studentAct = (s.studentActions || "").trim().toLowerCase();
16453
- if (studentAct.includes("nghe gi\u1EA3ng") || studentAct.includes("ch\xE9p b\xE0i") || studentAct.includes("listen passively") || studentAct.length < 10) {
16454
- passiveSections++;
15949
+ }
15950
+ for (const lo of input.objectives) {
15951
+ for (const r of lo.standardRefs ?? []) {
15952
+ if (!resolveStatementRef(r, input.packs)) {
15953
+ rows.push({
15954
+ packId: "(unresolved)",
15955
+ statementId: r,
15956
+ statementText: "",
15957
+ status: "UNCOVERED",
15958
+ objectives: [lo.code],
15959
+ hasActivity: false,
15960
+ hasAssessment: false,
15961
+ issues: [`standardRef "${r}" does not exist in any adopted pack \u2014 likely a hallucinated or stale ID`]
15962
+ });
16455
15963
  }
16456
15964
  }
16457
- if (passiveSections > 0 && sections.length > 0) {
16458
- score -= passiveSections * 8;
16459
- findings.push({
16460
- id: "5e_passive_student_roles",
16461
- dimension: "5E_INSTRUCTIONAL_FIDELITY",
16462
- severity: "MAJOR",
16463
- title: "Passive Student Roles Detected in Lesson Sections",
16464
- description: `${passiveSections} section(s) assign passive roles (listening/copying) to students rather than active inquiry, pair-discussion, or hands-on experimentation.`,
16465
- remediationAdvice: "Transform student actions into active tasks (e.g. Think-Pair-Share, code tracing, hypothesis testing, live bug hunting)."
16466
- });
16467
- } else if (sections.length > 0) {
16468
- strengths.push("Student roles emphasize active learning and hands-on participation throughout.");
15965
+ }
15966
+ const complianceRows = rows.filter((r) => r.status !== "UNMAPPED" && r.status !== "PARTIAL");
15967
+ const covered = complianceRows.filter((r) => r.status === "COVERED").length;
15968
+ const coveragePct = complianceRows.length === 0 ? 100 : Math.round(covered / complianceRows.length * 100);
15969
+ const unresolvedCount = rows.filter((r) => r.packId === "(unresolved)").length;
15970
+ const verdict = unresolvedCount > 0 || coveragePct < 60 ? "FAIL" : coveragePct < 100 ? "WARN" : "PASS";
15971
+ const lines = [
15972
+ "# Standards Coverage Report",
15973
+ "",
15974
+ `- Verdict: **${verdict}**`,
15975
+ `- Compliance coverage: **${coveragePct}%** (${covered}/${complianceRows.length} "covers" statements fully taught + assessed)`,
15976
+ `- Unresolved standardRefs: ${unresolvedCount}`,
15977
+ "",
15978
+ "| Pack | Statement | Status | LOs | Activity | Assessment |",
15979
+ "|---|---|---|---|---|---|",
15980
+ ...rows.map(
15981
+ (r) => `|${r.packId}|${r.statementId}|${r.status}|${r.objectives.join(", ") || "\u2014"}|${r.hasActivity ? "\u2713" : "\u2717"}|${r.hasAssessment ? "\u2713" : "\u2717"}|`
15982
+ )
15983
+ ];
15984
+ const issueLines = rows.filter((r) => r.issues.length > 0).flatMap((r) => r.issues.map((i) => `- [${r.packId}:${r.statementId}] ${i}`));
15985
+ if (issueLines.length > 0) lines.push("", "## Issues", ...issueLines);
15986
+ return {
15987
+ verdict,
15988
+ coveragePct,
15989
+ rows,
15990
+ summary: `Standards coverage ${coveragePct}% \u2014 verdict ${verdict}`,
15991
+ rawMarkdownReport: lines.join("\n")
15992
+ };
15993
+ }
15994
+ var StandardsRegistryAdapter = class {
15995
+ client;
15996
+ constructor(config = {}) {
15997
+ if (config.client) {
15998
+ this.client = config.client;
15999
+ return;
16469
16000
  }
16470
- score = Math.max(0, Math.min(100, score));
16471
- return {
16472
- score,
16473
- weight: 0.15,
16474
- passed: score >= 75 && !findings.some((f) => f.severity === "CRITICAL"),
16475
- strengths,
16476
- findings
16477
- };
16001
+ const url = config.supabaseUrl || process.env.NEXT_PUBLIC_SUPABASE_URL || process.env.SUPABASE_URL || "";
16002
+ const key = config.supabaseServiceRoleKey || process.env.SUPABASE_SERVICE_ROLE_KEY || config.supabaseAnonKey || process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || "";
16003
+ if (!url || !key) {
16004
+ throw new Error("StandardsRegistryAdapter: Supabase URL/key missing (pass client or env).");
16005
+ }
16006
+ this.client = createClient(url, key);
16478
16007
  }
16479
- };
16480
-
16481
- // src/evaluators/codeHardwareFeasibilityEvaluator.ts
16482
- var VALID_MERMAID_STARTERS = [
16483
- "graph",
16484
- "flowchart",
16485
- "sequencediagram",
16486
- "statediagram",
16487
- "classdiagram",
16488
- "erdiagram",
16489
- "gantt",
16490
- "gitgraph"
16491
- ];
16492
- var CodeHardwareFeasibilityEvaluator = class {
16493
- /**
16494
- * Audits technical accuracy, code syntax sanity, and hardware circuit safety.
16495
- */
16496
- static evaluateTechnicalFeasibility(lesson, codeLab, activity) {
16497
- const findings = [];
16498
- const strengths = [];
16499
- let score = 100;
16500
- if (lesson?.guidedPractice) {
16501
- const { codeSnippet, codeLanguage, mermaidDiagram } = lesson.guidedPractice;
16502
- if (!codeSnippet || codeSnippet.trim().length < 15) {
16503
- score -= 20;
16504
- findings.push({
16505
- id: "tech_empty_guided_code",
16506
- dimension: "TECHNICAL_AUTHENTICITY",
16507
- severity: "MAJOR",
16508
- title: "Empty or Trivial Guided Practice Code",
16509
- description: "Guided practice lacks runnable code snippet or domain calculation template.",
16510
- remediationAdvice: "Provide a complete, runnable code example with explanatory line-by-line comments."
16511
- });
16512
- } else {
16513
- if (codeLanguage?.toLowerCase() === "arduino" || codeLanguage?.toLowerCase() === "cpp" || codeSnippet.includes("pinMode")) {
16514
- if (codeSnippet.includes("digitalWrite") && !codeSnippet.includes("pinMode") && !codeSnippet.includes("setup()")) {
16515
- score -= 15;
16516
- findings.push({
16517
- id: "tech_arduino_missing_pinmode",
16518
- dimension: "TECHNICAL_AUTHENTICITY",
16519
- severity: "MAJOR",
16520
- title: "Missing pinMode() Configuration in Arduino Code",
16521
- description: "Code calls `digitalWrite()` without initializing the pin with `pinMode(pin, OUTPUT)`.",
16522
- remediationAdvice: "Ensure `setup()` configures pin direction before writing digital states."
16523
- });
16524
- }
16525
- if (codeSnippet.includes("delay(0)") || codeSnippet.includes("delay(-")) {
16526
- score -= 15;
16527
- findings.push({
16528
- id: "tech_arduino_invalid_delay",
16529
- dimension: "TECHNICAL_AUTHENTICITY",
16530
- severity: "MAJOR",
16531
- title: "Invalid delay() Parameter",
16532
- description: "delay() duration must be a positive integer in milliseconds.",
16533
- remediationAdvice: "Use realistic delay timings (e.g. 500ms, 1000ms)."
16534
- });
16535
- }
16536
- }
16537
- strengths.push("Guided practice features runnable code snippet with clear syntax.");
16538
- }
16539
- if (mermaidDiagram) {
16540
- const cleanDiagram = mermaidDiagram.trim().toLowerCase();
16541
- const isValidStarter = VALID_MERMAID_STARTERS.some((starter) => cleanDiagram.startsWith(starter));
16542
- if (!isValidStarter) {
16543
- score -= 15;
16544
- findings.push({
16545
- id: "tech_invalid_mermaid_syntax",
16546
- dimension: "TECHNICAL_AUTHENTICITY",
16547
- severity: "MAJOR",
16548
- title: "Invalid Mermaid Diagram Syntax",
16549
- description: `Mermaid diagram does not start with a valid declaration (e.g. "flowchart TD", "graph TD", "sequenceDiagram"). Got: "${mermaidDiagram.substring(0, 30)}..."`,
16550
- remediationAdvice: "Format Mermaid diagrams starting with `flowchart TD` or `sequenceDiagram`."
16551
- });
16552
- } else {
16553
- strengths.push("Valid Mermaid architectural diagram included.");
16554
- }
16555
- }
16556
- }
16557
- if (codeLab) {
16558
- const starter = codeLab.starterCode?.content || "";
16559
- const solution = codeLab.solutionCode?.content || "";
16560
- if (starter.length < 20 || solution.length < 20) {
16561
- score -= 25;
16562
- findings.push({
16563
- id: "tech_codelab_incomplete_codes",
16564
- dimension: "TECHNICAL_AUTHENTICITY",
16565
- severity: "CRITICAL",
16566
- title: "Incomplete CodeLab Starter / Solution Code",
16567
- description: "CodeLab must provide both scaffolding starter code and complete reference solution code.",
16568
- remediationAdvice: "Populate `starterCode` with TODO markers and `solutionCode` with tested implementation."
16569
- });
16570
- } else {
16571
- strengths.push("CodeLab provides complete starter skeleton and working solution code.");
16572
- }
16573
- if (!codeLab.testCases || codeLab.testCases.length === 0) {
16574
- score -= 15;
16575
- findings.push({
16576
- id: "tech_codelab_missing_testcases",
16577
- dimension: "TECHNICAL_AUTHENTICITY",
16578
- severity: "MAJOR",
16579
- title: "Missing Automated Verification Test Cases",
16580
- description: "CodeLab lacks test cases for students to self-verify their implementations.",
16581
- remediationAdvice: "Add at least 2 concrete test cases with input and expected output assertions."
16582
- });
16583
- }
16008
+ // ─── Intake (write path — service role) ───────────────────────────────────
16009
+ /** Persist a schema-validated pack as a new framework (status=draft). */
16010
+ async importPack(pack, opts) {
16011
+ const parsed = FrameworkPackSchema.safeParse(pack);
16012
+ if (!parsed.success) {
16013
+ throw new Error("importPack: pack failed schema validation: " + parsed.error.issues.map((i) => i.path.join(".") + ": " + i.message).join("; "));
16584
16014
  }
16585
- if (activity?.materialsBOM?.hardware && activity.materialsBOM.hardware.length > 0) {
16586
- const hwText = activity.materialsBOM.hardware.join(" ").toLowerCase();
16587
- const hasLED = hwText.includes("led");
16588
- const hasResistor = hwText.includes("\u0111i\u1EC7n tr\u1EDF") || hwText.includes("resistor") || hwText.includes("220") || hwText.includes("330") || hwText.includes("1k");
16589
- if (hasLED && !hasResistor) {
16590
- score -= 20;
16591
- findings.push({
16592
- id: "tech_hardware_unsafe_led_no_resistor",
16593
- dimension: "TECHNICAL_AUTHENTICITY",
16594
- severity: "CRITICAL",
16595
- title: "Dangerous Hardware Circuit: LED without Current-Limiting Resistor",
16596
- description: "Activity specifies an LED on breadboard/microcontroller without a 220\u03A9-1k\u03A9 current-limiting resistor, which causes electrical overload and burnout.",
16597
- remediationAdvice: "Add a 220\u03A9 or 330\u03A9 current-limiting resistor to the hardware BOM."
16598
- });
16599
- } else if (hasLED && hasResistor) {
16600
- strengths.push("Hardware BOM safely pairs LED with current-limiting resistor protection.");
16601
- }
16015
+ const p = parsed.data;
16016
+ const { data: fw, error: fwErr } = await this.client.from("standards_frameworks").insert({
16017
+ pack_id: p.manifest.id,
16018
+ content_version: p.manifest.contentVersion,
16019
+ name: p.manifest.name,
16020
+ spec_version: p.manifest.specVersion,
16021
+ subject: p.manifest.subject,
16022
+ languages: p.manifest.languages,
16023
+ grade_model: p.manifest.gradeModel,
16024
+ provenance: p.manifest.provenance,
16025
+ trust: p.manifest.trust,
16026
+ status: "draft",
16027
+ organization_code: opts?.organizationCode ?? (p.manifest.trust === "verified" ? null : p.manifest.provenance.importedBy?.replace(/^org:/, "") || null),
16028
+ original_file_path: opts?.originalFilePath ?? null,
16029
+ created_by: opts?.createdBy ?? null
16030
+ }).select("id").single();
16031
+ if (fwErr) throw new Error("importPack: framework insert failed: " + fwErr.message);
16032
+ const frameworkId = fw.id;
16033
+ const statementRows = p.statements.map((s) => ({
16034
+ framework_id: frameworkId,
16035
+ statement_id: s.id,
16036
+ parent_statement_id: s.parentId ?? null,
16037
+ grade_min: s.gradeBand[0],
16038
+ grade_max: s.gradeBand[1],
16039
+ texts: s.texts,
16040
+ classifications: s.classifications ?? [],
16041
+ bloom_hint: s.bloomHint ?? null,
16042
+ keywords: s.keywords ?? [],
16043
+ source_ref: s.sourceRef ?? null,
16044
+ provenance: s.provenance
16045
+ }));
16046
+ const { error: stErr, count: stCount } = await this.client.from("standards_statements").insert(statementRows, { count: "exact" });
16047
+ if (stErr) throw new Error("importPack: statement insert failed: " + stErr.message);
16048
+ let mappingCount = 0;
16049
+ if (p.mappings && p.mappings.length > 0) {
16050
+ const mappingRows = p.mappings.map((m) => ({
16051
+ framework_id: frameworkId,
16052
+ statement_id: m.statementId,
16053
+ target_ref: m.targetRef,
16054
+ kind: m.kind,
16055
+ confidence: m.confidence,
16056
+ provenance: m.provenance
16057
+ }));
16058
+ const { error: mpErr, count: mpCount } = await this.client.from("standards_mappings").insert(mappingRows, { count: "exact" });
16059
+ if (mpErr) throw new Error("importPack: mapping insert failed: " + mpErr.message);
16060
+ mappingCount = mpCount ?? mappingRows.length;
16602
16061
  }
16603
- score = Math.max(0, Math.min(100, score));
16604
- return {
16605
- score,
16606
- weight: 0.15,
16607
- passed: score >= 75 && !findings.some((f) => f.severity === "CRITICAL"),
16608
- strengths,
16609
- findings
16610
- };
16062
+ return { frameworkDbId: frameworkId, statementsInserted: stCount ?? statementRows.length, mappingsInserted: mappingCount };
16611
16063
  }
16612
- };
16613
-
16614
- // src/evaluators/misconceptionEvaluator.ts
16615
- var LAZY_DISTRACTOR_PATTERNS = [
16616
- /^(?:tất cả các đáp án trên đều (?:đúng|sai)|cả a,?\s*b,?\s*c đều (?:đúng|sai)|all of the above|none of the above)[\.\?!]?$/i,
16617
- /^(?:không có đáp án nào đúng|không có chức năng|không làm gì cả|không ảnh hưởng)[\.\?!]?$/i,
16618
- /^(?:đáp án khác|other)[\.\?!]?$/i
16619
- ];
16620
- var MisconceptionEvaluator = class {
16064
+ /** Activate a draft framework (immutable version is now live). */
16065
+ async activatePack(frameworkDbId) {
16066
+ const { error } = await this.client.from("standards_frameworks").update({ status: "active" }).eq("id", frameworkDbId).eq("status", "draft");
16067
+ if (error) throw new Error("activatePack failed: " + error.message);
16068
+ }
16069
+ async deprecatePack(frameworkDbId) {
16070
+ const { error } = await this.client.from("standards_frameworks").update({ status: "deprecated" }).eq("id", frameworkDbId);
16071
+ if (error) throw new Error("deprecatePack failed: " + error.message);
16072
+ }
16073
+ async adoptPack(frameworkDbId, organizationCode, adoptedBy) {
16074
+ const { error } = await this.client.from("standards_org_adoptions").upsert(
16075
+ { framework_id: frameworkDbId, organization_code: organizationCode, adopted_by: adoptedBy ?? null },
16076
+ { onConflict: "organization_code,framework_id" }
16077
+ );
16078
+ if (error) throw new Error("adoptPack failed: " + error.message);
16079
+ }
16080
+ // ─── Runtime (read path — generation) ─────────────────────────────────────
16621
16081
  /**
16622
- * Audits the psychometric and pedagogical rigor of diagnostic questions and their distractors.
16082
+ * Load all packs usable by an org: platform packs (verified, org IS NULL) +
16083
+ * org packs + org adoptions. Hydrated into the same FrameworkPack shape the
16084
+ * in-memory Phase-1 components consume (injector / coverage gate / judge).
16623
16085
  */
16624
- static evaluateQuiz(quiz) {
16625
- const findings = [];
16626
- const strengths = [];
16627
- let score = 100;
16628
- const questions = quiz.questions || [];
16629
- if (questions.length === 0) {
16630
- return {
16631
- score: 0,
16632
- weight: 0.2,
16633
- passed: false,
16634
- strengths: [],
16635
- findings: [
16636
- {
16637
- id: "misconception_no_questions",
16638
- dimension: "MISCONCEPTION_RIGOR",
16639
- severity: "CRITICAL",
16640
- title: "Empty Question Bank",
16641
- description: "No questions provided in quiz artifact.",
16642
- remediationAdvice: "Generate diagnostic questions with deliberate misconception traps."
16643
- }
16644
- ]
16645
- };
16086
+ async loadPacksForOrg(organizationCode) {
16087
+ let query = this.client.from("standards_frameworks").select("*, standards_org_adoptions(organization_code)").eq("status", "active");
16088
+ const { data: frameworks, error } = await query;
16089
+ if (error) throw new Error("loadPacksForOrg: " + error.message);
16090
+ const visible = (frameworks ?? []).filter((f) => {
16091
+ const own = f.organization_code && organizationCode && f.organization_code === organizationCode;
16092
+ const global = !f.organization_code;
16093
+ const adopted = organizationCode && (f.standards_org_adoptions ?? []).some((a) => a.organization_code === organizationCode);
16094
+ return global || own || adopted;
16095
+ });
16096
+ if (visible.length === 0) return [];
16097
+ const ids = visible.map((f) => f.id);
16098
+ const [{ data: statements, error: stErr }, { data: mappings, error: mpErr }, { data: overrides, error: ovErr }] = await Promise.all([
16099
+ this.client.from("standards_statements").select("*").in("framework_id", ids),
16100
+ this.client.from("standards_mappings").select("*").in("framework_id", ids),
16101
+ this.client.from("standards_mapping_overrides").select("*").in("framework_id", ids)
16102
+ ]);
16103
+ if (stErr) throw new Error("loadPacksForOrg statements: " + stErr.message);
16104
+ const overridesByFw = /* @__PURE__ */ new Map();
16105
+ for (const o of overrides ?? []) {
16106
+ const list = overridesByFw.get(o.framework_id) ?? [];
16107
+ list.push(o);
16108
+ overridesByFw.set(o.framework_id, list);
16646
16109
  }
16647
- let questionsWithFullExplanations = 0;
16648
- for (let i = 0; i < questions.length; i++) {
16649
- const q = questions[i];
16650
- const qId = q.id || `Q${i + 1}`;
16651
- const options = q.options || [];
16652
- if (options.length < 4) {
16653
- score -= 15;
16654
- findings.push({
16655
- id: `misconception_few_options_${qId}`,
16656
- dimension: "MISCONCEPTION_RIGOR",
16657
- severity: "MAJOR",
16658
- title: `Insufficient Distractors in ${qId}`,
16659
- description: `Question ${qId} has only ${options.length} options. Standard diagnostic rigor requires 4 plausible choices (1 key + 3 diagnostic distractors).`,
16660
- remediationAdvice: "Provide 4 full options (A, B, C, D) representing distinct cognitive states.",
16661
- affectedElement: qId
16662
- });
16663
- }
16664
- const correctCount = options.filter((o) => o.isCorrect).length;
16665
- if (correctCount !== 1) {
16666
- score -= 25;
16667
- findings.push({
16668
- id: `misconception_invalid_correct_count_${qId}`,
16669
- dimension: "MISCONCEPTION_RIGOR",
16670
- severity: "CRITICAL",
16671
- title: `Key Assignment Error in ${qId}`,
16672
- description: `Question ${qId} has ${correctCount} correct options (must have exactly 1 true answer).`,
16673
- remediationAdvice: "Set `isCorrect: true` on exactly one option and `isCorrect: false` on all distractors.",
16674
- affectedElement: qId
16675
- });
16676
- }
16677
- let missingExplanation = false;
16678
- for (const opt of options) {
16679
- const text = (opt.text || "").trim();
16680
- const explanation = (opt.explanation || "").trim();
16681
- if (LAZY_DISTRACTOR_PATTERNS.some((p) => p.test(text))) {
16682
- score -= 10;
16683
- findings.push({
16684
- id: `misconception_lazy_distractor_${qId}_${opt.id}`,
16685
- dimension: "MISCONCEPTION_RIGOR",
16686
- severity: "MAJOR",
16687
- title: `Low-Utility Distractor in ${qId} (${opt.id})`,
16688
- description: `Option "${text}" is a generic/throwaway distractor ("All/None of the above" or "No effect") that does not diagnose student cognitive models.`,
16689
- remediationAdvice: "Replace with an authentic student misconception (e.g. inverted logic, missing pullup, off-by-one boundary, unit confusion).",
16690
- affectedElement: `${qId}.${opt.id}`
16691
- });
16692
- }
16693
- if (!explanation || explanation.length < 20) {
16694
- missingExplanation = true;
16695
- }
16696
- }
16697
- if (missingExplanation) {
16698
- score -= 10;
16699
- findings.push({
16700
- id: `misconception_shallow_explanation_${qId}`,
16701
- dimension: "MISCONCEPTION_RIGOR",
16702
- severity: "MAJOR",
16703
- title: `Shallow Distractor Explanations in ${qId}`,
16704
- description: `Question ${qId} lacks detailed pedagogical explanations for all options. Students and teachers cannot diagnose root causes without option-level rationale.`,
16705
- remediationAdvice: "For EVERY option (A, B, C, D), explicitly write why the choice is correct or what mental misconception it represents.",
16706
- affectedElement: qId
16707
- });
16708
- } else {
16709
- questionsWithFullExplanations++;
16110
+ return visible.map((f) => {
16111
+ const stmts = (statements ?? []).filter((s) => s.framework_id === f.id).map((s) => ({
16112
+ id: s.statement_id,
16113
+ parentId: s.parent_statement_id ?? void 0,
16114
+ gradeBand: [s.grade_min, s.grade_max],
16115
+ texts: s.texts,
16116
+ classifications: s.classifications ?? [],
16117
+ bloomHint: s.bloom_hint ?? void 0,
16118
+ keywords: s.keywords ?? [],
16119
+ sourceRef: s.source_ref ?? void 0,
16120
+ provenance: s.provenance ?? { method: "imported" }
16121
+ }));
16122
+ const ov = overridesByFw.get(f.id) ?? [];
16123
+ const retired = new Set(ov.filter((o) => o.kind === "retired").map((o) => o.statement_id + "|" + o.target_ref));
16124
+ const embedded = (mappings ?? []).filter((m) => m.framework_id === f.id).map((m) => ({
16125
+ statementId: m.statement_id,
16126
+ targetRef: m.target_ref,
16127
+ kind: m.kind,
16128
+ confidence: Number(m.confidence),
16129
+ provenance: m.provenance ?? { method: "imported" }
16130
+ }));
16131
+ const overlay = ov.filter((o) => o.kind !== "retired").map((o) => ({
16132
+ statementId: o.statement_id,
16133
+ targetRef: o.target_ref,
16134
+ kind: o.kind,
16135
+ confidence: Number(o.confidence),
16136
+ provenance: { method: "human", reviewedBy: o.created_by ?? "overlay", note: o.note ?? void 0 }
16137
+ }));
16138
+ const bridge = /* @__PURE__ */ new Map();
16139
+ for (const m of embedded) bridge.set(m.statementId + "|" + m.targetRef, m);
16140
+ for (const m of overlay) bridge.set(m.statementId + "|" + m.targetRef, m);
16141
+ const finalMappings = [...bridge.values()].filter((m) => !retired.has(m.statementId + "|" + m.targetRef));
16142
+ const hydrated = FrameworkPackSchema.safeParse({
16143
+ manifest: {
16144
+ id: f.pack_id,
16145
+ name: f.name,
16146
+ specVersion: f.spec_version || "1.0",
16147
+ contentVersion: f.content_version,
16148
+ subject: f.subject,
16149
+ languages: f.languages,
16150
+ gradeModel: f.grade_model,
16151
+ provenance: f.provenance,
16152
+ trust: f.trust
16153
+ },
16154
+ statements: stmts,
16155
+ mappings: finalMappings
16156
+ });
16157
+ if (!hydrated.success) {
16158
+ throw new Error('loadPacksForOrg: hydrated pack "' + f.pack_id + '" failed schema: ' + hydrated.error.issues[0]?.message);
16710
16159
  }
16711
- }
16712
- if (questionsWithFullExplanations === questions.length && questions.length >= 3) {
16713
- strengths.push("All quiz questions feature rigorous 4-option breakdown with comprehensive misconception analysis.");
16714
- }
16715
- score = Math.max(0, Math.min(100, score));
16716
- return {
16717
- score,
16718
- weight: 0.2,
16719
- passed: score >= 75 && !findings.some((f) => f.severity === "CRITICAL"),
16720
- strengths,
16721
- findings
16722
- };
16160
+ return { ...hydrated.data, dbId: f.id, status: f.status, organizationCode: f.organization_code ?? null };
16161
+ });
16723
16162
  }
16724
16163
  };
16725
16164
 
@@ -17210,6 +16649,6 @@ function renderMediaPlaceholder(entry) {
17210
16649
  return `> \u{1F5BC}\uFE0F [\u1EA2nh \u0111ang ch\u1EDD: ${entry.name} \u2014 s\u1EBD \u0111\u01B0\u1EE3c t\u1EA1o sau khi duy\u1EC7t media]`;
17211
16650
  }
17212
16651
 
17213
- export { ACT_TEMPLATE, ARTIFACT_EXECUTION_ORDER, AcademicAuditor, ActiveLearningWorkflowSchema, ActivityLabSchema, ActivitySeqRowSchema, ActivityStepSchema, ArtifactContractRowSchema, AssessmentMapRowSchema, AssessmentObjectiveSchema, BELL_RINGER_TEMPLATE, BLOOM_ACTION_VERBS, BOM_TEMPLATE, BUNDLED_STANDARDS_PACK_IDS, BellRingerDaySchema, BellRingerSchema, BloomHintSchema, BloomLevelSchema, BloomTaxonomyEvaluator, BronzeTierSchema, CERConclusionSchema, CHOICE_BOARD_TEMPLATE, CODE_LAB_TEMPLATE, CURRICULUM_SLASH_COMMANDS, CardTierEnum, ChoiceBoardRubricRowSchema, ChoiceBoardSchema, ChoiceRuleSchema, ChoiceSquareSchema, ClassificationSchema, CodeHardwareFeasibilityEvaluator, CodeLabSchema, CodeSnippetSchema, CompetencyRubricRowSchema, ComputationalThinkingSchema, ConstructiveAlignmentEvaluator, CoreConceptSchema, CourseObjectiveSchema, CoverageReportSchema, CrossArtifactDriftEvaluator, CurriculumArtifactSchema, CurriculumError, CurriculumPlanSchema, CurriculumQualityReportSchema, DEFAULT_ENABLED_PROVIDERS, DEFAULT_GATE_SETTINGS, DEFAULT_STREAM_IDLE_MS, DEFAULT_STREAM_TOTAL_MS, DependencyEdgeSchema, DepthAssignmentSchema, DepthLevelSchema, DeterministicPipelineRunner, DeterministicStructuralLinter, DiagnosticQuestionSchema, DiagnosticQuizSchema, EDPPhaseEnum, EXIT_TICKET_TEMPLATE, EXPOSITION_REL, EXT_TEMPLATE, EntryLevelSchema, ExitTicketBugHuntSchema, ExitTicketMetacognitionSchema, ExitTicketQuickItemSchema, ExitTicketRecallPromptSchema, ExitTicketSchema, ExperimentalDesignSchema, ExpositionApprovalError, ExtensionChallengeSchema, ExtensionSchema, FileSystemCurriculumAdapter, FiveEFlowPhaseSchema, FiveEInstructionalEvaluator, FiveEPhaseEnum, FrameworkMappingSchema, FrameworkPackManifestSchema, FrameworkPackSchema, FrameworkStatementSchema, GLOSSARY_TEMPLATE, GRAPHIC_ORGANIZER_TEMPLATE, GlossaryQuickRefRowSchema, GlossarySchema, GlossaryTermSchema, GoldTierSchema, GradeBandSchema, GraphicOrganizerItemSchema, GraphicOrganizerSchema, HANDOUT_TEMPLATE, HandoutSchema, HandoutSectionSchema, InstructionSectionSchema, InstructionStepSchema, JudgeCriterionSchema, LAYER_TOTAL_BUDGET_MS, LESSON_PLAN_TEMPLATE, LLMJudgeEngine, LabTierTaskSchema, LearningObjectiveInputSchema, LearningObjectiveRowSchema, LessonFlowPhaseSchema, LessonPlan5ESchema, LessonPlanEDPSchema, LessonPlanSchema, LessonSectionSchema, LocalWorkspaceManager, MappingKindSchema, MarpSlideSchema, MediaError, MediaLedger, MentorCheatsheetSchema, MilestoneInputSchema, MisconceptionEvaluator, MisconceptionSchema, ModelPolicyResolver, NVIDIA_MODELS, NodeKindSchema, OrganizerTypeEnum, PROJECT_INSTRUCTION_TEMPLATE, PhaseInputSchema, PlanConstraintsSchema, PlannerInputSchema, PlanningGraphSchema, PlanningNodeSchema, PrerequisiteDecisionEntrySchema, PrerequisiteDecisionSchema, ProductGoalSchema, ProgressiveHintsSchema, ProjectGraphSchema, ProjectInstructionSchema, ProjectProfileSchema, QUIZ_TEMPLATE, QualityAuditVerdictSchema, QuizOptionSchema, REVIEW_GAME_TEMPLATE, RUBRIC_TEMPLATE, RecordProvenanceSchema, ResourceMapRowSchema, ReviewGameExportRowSchema, ReviewGameQuestionSchema, ReviewGameSchema, RoadmapInputSchema, RotationStationSchema, RubricCriteriaSchema, RubricSchema, SCIENCE_LAB_TEMPLATE, SELF_LAB_TEMPLATE, SLIDE_LAYOUT_PRESETS, SLIDE_TEMPLATE, STANDARD_SOT_FILES, STATION_ROTATION_TEMPLATE, ScaffoldDecisionEntrySchema, ScaffoldDecisionSchema, ScienceLabSchema, ScoringRubricRowSchema, SelfLabSchema, SelfPacedBundleSchema, SelfPacedChallengeSchema, SessionPlanSchema, SilverTierSchema, SlideDeckSchema, StandardizedTermRowSchema, StandardsRegistryAdapter, StationRecordRowSchema, StationRotationSchema, StationTypeEnum, SupabaseCurriculumAdapter, TASK_CARDS_TEMPLATE, TEACHER_GUIDE_TEMPLATE, TIERED_PRACTICE_TEMPLATE, TaskCardSchema, TaskCardsSchema, TeacherGuideSchema, TeachingScriptPhaseSchema, TierLevelEnum, TierObjectiveSchema, TieredPracticeSchema, TranslationPolicySchema, TroubleshootingEntrySchema, TroubleshootingRowSchema, UnitPlanSchema, UserJourneySchema, WORKSHEET_TEMPLATE, WorksheetItemSchema, WorksheetItemTypeEnum, WorksheetPartSchema, WorksheetSchema, activityTools, analystTools, analyzeProjectCreationIntent, approvalHookToken, approvalPayloadSchema, assertAcyclic, assessorTools, auditCurriculumQualityFlow, auditQualityReport, buildActivityPrompt, buildCodeLabPrompt, buildCurriculumContext, buildCurriculumPlan, buildDeliveryPackages, buildDiagnosticQuizPrompt, buildExpositionContext, buildExtensionPrompt, buildHandoutPrompt, buildImagePrompt, buildJudgePrompt, buildLessonMasterPrompt, buildProjectInstructionPrompt, buildSelfLabPrompt, buildSessionSliceContext, buildSlidesPrompt, buildStandardStackMarkdown, buildStandardsContext, buildStandardsContextBlock, buildTeacherGuidePrompt, buildWorksheetPrompt, computeContentHash, computePackingSpec, conductPreliminaryResearch, contentTools, convertRoadmapToFoundationSot, createAiInferenceError, createCurriculumStorage, createStreamAbortSignal, curateMediaLedger, designerTools, detectProjectPedagogy, ensureExpositionForLesson, ensureKnowledgeExposition, evaluateStandardsCoverage, executeCurriculumCommand, executeSingleArtifactStep, exportAllProjectQuizzes, expositionCacheKey, extractScopeSequenceRows, extractSessionSlice, extractStreamChunk, extractThoughtAndContent, formatQuizzesToCsv, fulfillMediaLedger, gateModeFor, generateActivityFlow, generateActivityStep, generateCodeLabFlow, generateCodeLabStep, generateDiagnosticQuizFlow, generateDiagnosticQuizStep, generateEducationalImage, generateExtensionFlow, generateExtensionStep, generateHandoutFlow, generateHandoutStep, generateLessonMasterFlow, generateMasterLessonStep, generateMilestoneCurriculumBundle, generateMilestoneWorkflow, generatePhase1SotArtifacts, generatePhase2SotArtifacts, generateProjectInstruction, generateProjectInstructionFlow, generateRoadmapCurriculum, generateRoadmapWorkflow, generateSelfLabFlow, generateSelfLabStep, generateSelfPacedBundle, generateSingleArtifact, generateSingleArtifactWorkflow, generateSlidesFlow, generateSlidesStep, generateTeacherGuideFlow, generateTeacherGuideStep, generateWorksheetFlow, generateWorksheetStep, getAIModel, getArtifactMetadata, getDesignatedFallbackChain, getDesignatedFallbackConfig, getLessonMetadata, getProjectArtifactScope, getProjectStatusReport, getSlideLayoutPresetById, getSlideLayoutPresetsByCategory, getSmartResumeContext, glossaryTermsForSession, illustratorTools, importRoadmapToProject, ingestProjectGraphIntoProject, initializeProjectInStorage, injectMediaIntoMarkdown, isExpositionFresh, isModelAllowed, isProviderEnabled, isTranslationDue, judgeMasterLessonStep, judgeSatelliteStep, lessonApprovalHook, lintAndSanitizeArtifact, lintCurriculumFramework, lintFrameworkPack, loadCurriculumTemplate, loadSotTemplate, normalizePlanningGraph, packagerTools, parseGateSettings, parseQuizMarkdown, parseRoadmapJsonToProjectPayload, produceBatchLessons, produceSingleLesson, publishToGitHub, publishToGitStep, publishToSupabase, publishToSupabaseStep, rankGenCandidates, renderFrameworkFromPlan, renderMediaPlaceholder, repairMasterLessonStep, researcherTools, resolveGateSettings, resolveStandardsPacks, resolveStreamBudget, resolveTranslationTargets, reviewerTools, runCurriculumAIInference, safeParseJson, saveMilestoneToWorkspaceStep, searchEducationalImages, searchEducationalVideos, selectStatementsForLesson, serializeActivityToMarkdown, serializeCodeLabToMarkdown, serializeDiagnosticQuizToMarkdown, serializeHandoutToMarkdown, serializeLessonToMarkdown, serializeProjectInstructionToMarkdown, serializeSelfLabToMarkdown, slugifyProjectName, streamCurriculumAIInference, streamCurriculumAIInferenceWithTools, streamDiagnosticQuizFlow, streamLLMWithFallback, streamLayerPrefillWithFallback, streamLessonMasterFlow, streamSelfLabFlow, techSmeTools, topoSort, uploadAssetToBucket, validateCurriculumPlan, validateFrameworkPack, validateMarkdownTables, validateMermaidSyntax, withAutoRepair, withRateLimitBackoff };
16652
+ export { ACT_TEMPLATE, ARTIFACT_EXECUTION_ORDER, AcademicAuditor, ActiveLearningWorkflowSchema, ActivityLabSchema, ActivitySeqRowSchema, ActivityStepSchema, ArtifactContractRowSchema, AssessmentMapRowSchema, AssessmentObjectiveSchema, BELL_RINGER_TEMPLATE, BLOOM_ACTION_VERBS, BOM_TEMPLATE, BUNDLED_STANDARDS_PACK_IDS, BellRingerDaySchema, BellRingerSchema, BloomHintSchema, BloomLevelSchema, BloomTaxonomyEvaluator, BronzeTierSchema, CERConclusionSchema, CHOICE_BOARD_TEMPLATE, CODE_LAB_TEMPLATE, CURRICULUM_SLASH_COMMANDS, CardTierEnum, ChoiceBoardRubricRowSchema, ChoiceBoardSchema, ChoiceRuleSchema, ChoiceSquareSchema, ClassificationSchema, CodeHardwareFeasibilityEvaluator, CodeLabSchema, CodeSnippetSchema, CompetencyRubricRowSchema, ComputationalThinkingSchema, ConstructiveAlignmentEvaluator, CoreConceptSchema, CourseObjectiveSchema, CoverageReportSchema, CrossArtifactDriftEvaluator, CurriculumArtifactSchema, CurriculumError, CurriculumPlanSchema, CurriculumQualityReportSchema, DEFAULT_ENABLED_PROVIDERS, DEFAULT_GATE_SETTINGS, DEFAULT_STREAM_IDLE_MS, DEFAULT_STREAM_TOTAL_MS, DependencyEdgeSchema, DepthAssignmentSchema, DepthLevelSchema, DeterministicPipelineRunner, DeterministicStructuralLinter, DiagnosticQuestionSchema, DiagnosticQuizSchema, EDPPhaseEnum, EXIT_TICKET_TEMPLATE, EXPOSITION_REL, EXT_TEMPLATE, EntryLevelSchema, ExitTicketBugHuntSchema, ExitTicketMetacognitionSchema, ExitTicketQuickItemSchema, ExitTicketRecallPromptSchema, ExitTicketSchema, ExperimentalDesignSchema, ExpositionApprovalError, ExtensionChallengeSchema, ExtensionSchema, FileSystemCurriculumAdapter, FiveEFlowPhaseSchema, FiveEInstructionalEvaluator, FiveEPhaseEnum, FrameworkMappingSchema, FrameworkPackManifestSchema, FrameworkPackSchema, FrameworkStatementSchema, GLOSSARY_TEMPLATE, GRAPHIC_ORGANIZER_TEMPLATE, GlossaryQuickRefRowSchema, GlossarySchema, GlossaryTermSchema, GoldTierSchema, GradeBandSchema, GraphicOrganizerItemSchema, GraphicOrganizerSchema, HANDOUT_TEMPLATE, HandoutSchema, HandoutSectionSchema, InstructionSectionSchema, InstructionStepSchema, JudgeCriterionSchema, LAYER_TOTAL_BUDGET_MS, LESSON_PLAN_TEMPLATE, LLMJudgeEngine, LabTierTaskSchema, LearningObjectiveInputSchema, LearningObjectiveRowSchema, LessonFlowPhaseSchema, LessonPlan5ESchema, LessonPlanEDPSchema, LessonPlanSchema, LessonSectionSchema, LocalWorkspaceManager, MappingKindSchema, MarpSlideSchema, MediaError, MediaLedger, MentorCheatsheetSchema, MilestoneInputSchema, MisconceptionEvaluator, MisconceptionSchema, ModelPolicyResolver, NVIDIA_MODELS, NodeKindSchema, OrganizerTypeEnum, PROJECT_INSTRUCTION_TEMPLATE, PhaseInputSchema, PlanConstraintsSchema, PlannerInputSchema, PlanningGraphSchema, PlanningNodeSchema, PrerequisiteDecisionEntrySchema, PrerequisiteDecisionSchema, ProductGoalSchema, ProgressiveHintsSchema, ProjectGraphSchema, ProjectInstructionSchema, ProjectProfileSchema, QUIZ_TEMPLATE, QualityAuditVerdictSchema, QuizOptionSchema, REVIEW_GAME_TEMPLATE, RUBRIC_TEMPLATE, RecordProvenanceSchema, ResourceMapRowSchema, ReviewGameExportRowSchema, ReviewGameQuestionSchema, ReviewGameSchema, RoadmapInputSchema, RotationStationSchema, RubricCriteriaSchema, RubricSchema, SCIENCE_LAB_TEMPLATE, SELF_LAB_TEMPLATE, SLIDE_LAYOUT_PRESETS, SLIDE_TEMPLATE, STANDARD_SOT_FILES, STATION_ROTATION_TEMPLATE, ScaffoldDecisionEntrySchema, ScaffoldDecisionSchema, ScienceLabSchema, ScoringRubricRowSchema, SelfLabSchema, SelfPacedBundleSchema, SelfPacedChallengeSchema, SessionPlanSchema, SilverTierSchema, SlideDeckSchema, StandardizedTermRowSchema, StandardsRegistryAdapter, StationRecordRowSchema, StationRotationSchema, StationTypeEnum, SupabaseCurriculumAdapter, TASK_CARDS_TEMPLATE, TEACHER_GUIDE_TEMPLATE, TIERED_PRACTICE_TEMPLATE, TaskCardSchema, TaskCardsSchema, TeacherGuideSchema, TeachingScriptPhaseSchema, TierLevelEnum, TierObjectiveSchema, TieredPracticeSchema, TranslationPolicySchema, TroubleshootingEntrySchema, TroubleshootingRowSchema, UnitPlanSchema, UserJourneySchema, WORKSHEET_TEMPLATE, WorksheetItemSchema, WorksheetItemTypeEnum, WorksheetPartSchema, WorksheetSchema, activityTools, analystTools, analyzeProjectCreationIntent, assertAcyclic, assessorTools, auditCurriculumQualityFlow, auditQualityReport, buildActivityPrompt, buildCodeLabPrompt, buildCurriculumContext, buildCurriculumPlan, buildDeliveryPackages, buildDiagnosticQuizPrompt, buildExpositionContext, buildExtensionPrompt, buildHandoutPrompt, buildImagePrompt, buildJudgePrompt, buildLessonMasterPrompt, buildProjectInstructionPrompt, buildSelfLabPrompt, buildSessionSliceContext, buildSlidesPrompt, buildStandardStackMarkdown, buildStandardsContext, buildStandardsContextBlock, buildTeacherGuidePrompt, buildWorksheetPrompt, closeTruncatedJson, computeContentHash, computePackingSpec, conductPreliminaryResearch, contentTools, convertRoadmapToFoundationSot, createAiInferenceError, createCurriculumStorage, createStreamAbortSignal, curateMediaLedger, designerTools, detectProjectPedagogy, ensureExpositionForLesson, ensureKnowledgeExposition, evaluateStandardsCoverage, executeCurriculumCommand, exportAllProjectQuizzes, expositionCacheKey, extractScopeSequenceRows, extractSessionSlice, extractStreamChunk, extractThoughtAndContent, formatQuizzesToCsv, fulfillMediaLedger, gateModeFor, generateActivityFlow, generateCodeLabFlow, generateDiagnosticQuizFlow, generateEducationalImage, generateExtensionFlow, generateHandoutFlow, generateLessonMasterFlow, generateMilestoneCurriculumBundle, generatePhase1SotArtifacts, generatePhase2SotArtifacts, generateProjectInstruction, generateProjectInstructionFlow, generateRoadmapCurriculum, generateSelfLabFlow, generateSelfPacedBundle, generateSingleArtifact, generateSlidesFlow, generateTeacherGuideFlow, generateWorksheetFlow, getAIModel, getArtifactMetadata, getDesignatedFallbackChain, getDesignatedFallbackConfig, getLessonMetadata, getProjectArtifactScope, getProjectStatusReport, getSlideLayoutPresetById, getSlideLayoutPresetsByCategory, getSmartResumeContext, glossaryTermsForSession, illustratorTools, importRoadmapToProject, ingestProjectGraphIntoProject, initializeProjectInStorage, injectMediaIntoMarkdown, isExpositionFresh, isModelAllowed, isProviderEnabled, isTranslationDue, lintAndSanitizeArtifact, lintCurriculumFramework, lintFrameworkPack, loadCurriculumTemplate, loadSotTemplate, normalizePlanningGraph, packagerTools, parseGateSettings, parseQuizMarkdown, parseRoadmapJsonToProjectPayload, produceBatchLessons, produceSingleLesson, publishToGitHub, publishToSupabase, rankGenCandidates, renderFrameworkFromPlan, renderMediaPlaceholder, researcherTools, resolveGateSettings, resolveStandardsPacks, resolveStreamBudget, resolveTranslationTargets, reviewerTools, runCurriculumAIInference, safeParseJson, searchEducationalImages, searchEducationalVideos, selectStatementsForLesson, serializeActivityToMarkdown, serializeCodeLabToMarkdown, serializeDiagnosticQuizToMarkdown, serializeHandoutToMarkdown, serializeLessonToMarkdown, serializeProjectInstructionToMarkdown, serializeSelfLabToMarkdown, slugifyProjectName, streamCurriculumAIInference, streamCurriculumAIInferenceWithTools, streamDiagnosticQuizFlow, streamLLMWithFallback, streamLayerPrefillWithFallback, streamLessonMasterFlow, streamSelfLabFlow, stripLlmJsonWrappers, techSmeTools, topoSort, uploadAssetToBucket, validateCurriculumPlan, validateFrameworkPack, validateMarkdownTables, validateMermaidSyntax, withAutoRepair };
17214
16653
  //# sourceMappingURL=index.mjs.map
17215
16654
  //# sourceMappingURL=index.mjs.map