@thanh01.pmt/domain-kit 0.1.0 → 0.2.1
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/LICENSE +21 -0
- package/dist/{chunk-GEUDHZE7.mjs → chunk-23TQPTHG.mjs} +173 -4
- package/dist/chunk-23TQPTHG.mjs.map +1 -0
- package/dist/chunk-7XGWW6CB.mjs +3 -0
- package/dist/{chunk-F4RZNBOE.mjs.map → chunk-7XGWW6CB.mjs.map} +1 -1
- package/dist/{chunk-VFART56O.mjs → chunk-BL5NBKPH.mjs} +12 -8
- package/dist/chunk-BL5NBKPH.mjs.map +1 -0
- package/dist/{chunk-3VVPSRAM.mjs → chunk-CRN6D4HG.mjs} +1056 -92
- package/dist/chunk-CRN6D4HG.mjs.map +1 -0
- package/dist/{chunk-3H2HX7PR.mjs → chunk-HUDFN4IX.mjs} +58 -8
- package/dist/chunk-HUDFN4IX.mjs.map +1 -0
- package/dist/chunk-IJZUV7N3.mjs +3 -0
- package/dist/chunk-IJZUV7N3.mjs.map +1 -0
- package/dist/chunk-R57WTNXW.mjs +3 -0
- package/dist/chunk-R57WTNXW.mjs.map +1 -0
- package/dist/chunk-T4Y2DE2W.mjs +187 -0
- package/dist/chunk-T4Y2DE2W.mjs.map +1 -0
- package/dist/{chunk-PM42MMDJ.mjs → chunk-WHBAGJWN.mjs} +48 -3
- package/dist/chunk-WHBAGJWN.mjs.map +1 -0
- package/dist/chunk-ZKLT27T4.mjs +3 -0
- package/dist/chunk-ZKLT27T4.mjs.map +1 -0
- package/dist/concepts/index.d.cts +2 -2
- package/dist/concepts/index.d.ts +2 -2
- package/dist/cpp-CZUPqJt9.d.cts +98 -0
- package/dist/cpp-CZUPqJt9.d.ts +98 -0
- package/dist/curriculumFeedEmitter-E5DAJYUZ.mjs +4 -0
- package/dist/curriculumFeedEmitter-E5DAJYUZ.mjs.map +1 -0
- package/dist/detector/index.cjs +10 -6
- package/dist/detector/index.cjs.map +1 -1
- package/dist/detector/index.d.cts +4 -19
- package/dist/detector/index.d.ts +4 -19
- package/dist/detector/index.mjs +2 -1
- package/dist/domainProfileDetector-DHb1T0zB.d.ts +22 -0
- package/dist/domainProfileDetector-bzugdQmS.d.cts +22 -0
- package/dist/extractors/index.d.cts +3 -3
- package/dist/extractors/index.d.ts +3 -3
- package/dist/feed/index.cjs +56 -6
- package/dist/feed/index.cjs.map +1 -1
- package/dist/feed/index.mjs +2 -1
- package/dist/graph/index.cjs +370 -66
- package/dist/graph/index.cjs.map +1 -1
- package/dist/graph/index.d.cts +7 -67
- package/dist/graph/index.d.ts +7 -67
- package/dist/graph/index.mjs +3 -2
- package/dist/hybridGraphPipeline-DVZYLCAQ.d.ts +159 -0
- package/dist/hybridGraphPipeline-DmWRKYXf.d.cts +159 -0
- package/dist/index.cjs +1303 -700
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -7
- package/dist/index.d.ts +9 -7
- package/dist/index.mjs +10 -7
- package/dist/{keywordExtractor-zPAz2isq.d.cts → keywordExtractor-BxlGRMHC.d.cts} +1 -1
- package/dist/{keywordExtractor-CKaXqSku.d.ts → keywordExtractor-DU5XRN8-.d.ts} +1 -1
- package/dist/parsers/index.cjs +185 -0
- package/dist/parsers/index.cjs.map +1 -1
- package/dist/parsers/index.d.cts +2 -98
- package/dist/parsers/index.d.ts +2 -98
- package/dist/parsers/index.mjs +2 -1
- package/dist/pipeline/index.cjs +3142 -8
- package/dist/pipeline/index.cjs.map +1 -1
- package/dist/pipeline/index.d.cts +87 -4
- package/dist/pipeline/index.d.ts +87 -4
- package/dist/pipeline/index.mjs +6 -2
- package/dist/schemas/index.cjs +51 -0
- package/dist/schemas/index.cjs.map +1 -1
- package/dist/schemas/index.d.cts +222 -3
- package/dist/schemas/index.d.ts +222 -3
- package/dist/schemas/index.mjs +1 -1
- package/dist/syllabusParser-MSX1fEzW.d.cts +40 -0
- package/dist/syllabusParser-MSX1fEzW.d.ts +40 -0
- package/package.json +9 -10
- package/dist/chunk-3H2HX7PR.mjs.map +0 -1
- package/dist/chunk-3VVPSRAM.mjs.map +0 -1
- package/dist/chunk-F4RZNBOE.mjs +0 -3
- package/dist/chunk-GEUDHZE7.mjs.map +0 -1
- package/dist/chunk-MOKNFLUD.mjs +0 -851
- package/dist/chunk-MOKNFLUD.mjs.map +0 -1
- package/dist/chunk-PM42MMDJ.mjs.map +0 -1
- package/dist/chunk-VFART56O.mjs.map +0 -1
- package/dist/graphVerifier-DsTP9uAN.d.ts +0 -37
- package/dist/graphVerifier-QjgDAJce.d.cts +0 -37
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/graph/loCodeStandard.ts","../src/graph/loExemplars.ts","../src/graph/depthAudit.ts","../src/graph/hierarchicalLoAuthoring.ts","../src/graph/knowledgeTreeCatalog.ts","../src/graph/conceptStandardizer.ts","../src/graph/knowledgeGraphPipeline.ts","../src/graph/hybridGraphPipeline.ts"],"names":["mkdirSync","writeFileSync","JSON_ONLY","prereqMap"],"mappings":";;;;;;AAiBA,IAAM,YAAA,GAAuC;AAAA,EAC3C,MAAA,EAAQ,IAAA;AAAA,EAAM,KAAA,EAAO,IAAA;AAAA,EAAM,UAAA,EAAY,IAAA;AAAA,EAAM,UAAA,EAAY,IAAA;AAAA,EAAM,IAAA,EAAM,MAAA;AAAA,EACrE,MAAA,EAAQ,IAAA;AAAA,EAAM,EAAA,EAAI,IAAA;AAAA,EAAM,IAAA,EAAM,MAAA;AAAA,EAAQ,MAAA,EAAQ,IAAA;AAAA,EAAM,GAAA,EAAK,KAAA;AAAA,EAAO,IAAA,EAAM,IAAA;AAAA,EACtE,GAAA,EAAK,KAAA;AAAA,EAAO,IAAA,EAAM,IAAA;AAAA,EAAM,GAAA,EAAK,KAAA;AAAA,EAAO,IAAA,EAAM,MAAA;AAAA,EAAQ,GAAA,EAAK;AACzD,CAAA;AAGO,SAAS,WAAW,SAAA,EAA2B;AACpD,EAAA,MAAM,OAAA,GAAA,CAAW,SA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B,WAAA,CAAY,MAAA,GAAS,6BAA6B,OAAA,GAAU,CAAA,CAAA,GAAK,GAAA,GAAM,sBAAA,GAAyB,GAAG,CAAA;AAAA,IAC7I;AAAA,EACF;AACA,EAAA,IAAI,WAAA,CAAY,SAAS,CAAA,EAAG;AAC1B,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,oEAAA,GAAuE,WAAA,CAAY,MAAA,GAAS,eAAA,GAC1F,WAAA,CAAY,GAAA,CAAI,CAAC,CAAA,KAAM,MAAA,GAAS,CAAC,CAAA,CAAE,IAAA,CAAK,IAAI,CAAA,GAC5C;AAAA,KACJ;AAAA,EACF;AAEA,EAAA,IAAI,MAAA,CAAO,MAAA,KAAW,CAAA,IAAK,QAAA,CAAS,SAAS,CAAA,EAAG;AAC9C,IAAA,QAAA,CAAS,IAAA,CAAK,qBAAA,GAAwB,QAAA,CAAS,MAAA,GAAS,yDAAyD,CAAA;AAAA,EACnH;AAEA,EAAA,GAAA,CAAI,QAAA,EAAU,qBAAqB,MAAA,CAAO,MAAA,GAAS,cAC/C,MAAA,CAAO,GAAA,CAAI,CAAA,CAAA,KAAK,CAAA,CAAE,EAAA,GAAK,GAAA,GAAM,EAAE,WAAA,CAAY,MAAA,GAAS,OAAO,CAAA,CAAE,UAAA,CAAW,SAAS,IAAI,CAAA,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA;AACrG,EAAA,OAAO,MAAA;AACT","file":"chunk-3VVPSRAM.mjs","sourcesContent":["/**\n * LO code + statement standard — calibrated against the production\n * learning_objectives table (6,693 live rows) and the knowledge-tree\n * Naming Conventions v2.2 (Appendix C of adaptive-learning-platform.md).\n *\n * Codes (deterministic, never LLM-generated):\n * concept CONCEPT_CODE UPPER_SNAKE_CASE, technology-neutral\n * ULO ULO-[CONCEPT]-NN one primary ULO per concept (NN = 01)\n * CIO CIO-[CONCEPT]-NN-[ACTION] parent = ULO, ACTION = SNAKE verb phrase\n * SIO SIO-[TECH]-[CONCEPT]-NN only tier carrying a tech tag (PY, SW, TS...)\n *\n * Statements: every LO description uses the normalized clause\n * \"The learner will be able to ...\" (production Supabase style).\n */\n\n// ─── Technology tag (SIO tier only) ─────────────────────────────────────────\n\nconst TECH_TAG_MAP: Record<string, string> = {\n python: \"PY\", swift: \"SW\", typescript: \"TS\", javascript: \"JV\", java: \"JAVA\",\n kotlin: \"KT\", go: \"GO\", rust: \"RUST\", csharp: \"CS\", cpp: \"CPP\", dart: \"DT\",\n php: \"PHP\", ruby: \"RB\", sql: \"SQL\", html: \"HTML\", css: \"CSS\",\n};\n\n/** Map a tech stack string to the production SIO tech tag (PY, SW, TS...). */\nexport function techTagFor(techStack: string): string {\n const primary = (techStack || \"\").trim().toLowerCase();\n for (const [key, tag] of Object.entries(TECH_TAG_MAP)) {\n if (primary.includes(key)) return tag;\n }\n const first = primary.split(/[\\s,+/]+/)[0] ?? \"\";\n if (!/^[a-z]/.test(first)) return \"GEN\";\n return first.length <= 4 ? first.toUpperCase() : first.slice(0, 3).toUpperCase();\n}\n\n// ─── Concept code (UPPER_SNAKE_CASE, neutral) ───────────────────────────────\n\nconst SMALL_WORDS = new Set([\"and\", \"or\", \"the\", \"of\", \"for\", \"in\", \"on\", \"a\", \"an\", \"vs\"]);\n\n/** Derive a neutral UPPER_SNAKE_CASE concept code from a human concept name. */\nexport function conceptCodeFromName(name: string): string {\n const words = name\n .replace(/[^A-Za-z0-9]+/g, \" \")\n .trim()\n .split(/\\s+/)\n .filter((w) => w.length > 0 && !SMALL_WORDS.has(w.toLowerCase()));\n const base = words.join(\"_\").toUpperCase().replace(/^_+|_+$/g, \"\").replace(/_{2,}/g, \"_\");\n const trimmed = (base || \"CONCEPT\").slice(0, 60).replace(/_+$/g, \"\");\n return trimmed;\n}\n\n/**\n * Assign unique concept codes to every concept (first occurrence keeps the\n * plain code, later collisions get a _2.._N suffix) — mirrors the DB where\n * concept_codes are unique neutral UPPER_SNAKE keys.\n */\nexport function assignConceptCodes(concepts: Array<{ id: string; name: string }>): Record<string, string> {\n const used = new Map<string, number>();\n const out: Record<string, string> = {};\n for (const c of concepts) {\n const base = conceptCodeFromName(c.name);\n const n = (used.get(base) ?? 0) + 1;\n used.set(base, n);\n out[c.id] = n === 1 ? base : base + \"_\" + n;\n }\n return out;\n}\n\n// ─── LO codes ───────────────────────────────────────────────────────────────\n\nconst pad2 = (n: number): string => String(n).padStart(2, \"0\");\n\nexport function uloCode(conceptCode: string, seq = 1): string {\n return \"ULO-\" + conceptCode + \"-\" + pad2(seq);\n}\n\nconst CIO_STOPWORDS = new Set([\n // clause boilerplate\n \"learner\", \"will\", \"be\", \"able\",\n // generic fillers\n \"a\", \"an\", \"the\", \"of\", \"to\", \"and\", \"or\", \"in\", \"on\", \"for\", \"by\", \"with\",\n \"is\", \"are\", \"that\", \"it\", \"its\", \"their\", \"when\", \"how\", \"as\", \"into\", \"from\",\n]);\n\n/** Extract a short SNAKE_CASE action phrase (2-4 content words) for a CIO code. */\nexport function cioActionSlug(cioText: string): string {\n const body = cioText.startsWith(LEARNER_CLAUSE) ? cioText.slice(LEARNER_CLAUSE.length) : cioText;\n const words = body.replace(/[^A-Za-z0-9]+/g, \" \").trim().split(/\\s+/)\n .map((w) => w.toLowerCase())\n .filter((w) => w.length > 2 && !CIO_STOPWORDS.has(w));\n const seen = new Set<string>();\n const picked: string[] = [];\n for (const w of words) {\n if (!seen.has(w)) { seen.add(w); picked.push(w); }\n if (picked.length === 3) break;\n }\n return (picked.length > 0 ? picked : [\"apply\"]).join(\"_\").toUpperCase();\n}\n\nexport function cioCode(conceptCode: string, uloSeq: number, actionSlug: string): string {\n return \"CIO-\" + conceptCode + \"-\" + pad2(uloSeq) + \"-\" + actionSlug;\n}\n\nexport function sioCode(techTag: string, conceptCode: string, seq: number): string {\n return \"SIO-\" + techTag + \"-\" + conceptCode + \"-\" + pad2(seq);\n}\n\n// ─── Standard statement clause ──────────────────────────────────────────────\n\nexport const LEARNER_CLAUSE = \"The learner will be able to \";\n\n/** Normalize any LO text into the production statement form with the standard clause. */\nexport function standardStatement(text: string): string {\n let body = (text || \"\").trim().replace(/^the learner (will be able to|can)\\s*/i, \"\").replace(/\\s+/g, \" \");\n if (body.length === 0) return \"\";\n // Lowercase a leading word unless it looks like an acronym/proper code (X.Y or ALLCAPS).\n const firstWord = body.split(\" \")[0] ?? \"\";\n const looksAcronym = /^[A-Z0-9_.`]+$/.test(firstWord) && firstWord.length > 1;\n if (!looksAcronym) body = body.charAt(0).toLowerCase() + body.slice(1);\n body = body.replace(/[.\\s]+$/, \"\");\n return LEARNER_CLAUSE + body + \".\";\n}\n\n// ─── Regex validators (calibrated to the live DB patterns) ─────────────────\n\nexport const CONCEPT_CODE_RE = /^[A-Z][A-Z0-9_]*$/;\nexport const ULO_CODE_RE = /^ULO-[A-Z][A-Z0-9_]*-\\d{2}$/;\nexport const CIO_CODE_RE = /^CIO-[A-Z][A-Z0-9_]*-\\d{2}-[A-Z][A-Z0-9_]*$/;\nexport const SIO_CODE_RE = /^SIO-[A-Z0-9]+-[A-Z][A-Z0-9_]*-\\d{2}$/;\n","/**\n * Exemplar bank for hierarchical LO authoring.\n * ULO/CIO exemplars ported from knowledge-tree master_learning_objectives.tsv\n * (approved reference bank). SIO exemplars follow the same style as judged-PASS\n * items from real pipeline runs: keyword-bound, completable, context-specific.\n */\n\nexport const ULO_EXEMPLARS: string[] = [\n // Calibrated against production learning_objectives (UNIVERSAL rows, neutral)\n \"The learner will be able to recall the key concepts, terminology, and characteristics of layers of abstraction.\",\n \"The learner will be able to explain how layers of abstraction hide implementation details while exposing essential behavior.\",\n \"The learner will be able to explain how a program changes state through statements and control flow.\",\n \"The learner will be able to differentiate local from global scope and describe how return values affect data flow.\",\n \"The learner will be able to describe the mechanism of a loop, including its condition, step and stopping rule.\",\n \"The learner will be able to explain why a representation format must balance readability against processing efficiency.\",\n];\n\nexport const CIO_EXEMPLARS: string[] = [\n // Production CONCEPTUAL_IMPL rows: mechanism behind the clause, Marr 2-Language neutral\n \"The learner will be able to develop a conceptual model that explains the internal mechanism by which the representation produces its effect.\",\n \"The learner will be able to compare alternative approaches for the same operation and describe the trade-offs between them.\",\n \"The learner will be able to decompose the choice of representation into decisive criteria such as cost, fidelity and tolerance to change.\",\n \"The learner will be able to describe the sequence of steps by which a process transforms its input into its output, including the stopping condition.\",\n];\n\nexport const SIO_EXEMPLARS: string[] = [\n // Production SPECIFIC_IMPL style: keyword-bound completable tasks, tech-tagged tier\n \"The learner will be able to use argparse.ArgumentParser with add_subparsers to register add, done and list commands in a Python CLI.\",\n \"The learner will be able to define a @dataclass with type hints and a __post_init__ method that raises ValueError on invariant violation.\",\n \"The learner will be able to execute parameterized statements via sqlite3.Connection.execute inside a with conn: transaction to perform CRUD on a tasks table.\",\n \"The learner will be able to write a pytest test that runs the CLI entry point via subprocess.run and asserts the exit code and printed output.\",\n];\n","/**\n * Deterministic ULO/CIO/SIO Contract Audit.\n *\n * Code-level checks that do NOT trust the LLM: they measure whether generated\n * depth layers satisfy the structural part of the authoring contract.\n * Ported context: knowledge-tree lo_quality/proof_tiers philosophy — generate\n * and verify are separate concerns; verification must be deterministic-first.\n */\nimport { LEARNER_CLAUSE, CONCEPT_CODE_RE, ULO_CODE_RE, CIO_CODE_RE, SIO_CODE_RE } from \"./loCodeStandard.js\";\n\n// --- Deterministic ULO/CIO/SIO Contract Audit ---------------------------------\n// Code-level checks that do NOT trust the LLM: they measure whether generated\n// depth layers satisfy the structural part of the authoring contract. The LLM\n// judge (semantic quality) complements these; it never replaces them.\n\n/** Concrete-technology signals: snake/camel identifiers, file extensions, tech acronyms. */\nconst TECH_SIGNAL_RES: RegExp[] = [\n /`[^`]+`/,\n /\\b[a-zA-Z_][A-Za-z0-9_]*\\(\\)/,\n // call-with-arguments: Status(enum.Enum), field(default_factory=list)\n /\\b[A-Za-z_][A-Za-z0-9_]*\\([^)]+\\)/,\n // attribute access glued to a value: enum.Enum, os.path, tasks.json\n /[A-Za-z0-9_)\\]]\\.[A-Za-z_][A-Za-z0-9_]+/,\n /[a-z]+_[a-z]+/,\n /[a-z]+[A-Z][A-Za-z]*/,\n /\\.[a-z]{2,4}\\b/,\n /\\b(?:API|SDK|JSON|XML|YAML|HTTP|SQL|UUID|URL|DOM|CLI|TUI|CSV|UTF|CRUD|DSL)\\b/,\n // Exception/error class names: Exception, ValueError, CustomError\n /\\b[A-Z][a-zA-Z0-9_]*(?:Error|Exception|Warning|Fault)\\b/,\n // class declarations or references: class Status, static methods on types\n /\\bclass\\s+[A-Za-z_][A-Za-z0-9_]*/,\n // inheritance/derivation mentions: inheriting from Exception, subclass of Base\n /\\b(?:inherit(?:ing|s)?|subclass(?:ing)?|deriv(?:ing|ed|es)?)\\s+(?:from|of)\\s+[A-Z][A-Za-z0-9_]*/,\n];\n\n/** Single-letter matches to ignore. */\nconst GENERIC_STOP = new Set([\"e\", \"g\", \"i\"]);\n\nfunction techSignalHits(text: string): string[] {\n const hits: string[] = [];\n for (const re of TECH_SIGNAL_RES) {\n const found = text.match(new RegExp(re.source, \"g\")) ?? [];\n for (const m of found) if (!GENERIC_STOP.has(m.toLowerCase())) hits.push(m);\n }\n return hits;\n}\n\nexport interface DepthLayerAudit {\n conceptId: string;\n uloHasTechSignals: boolean;\n uloTechSignals: string[];\n uloHasImplementationVerbs: boolean;\n sioAllKeywordBound: boolean;\n sioUnboundItems: string[];\n sioConceptKeywordBound: boolean;\n sioOffConceptItems: string[];\n sioAllCompletable: boolean;\n sioNotCompletable: string[];\n concretenessIncreases: boolean;\n clauseOk: boolean;\n codesOk: boolean;\n codeIssues: string[];\n passed: boolean;\n}\n\nexport function auditDepthLayers(\n concepts: Array<{\n id: string; name?: string; ulo?: string; cio?: string; sio?: string[];\n code?: string; ulo_code?: string; cio_code?: string; sio_codes?: string[];\n keywords?: string[];\n }>,\n): DepthLayerAudit[] {\n return concepts.map((c) => {\n const ulo = (c.ulo ?? \"\").trim();\n const cio = (c.cio ?? \"\").trim();\n const sioItems = (c.sio ?? []).map((s) => (s ?? \"\").trim()).filter(Boolean);\n const uloTechSignals = techSignalHits(ulo);\n const uloHasTechSignals = uloTechSignals.length > 0;\n const IMPL_VERBS = /\\b(implement|refactor|debug|serialize)\\b/i;\n const uloHasImplementationVerbs = IMPL_VERBS.test(ulo);\n const registryKeywords = (c.keywords ?? []).map((k) => String(k).toLowerCase()).filter((k) => k.length >= 3);\n // Concept identity tokens fall back to the concept NAME when the registry is\n // narrow: an SIO that names the concept's own subject is on-concept.\n const nameTokens = String(c.name ?? \"\").toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length >= 4);\n const boundToConcept = (s: string): boolean => {\n const lower = s.toLowerCase();\n return registryKeywords.some((k) => lower.includes(k)) || nameTokens.some((w) => lower.includes(w));\n };\n const sioUnboundItems = sioItems.filter((s) => {\n if (techSignalHits(s).length > 0) return false;\n // Bare tool/technology names (pytest, capsys, python -m build) carry no\n // punctuation signal — the concept keyword registry is the binding source.\n return !boundToConcept(s);\n });\n // Concept-keyword binding: at least one SIO item must reference a keyword\n // FROM THIS CONCEPT's registry (not just any tech signal). Skipped when the\n // caller provides no keyword registry.\n const conceptKeywords = (c.keywords ?? []).map((k) => k.toLowerCase()).filter(Boolean);\n const sioOffConceptItems = conceptKeywords.length > 0\n ? sioItems.filter((s) => !boundToConcept(s))\n : [];\n const COMPLETABLE = /\\b(build|create|implement|write|configure|add|use|apply|display|store|load|save|handle|parse|validate|test|register|compute|generate|print|format|convert|extend|define|execute|run|read|fetch|wrap|log|call|raise|install|import|export|declare|embed|model|represent|override|customize|enforce|mock|assert|query|index|cache|stream|split|join|strip|encode|decode|traverse|measure|evaluate|benchmark|diagnose|demonstrate|verify|organize|structure|choose|select|compare|distinguish|attach|annotate|expose|accept|manage|group|sort|filter|map|reduce|catch|throw|migrate|inspect|trace|parameterize|construct|design|capture)\\b/i;\n const sioNotCompletable = sioItems.filter((s) => !COMPLETABLE.test(s) && !/`[^`]+`/.test(s));\n const density = (text: string): number => {\n if (!text) return 0;\n return (techSignalHits(text).length / Math.max(1, text.split(/\\s+/).length)) * 100;\n };\n const dUlo = density(ulo);\n const dCio = density(cio);\n const dSio = sioItems.length > 0 ? Math.max(...sioItems.map(density)) : 0;\n const concretenessIncreases = dSio > dUlo;\n // Naming Conventions v2.2 + production statement clause checks\n const clauseOk =\n ulo.startsWith(LEARNER_CLAUSE) &&\n cio.startsWith(LEARNER_CLAUSE) &&\n sioItems.every((t) => t.startsWith(LEARNER_CLAUSE));\n const codeIssues: string[] = [];\n const conceptCode = (c as { code?: string }).code;\n if (conceptCode !== undefined && !CONCEPT_CODE_RE.test(conceptCode)) codeIssues.push(\"concept code not UPPER_SNAKE: \" + conceptCode);\n const uloCodeVal = (c as { ulo_code?: string }).ulo_code;\n if (uloCodeVal !== undefined && uloCodeVal !== \"\" && !ULO_CODE_RE.test(uloCodeVal)) codeIssues.push(\"ULO code malformed: \" + uloCodeVal);\n const cioCodeVal = (c as { cio_code?: string }).cio_code;\n if (cioCodeVal !== undefined && cioCodeVal !== \"\" && !CIO_CODE_RE.test(cioCodeVal)) codeIssues.push(\"CIO code malformed: \" + cioCodeVal);\n const sioCodeVals = (c as { sio_codes?: string[] }).sio_codes;\n if (sioCodeVals !== undefined) {\n if (sioCodeVals.length !== sioItems.length) codeIssues.push(\"SIO codes count mismatch\");\n for (const sc of sioCodeVals) if (!SIO_CODE_RE.test(sc)) codeIssues.push(\"SIO code malformed: \" + sc);\n }\n const codesOk = codeIssues.length === 0;\n const passed =\n !uloHasTechSignals &&\n !uloHasImplementationVerbs &&\n sioUnboundItems.length === 0 &&\n sioOffConceptItems.length === 0 &&\n sioNotCompletable.length === 0 &&\n concretenessIncreases &&\n clauseOk &&\n codesOk;\n return {\n conceptId: c.id,\n uloHasTechSignals,\n uloTechSignals,\n uloHasImplementationVerbs,\n sioAllKeywordBound: sioUnboundItems.length === 0,\n sioUnboundItems,\n sioConceptKeywordBound: sioOffConceptItems.length === 0,\n sioOffConceptItems,\n sioAllCompletable: sioNotCompletable.length === 0,\n sioNotCompletable,\n concretenessIncreases,\n clauseOk,\n codesOk,\n codeIssues,\n passed,\n };\n });\n}","/**\n * Hierarchical LO authoring — ported from knowledge-tree\n * (.agents/skills/learning-objective-generator/llm_generate_hierarchical_lo.py).\n *\n * Original architecture (3 independent phases, each gated before the next):\n * Phase A: ULOs from concepts — core competency (WHAT + WHY), technology-\n * agnostic, Cognitive Ceiling + Pragmatic Verb Mapping.\n * Phase B: CIOs from approved ULOs — mechanism (HOW), Marr 2-Language Test.\n * Phase C: SIOs from approved CIOs — keyword-bound implementation tasks.\n *\n * Depth policy (user-approved contract, differs from original Bloom ceiling):\n * - ULO/CIO bind to the CONCEPT nature; ULO typically Remember/Understand.\n * - SIO binds to KEYWORDS; Apply/Analyze/Create are assessed INDIRECTLY\n * through completing SIO in concrete context (no fixed Bloom ceiling).\n *\n * Deterministic audit (depthAudit.ts) gates every phase; a failing phase\n * triggers one targeted repair round, then hard-fails (no silent fallback).\n */\nimport { LEARNER_CLAUSE, standardStatement } from \"./loCodeStandard.js\";\nimport { ULO_EXEMPLARS, CIO_EXEMPLARS, SIO_EXEMPLARS } from './loExemplars';\nimport { auditDepthLayers, type DepthLayerAudit } from './depthAudit';\nimport { parseJsonFromLlm, type LlmClient } from '../utils/llmClient';\n\nexport interface HierarchicalLoConceptInput {\n keywords?: string[];\n id: string;\n name: string;\n description?: string;\n}\n\nexport interface HierarchicalLoResult {\n uloByConcept: Record<string, string>;\n cioByConcept: Record<string, string>;\n sioByConcept: Record<string, string[]>;\n audits: DepthLayerAudit[];\n warnings: string[];\n}\n\nfunction excerpt(text: string | undefined, max: number): string {\n const t = (text || \"\").trim();\n return t.length > max ? t.slice(0, max) + \"...\" : t;\n}\n\nasync function chatJson(\n client: LlmClient,\n system: string,\n user: string,\n): Promise<Record<string, unknown>> {\n const r = await client.chat(\n [{ role: \"system\", content: system }, { role: \"user\", content: user }],\n { temperature: 0.1, maxTokens: parseInt(process.env.KG_MAX_TOKENS || \"65536\", 10) },\n );\n return parseJsonFromLlm(r.content) as Record<string, unknown>;\n}\n\n// Batch size for per-phase LLM calls: large single batches risk output truncation\n// (reasoning tokens count against max_tokens) — 6 concepts per call keeps each\n// response comfortably inside budget.\nconst LO_BATCH_SIZE = 6;\nfunction chunkConcepts<T>(items: T[], size: number): T[][] {\n const out: T[][] = [];\n for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));\n return out;\n}\n\nconst JSON_ONLY = \"Return EXACTLY JSON. No markdown, no explanations.\";\n\nexport async function authorDepthLayersHierarchically(\n client: LlmClient,\n concepts: Array<HierarchicalLoConceptInput>,\n techStack: string,\n warnings: string[],\n): Promise<HierarchicalLoResult> {\n const uloByConcept: Record<string, string> = {};\n const cioByConcept: Record<string, string> = {};\n const sioByConcept: Record<string, string[]> = {};\n\n const conceptList = concepts\n .map((c) => \"- \" + c.id + \": \" + c.name + (c.description ? \" — \" + excerpt(c.description, 160) : \"\"))\n .join(\"\\n\");\n\n // ── Phase A: ULO (WHAT + WHY, concept-bound, technology-agnostic) ──\n const uloSystem = [\n \"You are a Curriculum Design Expert writing Universal Learning Objectives (ULO).\",\n \"\",\n \"ULO = Computational Tier: the CORE COMPETENCY — WHAT the concept is and WHY it exists —\",\n \"completely independent of any technology, language, framework, library, file format or tool.\",\n \"\",\n \"Rules:\",\n \"1. NEVER mention a concrete technology, API, library, file name or syntax in a ULO.\",\n \"2. Bind the ULO to the concept intrinsic nature: the problem it solves in principle.\",\n \"3. Typical assessment level: Remember or Understand. Use pragmatic, measurable verbs\",\n \" (Explain, Differentiate, Identify, Describe) instead of Know/Understand/Summarize.\",\n \"4. Cognitive Ceiling: do NOT force Analyze/Evaluate/Create ULOs — if the concept is\",\n \" foundational, its core competency is low-level. Higher levels are exercised later\",\n \" INDIRECTLY through implementation work, not in the ULO itself.\",\n \"5. One ULO per concept; 1-2 sentences covering WHAT + WHY.\",\n \"6. Statement form (mandatory): every ULO MUST read 'The learner will be able to ...' —\",\n \" a lowercase actionable verb follows the clause (explain ..., differentiate ...).\",\n \" Do not prefix any other phrasing.\",\n \"\",\n \"Approved style exemplars (production bank):\",\n ULO_EXEMPLARS.map((e) => \"- \" + e).join(\"\\n\"),\n \"\",\n JSON_ONLY,\n ].join(\"\\n\");\n const uloUser = [\n \"Concepts:\",\n conceptList,\n\n \"\",\n \"Return JSON:\",\n '{\"ulos\":[{\"concept_id\":\"C1\",\"ulo\":\"...\"}]}',\n ].join(\"\\n\");\n for (const batch of chunkConcepts(concepts, LO_BATCH_SIZE)) {\n const batchList = batch\n .map((c) => \"- \" + c.id + \" (\" + c.name + \")\" + (c.description ? \": \" + excerpt(c.description, 160) : \"\"))\n .join(\"\\n\");\n const batchUser = \"Concepts:\\n\" + batchList + \"\\n\\nReturn JSON:\\n\" + '{\"ulos\":[{\"concept_id\":\"C1\",\"ulo\":\"...\"}]}';\n const uloRes = await chatJson(client, uloSystem, batchUser);\n for (const u of (uloRes.ulos ?? []) as Array<{ concept_id?: string; ulo?: string }>) {\n if (u.concept_id && u.ulo) uloByConcept[u.concept_id] = standardStatement(u.ulo);\n }\n }\n for (const c of concepts) {\n if (!uloByConcept[c.id]) {\n warnings.push(\"Phase A: no ULO generated for \" + c.id + \" — kept empty (audit will fail)\");\n uloByConcept[c.id] = \"\";\n }\n }\n\n // ── Phase B: CIO (HOW mechanism, concept-bound, Marr 2-Language spirit) ──\n const uloContext = concepts\n .map((c) => \"- \" + c.id + \" (\" + c.name + \"): \" + uloByConcept[c.id])\n .join(\"\\n\");\n const cioSystem = [\n \"You are a Curriculum Design Expert writing Concept-level Instructional Objectives (CIO).\",\n \"\",\n \"CIO = Algorithmic Tier: the MECHANISM — HOW the concept works, step by step, at a\",\n \"procedural level. CIOs are derived from approved ULOs.\",\n \"\",\n \"Rules:\",\n \"1. Still technology-agnostic: describe the neutral pattern/approach WITHOUT concrete\",\n \" API names, libraries, file formats or syntax.\",\n \"2. Marr 2-Language Test: the CIO must read as true and implementable regardless of\",\n \" whether the learner uses Python, Swift, JavaScript or any other language. If it\",\n \" only makes sense in one language, rewrite it more neutrally.\",\n \"3. More concrete than the ULO: reference stages, conditions, ordering or trade-offs\",\n \" of the underlying process.\",\n \"4. One CIO per concept; 1-3 sentences describing the mechanism.\",\n \"5. Statement form (mandatory): every CIO MUST read 'The learner will be able to ...' —\",\n \" the mechanism is described after the clause.\",\n \"\",\n \"Approved style exemplars (production bank):\",\n CIO_EXEMPLARS.map((e) => \"- \" + e).join(\"\\n\"),\n \"\",\n JSON_ONLY,\n ].join(\"\\n\");\n const cioUser = [\n \"Approved ULOs:\",\n uloContext,\n \"\",\n \"Return JSON:\",\n '{\"cios\":[{\"concept_id\":\"C1\",\"cio\":\"...\"}]}',\n ].join(\"\\n\");\n for (const batch of chunkConcepts(concepts, LO_BATCH_SIZE)) {\n const batchIds = new Set(batch.map((c) => c.id));\n const batchUloContext = batch\n .map((c) => \"- \" + c.id + \" (\" + c.name + \"): \" + (uloByConcept[c.id] || \"(missing)\"))\n .join(\"\\n\");\n const batchCioUser = \"Approved ULOs:\\n\" + batchUloContext + \"\\n\\nReturn JSON:\\n\" + '{\"cios\":[{\"concept_id\":\"C1\",\"cio\":\"...\"}]}';\n const cioRes = await chatJson(client, cioSystem, batchCioUser);\n for (const x of (cioRes.cios ?? []) as Array<{ concept_id?: string; cio?: string }>) {\n if (x.concept_id && x.cio) cioByConcept[x.concept_id] = standardStatement(x.cio);\n }\n }\n for (const c of concepts) {\n if (!cioByConcept[c.id]) {\n warnings.push(\"Phase B: no CIO generated for \" + c.id + \" — kept empty (audit will fail)\");\n cioByConcept[c.id] = \"\";\n }\n }\n\n // ── Phase C: SIO (keyword-bound implementation tasks) ──\n const cioContext = concepts\n .map((c) => \"- \" + c.id + \" (\" + c.name + \"): CIO=\" + cioByConcept[c.id] + \" | ULO=\" + uloByConcept[c.id])\n .join(\"\\n\");\n const sioSystem = [\n \"You are a Curriculum Design Expert writing Specific Instructional Objectives (SIO).\",\n \"\",\n \"SIO = Implementation Tier: completable, context-specific implementation tasks derived\",\n \"from approved CIOs, bound to the TARGET technology of the course.\",\n \"\",\n \"Rules:\",\n \"1. EVERY SIO item MUST name concrete keywords/technologies: a real API, function,\",\n \" decorator, module, class, file or command of the target technology.\",\n \"2. Each item is a completable task: an actionable verb + the concrete construct + the\",\n \" context where it is used. Application/Analysis/Creation skills are assessed\",\n \" INDIRECTLY through completing these tasks — there is no fixed Bloom ceiling.\",\n \" MACHINE CHECK: every item MUST contain at least one ACTION VERB from this whitelist\",\n \" (build, create, implement, write, configure, add, use, apply, display, store, load,\",\n \" save, handle, parse, validate, test, register, compute, generate, print, format,\",\n \" convert, extend, define, execute, run, read, fetch, wrap, log, call, raise, install,\",\n \" import, export, declare, embed, model, represent, override, customize, enforce, mock,\",\n \" assert, query, index, cache, stream, split, join, strip, encode, decode, traverse,\",\n \" measure, evaluate, benchmark, diagnose, demonstrate, verify, organize, structure,\",\n \" choose, select, compare, distinguish, attach, annotate, expose, accept, manage, group,\",\n \" sort, filter, map, reduce, catch, throw, migrate, inspect, trace, parameterize,\",\n \" construct, design, capture) — OR wrap the concrete construct in backticks.\",\n \" Items with abstract verbs (understand, learn, know, grasp, appreciate, explore) and\",\n \" no backtick construct FAIL the audit. Prefer starting the task phrase with the verb.\",\n \"3. 2-3 items per concept, each referencing a DIFFERENT concrete construct.\",\n \"4. Statement form (mandatory): every SIO MUST read 'The learner will be able to ...' —\",\n \" the concrete task follows the clause.\",\n \"\",\n \"Approved style exemplars (production bank):\",\n SIO_EXEMPLARS.map((e) => \"- \" + e).join(\"\\n\"),\n \"\",\n JSON_ONLY,\n ].join(\"\\n\");\n const kwContext = concepts\n .map((c) => \"- \" + c.id + \" (\" + c.name + \"): \" + ((c.keywords ?? []).slice(0, 10).join(\", \") || \"(none listed — use concrete constructs of \" + techStack + \")\"))\n .join(\"\\n\");\n for (const batch of chunkConcepts(concepts, LO_BATCH_SIZE)) {\n const batchKw = batch\n .map((c) => \"- \" + c.id + \" (\" + c.name + \"): \" + ((c.keywords ?? []).slice(0, 10).join(\", \") || \"(none listed — use concrete constructs of \" + techStack + \")\"))\n .join(\"\\n\");\n const batchCioCtx = batch\n .map((c) => \"- \" + c.id + \" (\" + c.name + \"): CIO=\" + (cioByConcept[c.id] || \"(missing)\") + \" | ULO=\" + (uloByConcept[c.id] || \"(missing)\"))\n .join(\"\\n\");\n const batchSioUser = [\n \"Target technology: \" + techStack,\n \"\",\n \"Concept keywords (each SIO item MUST contain at least one of its concept's keywords):\",\n batchKw,\n \"\",\n \"Approved CIOs and ULOs:\",\n batchCioCtx,\n \"\",\n \"Return JSON:\",\n '{\"sios\":[{\"concept_id\":\"C1\",\"sio\":[\"...\",\"...\"]}]}',\n ].join(\"\\n\");\n const sioRes = await chatJson(client, sioSystem, batchSioUser);\n for (const x of (sioRes.sios ?? []) as Array<{ concept_id?: string; sio?: string[] }>) {\n if (x.concept_id && Array.isArray(x.sio)) sioByConcept[x.concept_id] = x.sio.map((item) => standardStatement(String(item)));\n }\n }\n for (const c of concepts) {\n if (!sioByConcept[c.id] || sioByConcept[c.id].length === 0) {\n warnings.push(\"Phase C: no SIO generated for \" + c.id + \" — kept empty (audit will fail)\");\n sioByConcept[c.id] = [];\n }\n }\n\n // ── Deterministic audit + one targeted repair round (fail-closed) ──\n const conceptIds = concepts.map((c) => c.id);\n const auditOnce = (): DepthLayerAudit[] =>\n auditDepthLayers(concepts.map((c) => ({\n id: c.id,\n name: c.name,\n keywords: c.keywords ?? [],\n ulo: uloByConcept[c.id],\n cio: cioByConcept[c.id],\n sio: sioByConcept[c.id],\n })));\n let audits = auditOnce();\n const repairRound = async (round: number): Promise<boolean> => {\n const failingNow = audits.filter((a) => !a.passed);\n if (failingNow.length === 0) return false;\n if (round > 1) warnings.push(\"Depth audit repair round \" + round + \": \" + failingNow.length + \" concept(s) still failing\");\n const failing = failingNow;\n {\n warnings.push(\"Depth audit: \" + failing.length + \"/\" + concepts.length + \" concepts failed first audit — targeted repair\");\n const repairTargets = failing.map((a) => {\n const c = concepts.find((x) => x.id === a.conceptId);\n const issues: string[] = [];\n if (a.uloHasTechSignals) issues.push(\"ULO names concrete technology (remove: \" + a.uloTechSignals.join(\", \") + \")\");\n if (a.uloHasImplementationVerbs) issues.push(\"ULO reads as an implementation task (rewrite as WHAT+WHY competency)\");\n for (const item of a.sioUnboundItems) issues.push(\"SIO not keyword-bound: \" + excerpt(item, 120));\n for (const item of a.sioOffConceptItems) issues.push(\"SIO does not reference any of this concept's keywords (\" + (c?.keywords ?? []).join(\", \") + \"): \" + excerpt(item, 120));\n for (const item of a.sioNotCompletable) issues.push(\"SIO not a completable task: \" + excerpt(item, 120));\n if (!a.concretenessIncreases) issues.push(\"SIO is not more concrete than the ULO — bind it to concrete constructs\");\n return {\n concept_id: a.conceptId,\n name: c?.name ?? a.conceptId,\n keywords: c?.keywords ?? [],\n current: { ulo: uloByConcept[a.conceptId], cio: cioByConcept[a.conceptId], sio: sioByConcept[a.conceptId] },\n issues,\n };\n });\n const repairSystem = [\n \"You repair depth-layer learning objectives that failed a deterministic contract audit.\",\n \"For each concept, rewrite ONLY the layers mentioned in issues, keeping the others as-is.\",\n \"Contract:\",\n \"- ULO: WHAT+WHY, concept-bound, technology-agnostic, Remember/Understand verbs.\",\n \"- CIO: HOW mechanism, technology-agnostic, more concrete than ULO, Marr 2-Language neutral.\",\n \"- SIO: keyword-bound completable implementation tasks naming real constructs of \" + techStack + \".\",\n \"- BINDING RULE: every SIO item must contain at least one of the concept's listed keywords VERBATIM (copy the exact keyword text into the sentence).\",\n \"- COMPLETABILITY RULE: every SIO item must contain an actionable verb (build, create, implement, write, configure, parse, validate, handle, store, load, run, read, fetch, display, generate, format, convert, test, debug, trace, measure, design, structure, select, filter, sort, map, reduce, catch, throw, migrate, deploy, query, index, cache, stream, inspect) or wrap a concrete construct in backticks — abstract verbs (understand, learn, know, grasp, explore, appreciate) always fail.\",\n \"\",\n JSON_ONLY,\n ].join(\"\\n\");\n const repairUser = [\n \"Failing concepts:\",\n JSON.stringify(repairTargets, null, 2),\n \"\",\n \"Return the FULL repaired set for these concepts in the same 3-layer JSON shape:\",\n '{\"repairs\":[{\"concept_id\":\"C1\",\"ulo\":\"...\",\"cio\":\"...\",\"sio\":[\"...\"]}]}',\n ].join(\"\\n\");\n try {\n const repairRes = await chatJson(client, repairSystem, repairUser);\n for (const r of (repairRes.repairs ?? []) as Array<{ concept_id?: string; ulo?: string; cio?: string; sio?: string[] }>) {\n if (!r.concept_id) continue;\n if (r.ulo) uloByConcept[r.concept_id] = standardStatement(r.ulo);\n if (r.cio) cioByConcept[r.concept_id] = standardStatement(r.cio);\n if (Array.isArray(r.sio) && r.sio.length > 0) sioByConcept[r.concept_id] = r.sio.map((t) => standardStatement(String(t)));\n }\n audits = auditOnce();\n } catch (err) {\n warnings.push(\"Depth repair round failed: \" + (err instanceof Error ? err.message : String(err)));\n }\n }\n return audits.every((a) => a.passed);\n };\n for (let round = 1; round <= 2; round++) {\n const allPass = await repairRound(round);\n if (allPass) break;\n }\n\n const stillFailing = audits.filter((a) => !a.passed);\n if (stillFailing.length > 0) {\n // Deterministic debug dump: inspect what the LLM actually wrote before failing.\n try {\n const { mkdirSync, writeFileSync } = await import(\"node:fs\");\n const dumpDir = (await import('node:os')).tmpdir() + '/domain-kit-debug/';\n mkdirSync(dumpDir, { recursive: true });\n writeFileSync(dumpDir + \"depth-audit-debug.json\", JSON.stringify(\n stillFailing.map((a) => ({ audit: a, ulo: uloByConcept[a.conceptId], cio: cioByConcept[a.conceptId], sio: sioByConcept[a.conceptId] })), null, 2));\n } catch { /* dump is best-effort */ }\n const detail = stillFailing.map((a) => a.conceptId + \"[\" + (a.uloHasTechSignals ? \"ulo-tech \" : \"\") + (a.uloHasImplementationVerbs ? \"ulo-impl \" : \"\") + (a.sioUnboundItems.length ? \"sio-unbound \" : \"\") + (a.sioNotCompletable.length ? \"sio-incomplete\" : \"\") + \"]\").join(\", \");\n throw new Error(\n \"Depth-layer contract audit failed after repair for: \" + detail +\n \" — regenerate or fix the prompt contract (fail-closed, no silent fallback)\"\n );\n }\n\n return { uloByConcept, cioByConcept, sioByConcept, audits, warnings };\n}\n","/**\n * knowledgeTreeCatalog.ts — loads the mlo-knowledge-tree TSV (CONCEPT/TOPIC/\n * CATEGORY/SUBJECT/FIELD rows) and exposes the deterministic half of concept\n * standardization:\n * - full CATEGORY / TOPIC listings for the LLM relevance pre-selection\n * - topic->category resolution (CONCEPT rows only carry topic codes)\n * - filtering tree concepts by selected categories/topics (+ a keyword\n * overlap safety net so strong individual matches are never filtered out)\n * - prerequisite codes per concept (prerequisite_concept_codes column)\n *\n * No LLM here: this module is pure data shaping.\n */\nimport { readFileSync } from 'node:fs';\n\nexport interface TreeConcept {\n code: string;\n name: string;\n description: string;\n keywords: string[];\n topicCodes: string[];\n categoryCodes: string[];\n prerequisiteCodes: string[];\n}\n\nexport interface TreeCatalog {\n path: string;\n concepts: TreeConcept[];\n /** category code -> name */\n categories: Map<string, string>;\n /** topic code -> { name, categoryCodes } */\n topics: Map<string, { name: string; categoryCodes: string[] }>;\n}\n\nfunction cell(v: string | undefined): string[] {\n return (v || '').split(',').map((s) => s.trim()).filter(Boolean);\n}\n\nexport function loadKnowledgeTreeCatalog(tsvPath: string): TreeCatalog {\n const text = readFileSync(tsvPath, 'utf8');\n const lines = text.split('\\n').filter((l) => l.trim().length > 0);\n if (lines.length === 0) throw new Error('Knowledge tree TSV is empty: ' + tsvPath);\n const header = lines[0].split('\\t').map((h) => h.trim());\n const col = (name: string): number => header.indexOf(name);\n const iT = col('item_type');\n const iC = col('code');\n const iN = col('name');\n const iD = col('description');\n const iCat = col('category_codes');\n const iTpc = col('topic_codes');\n const iPre = col('prerequisite_concept_codes');\n const iKw = col('keywords');\n for (const [name, idx] of [['item_type', iT], ['code', iC], ['name', iN]] as const) {\n if (idx < 0) throw new Error('Knowledge tree TSV missing column: ' + name);\n }\n const categories = new Map<string, string>();\n const topics = new Map<string, { name: string; categoryCodes: string[] }>();\n const concepts: TreeConcept[] = [];\n for (const line of lines.slice(1)) {\n const c = line.split('\\t');\n const type = (c[iT] || '').trim();\n const code = (c[iC] || '').trim();\n const name = (c[iN] || '').trim();\n if (!code || !name) continue;\n if (type === 'CATEGORY') categories.set(code, name);\n if (type === 'TOPIC') topics.set(code, { name, categoryCodes: cell(c[iCat]) });\n if (type !== 'CONCEPT') continue;\n const topicCodes = cell(c[iTpc]);\n // CONCEPT rows carry topic codes only — resolve categories via the topic map\n const categoryCodes = new Set<string>();\n for (const t of topicCodes) for (const cc of topics.get(t)?.categoryCodes || []) categoryCodes.add(cc);\n concepts.push({\n code,\n name,\n description: (c[iD] || '').trim(),\n keywords: cell(c[iKw]),\n topicCodes,\n categoryCodes: [...categoryCodes],\n prerequisiteCodes: cell(c[iPre]),\n });\n }\n if (concepts.length === 0) throw new Error('Knowledge tree TSV has no CONCEPT rows: ' + tsvPath);\n return { path: tsvPath, concepts, categories, topics };\n}\n\nfunction tokens(s: string): Set<string> {\n return new Set(\n s.toLowerCase().replace(/[^a-z0-9\\s-]/g, ' ').split(/\\s+/).filter((w) => w.length >= 4),\n );\n}\n\n/**\n * Deterministic filter AFTER the LLM picked relevant categories/topics:\n * keep concepts whose topic or category was selected. Concepts with a strong\n * individual keyword overlap are ALWAYS kept (safety net against a missed\n * category). Returns [] only when the selection is empty.\n */\nexport function filterBySelection(\n catalog: TreeCatalog,\n selectedCategories: string[],\n selectedTopics: string[],\n analysisConcepts: Array<{ name: string; keywords: string[] }>,\n maxConcepts = 120,\n): TreeConcept[] {\n const tps = new Set(selectedTopics.map((c) => c.trim().toUpperCase()).filter(Boolean));\n const cats = new Set(selectedCategories.map((c) => c.trim().toUpperCase()).filter(Boolean));\n const probe = analysisConcepts.map((c) => tokens(c.name + ' ' + c.keywords.join(' ')));\n const probeAll = new Set<string>();\n for (const p of probe) for (const w of p) probeAll.add(w);\n const inSelection = (tc: TreeConcept): boolean =>\n tc.topicCodes.some((t) => tps.has(t)) || tc.categoryCodes.some((c) => cats.has(c));\n const overlapScore = (tc: TreeConcept): number => {\n const tcTok = tokens(tc.name + ' ' + tc.description.slice(0, 300) + ' ' + tc.keywords.join(' '));\n let overlap = 0;\n for (const w of tcTok) if (probeAll.has(w)) overlap++;\n const kwDirect = tc.keywords.filter((k) => {\n const kl = k.toLowerCase();\n return [...probeAll].some((w) => w === kl || (w.length >= 5 && kl.includes(w)));\n }).length;\n return overlap * 2 + kwDirect * 3;\n };\n const kept = catalog.concepts.filter((tc) => inSelection(tc) || overlapScore(tc) >= 6);\n return kept\n .map((tc) => ({ tc, s: overlapScore(tc) }))\n .sort((a, b) => b.s - a.s)\n .slice(0, maxConcepts)\n .map((x) => x.tc);\n}\n\n/** Compact rendering for the standardization prompt. */\nexport function renderShortlist(shortlist: TreeConcept[]): string {\n return shortlist\n .map((tc) => '- ' + tc.code + ' | ' + tc.name + ' | kw: ' + tc.keywords.slice(0, 8).join(', ') +\n (tc.prerequisiteCodes.length ? ' | prereqs: ' + tc.prerequisiteCodes.join(',') : ''))\n .join('\\n');\n}\n\n/** Category + topic listing for the LLM relevance pre-selection prompt. */\nexport function renderCategoryTopicIndex(catalog: TreeCatalog): string {\n const topicToConcepts = new Map<string, number>();\n for (const tc of catalog.concepts) for (const t of tc.topicCodes) topicToConcepts.set(t, (topicToConcepts.get(t) || 0) + 1);\n const byCat = new Map<string, string[]>();\n for (const [code, info] of catalog.topics) {\n for (const cat of info.categoryCodes) {\n const arr = byCat.get(cat) || [];\n arr.push(code + ' ' + info.name + ' (' + (topicToConcepts.get(code) || 0) + ' concepts)');\n byCat.set(cat, arr);\n }\n }\n const out: string[] = [];\n for (const [code, name] of catalog.categories) {\n out.push('CATEGORY ' + code + ' — ' + name);\n for (const t of byCat.get(code) || []) out.push(' TOPIC: ' + t);\n }\n return out.join('\\n');\n}\n","/**\n * conceptStandardizer.ts — STEP 2.5 of the concept identification flow:\n *\n * 1. keywords -> escalate -> concepts (upstream STEP_6, unchanged)\n * 2. HERE: LLM-driven standardization against the knowledge-tree catalog\n * (category pre-filtered), producing:\n * - standardized concepts: adopt the tree code + tree keywords +\n * tree prerequisite codes (seed)\n * - proposed NEW concepts: kept OUT of the standard code namespace,\n * written to a separate proposals artifact for later merge\n * - ambiguous matches: treated as proposed_new with possible_tree_matches\n * 3. downstream steps use the standardized/proposed codes (fail-closed)\n *\n * The SEMANTIC decision is the LLM's. Code only validates the contract\n * (fail-closed) and writes artifacts.\n */\nimport { mkdirSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport type { LlmClient } from '../utils/llmClient';\nimport {\n loadKnowledgeTreeCatalog,\n filterBySelection,\n renderShortlist,\n renderCategoryTopicIndex,\n type TreeCatalog,\n} from './knowledgeTreeCatalog';\n\nexport interface StandardizeInput {\n id: string;\n name: string;\n description: string;\n keywords: string[];\n}\n\nexport interface StandardizationDecision {\n id: string;\n decision: 'standardized' | 'proposed_new';\n tree_code?: string;\n note?: string;\n proposed_code?: string;\n proposed_definition?: string;\n possible_tree_matches?: string[];\n /** LLM-selected subset of the tree concept's keywords that fit the course tech stack. */\n adopted_keywords?: string[];\n}\n\nexport interface StandardizationResult {\n decisions: StandardizationDecision[];\n proposals: Array<Record<string, unknown>>;\n warnings: string[];\n shortlistSize: number;\n catalogSize: number;\n}\n\nconst JSON_ONLY =\n 'Return ONLY a JSON object, no markdown fences, no commentary.';\n\nfunction parseJsonBlock(text: string): unknown {\n const start = text.indexOf('{');\n const end = text.lastIndexOf('}');\n if (start < 0 || end <= start) throw new Error('LLM standardization response has no JSON object');\n return JSON.parse(text.slice(start, end + 1));\n}\n\n/**\n * Standardize analysis concepts against the tree.\n * Throws (fail-closed) when the LLM leaves a concept undecided or the tree\n * cannot be loaded.\n */\nexport async function standardizeConcepts(opts: {\n client: LlmClient;\n concepts: StandardizeInput[];\n catalog: TreeCatalog;\n techStack?: string;\n proposalsPath?: string;\n onProgress?: (step: string, message: string) => void;\n}): Promise<StandardizationResult> {\n const { client, catalog, techStack = 'python', proposalsPath } = opts;\n const log = opts.onProgress ?? (() => {});\n const warnings: string[] = [];\n\n // ── Stage A (LLM): which categories/topics could be relevant? ──\n const hasTopics = catalog.topics.size > 0;\n const selSystem = [\n 'You pre-select relevant areas of an institutional knowledge tree before a detailed concept alignment pass.',\n hasTopics\n ? 'Given the analysis concepts, pick the TOPICS that could contain matching concepts. Concepts are filed under topics, so topics are the filter dimension.'\n : 'Given the analysis concepts, pick the CATEGORIES that could contain matching concepts.',\n '- Be generous: missing a relevant topic corrupts the alignment; an extra topic only costs attention.',\n '- Only codes that appear in the index are valid.',\n JSON_ONLY,\n ].join('\\n');\n const selUser = [\n 'ANALYSIS CONCEPTS:',\n opts.concepts.map((c) => '- ' + c.name + ': ' + c.description.slice(0, 160)).join('\\n'),\n '',\n 'KNOWLEDGE TREE INDEX:',\n renderCategoryTopicIndex(catalog),\n '',\n hasTopics\n ? 'Return JSON: {\"relevant_topics\":[\"TOPIC_CODE\"]}'\n : 'Return JSON: {\"relevant_categories\":[\"CATEGORY_CODE\"]}',\n ].join('\\n');\n const selRes = await client.chat(\n [{ role: 'system', content: selSystem }, { role: 'user', content: selUser }],\n { temperature: 0, maxTokens: 4096 },\n );\n const sel = parseJsonBlock(selRes.content) as { relevant_categories?: string[]; relevant_topics?: string[] };\n // ONE filter dimension: topics when the tree files concepts under topics,\n // categories only as fallback. Never both mixed.\n const selTps = hasTopics ? (sel.relevant_topics || []).map(String).filter(Boolean) : [];\n const selCats = hasTopics ? [] : (sel.relevant_categories || []).map(String).filter(Boolean);\n log('STEP_2_5', 'LLM relevance pre-selection (' + (hasTopics ? 'topics' : 'categories') + '): ' + (hasTopics ? selTps.join(',') : selCats.join(',')));\n\n // ── Stage B (deterministic): filter tree concepts by that selection ──\n const shortlist = filterBySelection(catalog, selCats, selTps, opts.concepts);\n log('STEP_2_5', 'Filtered tree concepts: ' + shortlist.length + '/' + catalog.concepts.length + ' shortlisted for alignment');\n if (shortlist.length === 0) throw new Error('Topic/category pre-selection eliminated every tree concept — fail-closed');\n\n const system = [\n 'You align auto-derived learning concepts with an institutional knowledge tree.',\n 'For EACH input concept decide exactly one of:',\n ' 1. \"standardized\" - the concept teaches the SAME underlying knowledge as one tree concept. Applying a tree concept inside a specific product context (e.g. \"File-based persistence in a CLI app\") is STILL the tree concept if the core knowledge matches. Set tree_code to that concept\\'s code.',\n ' Adopt the tree\\'s terminology. Only propose new when the tree genuinely has NO concept teaching that knowledge (broader AND narrower both fail).',\n ' 2. \"proposed_new\" - no tree concept covers it at the same granularity. Propose an UPPER_SNAKE_CASE code (descriptive, stable, max 5 words) and a one-sentence definition.',\n ' If between 1 and 3 tree concepts are CLOSE but not exact, list their codes in possible_tree_matches for human review.',\n 'For a \"standardized\" decision ALSO return \"adopted_keywords\": the subset of that tree concept\\'s keywords (from the shortlist) that make sense for the course TECH STACK. Drop keywords that name tooling from other ecosystems (e.g. JS test runners for a Python course) — keep conceptual keywords even when spelled generically. Maximum 8, ordered most-relevant first.',\n 'Rules:',\n '- Judge by MEANING (definition + keywords), not by string similarity.',\n '- COVERAGE RULE: a \"standardized\" match must cover ALL primary dimensions of the input concept — every distinct aspect named in its title or description. A tree concept covering only ONE of several aspects (e.g. \"interpreting error messages\" for a concept about error handling AND user experience) is a PARTIAL match: decide \"proposed_new\" and list that tree code in possible_tree_matches.',\n '- Context-specific wording does NOT make a new concept: new concept = knowledge absent from the tree, not knowledge applied elsewhere.',\n '- Every input concept MUST receive exactly one decision. Never merge two input concepts into one tree code.',\n '- Prefer proposed_new over a wrong standardized match: a false match corrupts the curriculum.',\n JSON_ONLY,\n ].join('\\n');\n\n const user = [\n 'TECH STACK: ' + techStack,\n '',\n 'ANALYSIS CONCEPTS (to standardize):',\n JSON.stringify(opts.concepts.map((c) => ({ id: c.id, name: c.name, description: c.description.slice(0, 300), keywords: c.keywords.slice(0, 12) })), null, 1),\n '',\n 'KNOWLEDGE TREE SHORTLIST (pre-filtered, ' + shortlist.length + ' candidate concepts):',\n renderShortlist(shortlist),\n '',\n 'Return JSON: {\"decisions\":[{\"id\":\"<input id>\",\"decision\":\"standardized\",\"tree_code\":\"TREE_CODE\",\"adopted_keywords\":[\"kw1\",\"kw2\"],\"note\":\"one sentence\"},',\n ' {\"id\":\"<input id>\",\"decision\":\"proposed_new\",\"proposed_code\":\"PROPOSED_CODE\",\"proposed_definition\":\"...\",\"possible_tree_matches\":[\"CODE\"]}]}',\n ].join('\\n');\n\n const res = await client.chat(\n [{ role: 'system', content: system }, { role: 'user', content: user }],\n { temperature: 0, maxTokens: 8192 },\n );\n log('STEP_2_5', 'Standardization response received (provider ' + (res as unknown as { provider?: string }).provider + ')');\n\n const parsed = parseJsonBlock(res.content) as { decisions?: StandardizationDecision[] };\n const decisions = parsed.decisions ?? [];\n const byId = new Map(decisions.map((d) => [String(d.id), d]));\n\n const finalDecisions: StandardizationDecision[] = [];\n const proposals: Array<Record<string, unknown>> = [];\n for (const c of opts.concepts) {\n const d = byId.get(c.id);\n if (!d || (d.decision !== 'standardized' && d.decision !== 'proposed_new')) {\n // fail-closed: undecided concept cannot silently keep a nonstandard code\n throw new Error('Concept ' + c.id + ' (' + c.name + ') has no standardization decision — fail-closed');\n }\n if (d.decision === 'standardized') {\n const tc = catalog.concepts.find((x) => x.code === d.tree_code);\n if (!tc) throw new Error('Concept ' + c.id + ' standardized to unknown tree code ' + d.tree_code + ' — fail-closed');\n // adopted_keywords must come from the tree concept's own keywords — an\n // invented token would silently corrupt the registry (fail-closed).\n const treeKw = new Set(tc.keywords.map((k) => k.toLowerCase()));\n const adopted = (d.adopted_keywords || []).map((k) => String(k)).filter((k) => {\n if (treeKw.has(k.toLowerCase())) return true;\n throw new Error('Concept ' + c.id + ' adopted keyword \"' + k + '\" not in tree concept ' + tc.code + ' — fail-closed');\n });\n if (tc.keywords.length > 0 && adopted.length === 0) {\n throw new Error('Concept ' + c.id + ' standardized to ' + tc.code + ' without adopted_keywords — fail-closed');\n }\n finalDecisions.push({ ...d, id: c.id, tree_code: tc.code, adopted_keywords: adopted });\n warnings.push('Concept ' + c.id + ' standardized as ' + tc.code + ' (' + tc.name + '), adopted keywords: ' + adopted.join(', ') + (d.note ? ' — ' + d.note : ''));\n } else {\n const code = (d.proposed_code || '').toUpperCase().replace(/[^A-Z0-9_]/g, '_');\n if (!/^[A-Z][A-Z0-9_]*$/.test(code)) {\n throw new Error('Concept ' + c.id + ' proposed invalid code \"' + d.proposed_code + '\" — fail-closed');\n }\n finalDecisions.push({ ...d, id: c.id, proposed_code: code });\n proposals.push({\n code,\n name: c.name,\n description: d.proposed_definition || c.description.slice(0, 300),\n keywords: c.keywords,\n subject_codes: 'PY',\n category_codes: '',\n topic_codes: '',\n prerequisite_concept_codes: [],\n status: 'proposed',\n source_concept_id: c.id,\n possible_tree_matches: (d.possible_tree_matches || []).filter(Boolean),\n });\n warnings.push('Concept ' + c.id + ' proposed as NEW: ' + code + (d.possible_tree_matches?.length ? ' (near matches: ' + d.possible_tree_matches.join(', ') + ')' : ''));\n }\n }\n\n // Persist proposals separately for the later merge (never in the standard namespace)\n const outPath = proposalsPath || join(tmpdir(), 'domain-kit-debug', 'concept-proposals.json');\n try {\n mkdirSync(outPath.slice(0, outPath.lastIndexOf('/')), { recursive: true });\n writeFileSync(outPath, JSON.stringify({ generated_at: new Date().toISOString(), proposals }, null, 2));\n log('STEP_2_5', 'Proposals written: ' + proposals.length + ' -> ' + outPath);\n } catch (e) {\n warnings.push('Could not write proposals artifact: ' + (e instanceof Error ? e.message : String(e)));\n }\n\n return { decisions: finalDecisions, proposals, warnings, shortlistSize: shortlist.length, catalogSize: catalog.concepts.length };\n}\n","/**\n * Knowledge Graph Pipeline — generates knowledge_graph for concept-driven learning.\n *\n * Input: syllabus text, subject description, grade band\n * Output: KnowledgeGraph with concepts, problem_types, prerequisites, learning_path\n *\n * Includes:\n * - Cycle detection in prerequisite chains\n * - Topological sort for learning_path\n * - Multi-language syllabus support\n * - ULO/CIO/SIO depth control per concept\n */\n\nimport { assignConceptCodes, techTagFor, uloCode, cioCode, sioCode, cioActionSlug } from \"./loCodeStandard.js\";\nimport { createLlmClient, llmChatJson, type LlmClientConfig } from '../utils/llmClient';\nimport type { KnowledgeGraph, Concept, ConceptCategory, LearningPathStep } from '../schemas/knowledgeGraphSchema';\n\nexport interface KnowledgeGraphPipelineOptions {\n subject: string;\n description?: string;\n syllabusText?: string;\n gradeBand?: [number, number];\n domain?: string;\n /** Target technology for SIO keyword binding (e.g. \"python\", \"swift\"); auto-detected fallback applies. */\n techStack?: string;\n llmConfig?: LlmClientConfig;\n onProgress?: (step: string, message: string) => void;\n /** Path to mlo-knowlege-tree.tsv. When provided, STEP_2_5 standardizes every concept against the tree (fail-closed). */\n knowledgeTreePath?: string;\n /** Where to persist proposed-new concepts for the later merge. Default: tmpdir/domain-kit-debug/concept-proposals.json */\n proposalsPath?: string;\n}\n\nexport interface KnowledgeGraphPipelineResult {\n knowledgeGraph: KnowledgeGraph;\n warnings: string[];\n}\nimport { auditDepthLayers } from './depthAudit';\nimport { authorDepthLayersHierarchically } from './hierarchicalLoAuthoring';\nimport { loadKnowledgeTreeCatalog } from './knowledgeTreeCatalog';\nimport { standardizeConcepts } from './conceptStandardizer';\n\n\n// ─── Cycle Detection ──────────────────────────────────────────────────────────\n\n/**\n * Detect cycles in prerequisite graph using DFS.\n * Returns array of cycle paths if found, empty if no cycles.\n */\nfunction detectCycles(concepts: Concept[]): string[][] {\n const cycles: string[][] = [];\n const visited = new Set<string>();\n const inStack = new Set<string>();\n const path: string[] = [];\n\n function dfs(conceptId: string, prereqMap: Map<string, string[]>) {\n if (inStack.has(conceptId)) {\n // Found a cycle — extract cycle path\n const cycleStart = path.indexOf(conceptId);\n if (cycleStart >= 0) {\n cycles.push([...path.slice(cycleStart), conceptId]);\n }\n return;\n }\n if (visited.has(conceptId)) return;\n\n visited.add(conceptId);\n inStack.add(conceptId);\n path.push(conceptId);\n\n const prereqs = prereqMap.get(conceptId) || [];\n for (const prereq of prereqs) {\n dfs(prereq, prereqMap);\n }\n\n path.pop();\n inStack.delete(conceptId);\n }\n\n // Build reverse map: concept → its prerequisites\n const prereqMap = new Map<string, string[]>();\n for (const concept of concepts) {\n prereqMap.set(concept.id, concept.prerequisites || []);\n }\n\n for (const concept of concepts) {\n if (!visited.has(concept.id)) {\n dfs(concept.id, prereqMap);\n }\n }\n\n return cycles;\n}\n\n/**\n * Remove cycles by breaking the back-edge with lowest confidence.\n * For simplicity, we break the cycle at the concept that appears LAST in the original list.\n */\nfunction breakCycles(concepts: Concept[], cycles: string[][]): { fixed: Concept[]; removed: Array<{ from: string; to: string }> } {\n const removed: Array<{ from: string; to: string }> = [];\n const fixed = concepts.map(c => ({ ...c, prerequisites: [...(c.prerequisites || [])] }));\n\n for (const cycle of cycles) {\n // Remove the last edge in the cycle (concept → prerequisite)\n // The \"last\" concept in the cycle is the one whose prerequisite creates the back-edge\n if (cycle.length >= 2) {\n const breaker = cycle[cycle.length - 2]; // The concept that points back\n const target = cycle[cycle.length - 1]; // The prerequisite that creates cycle\n\n for (const concept of fixed) {\n if (concept.id === breaker) {\n concept.prerequisites = concept.prerequisites.filter(p => p !== target);\n removed.push({ from: breaker, to: target });\n }\n }\n }\n }\n\n return { fixed, removed };\n}\n\n/**\n * Topological sort using Kahn's algorithm.\n * Returns sorted concept IDs, or throws if there's still a cycle.\n */\nfunction topologicalSort(concepts: Concept[]): string[] {\n const inDegree = new Map<string, number>();\n const adjacency = new Map<string, string[]>();\n\n for (const concept of concepts) {\n inDegree.set(concept.id, 0);\n adjacency.set(concept.id, []);\n }\n\n for (const concept of concepts) {\n for (const prereq of concept.prerequisites || []) {\n // prereq → concept (prereq must come before concept)\n adjacency.get(prereq)?.push(concept.id);\n inDegree.set(concept.id, (inDegree.get(concept.id) || 0) + 1);\n }\n }\n\n const queue: string[] = [];\n for (const [id, degree] of inDegree) {\n if (degree === 0) queue.push(id);\n }\n\n const sorted: string[] = [];\n while (queue.length > 0) {\n const current = queue.shift()!;\n sorted.push(current);\n\n for (const neighbor of adjacency.get(current) || []) {\n const newDegree = (inDegree.get(neighbor) || 1) - 1;\n inDegree.set(neighbor, newDegree);\n if (newDegree === 0) queue.push(neighbor);\n }\n }\n\n if (sorted.length !== concepts.length) {\n // Still has cycle after breaking — shouldn't happen, but log warning\n console.warn(`[WARN] Topological sort incomplete: ${sorted.length}/${concepts.length} concepts sorted`);\n }\n\n return sorted;\n}\n\n// ─── ULO/CIO/SIO Depth Estimation ────────────────────────────────────────────\n\n/**\n * Estimate ULO/CIO/SIO depth level for a concept based on:\n * - Number of prerequisites (more prereqs = deeper concept)\n * - Bloom level of associated problem types\n * - Position in learning path (earlier = more foundational)\n */\nfunction estimateConceptDepth(\n concept: Concept,\n position: number,\n totalConcepts: number,\n): { suggestedDepth: 'ulo' | 'cio' | 'sio'; rationale: string } {\n const prereqCount = (concept.prerequisites || []).length;\n const problemTypes = concept.problem_types || [];\n const maxBloom = problemTypes.reduce((max, pt) => {\n const levels = ['Remember', 'Understand', 'Apply', 'Analyze', 'Evaluate', 'Create'];\n const idx = levels.indexOf(pt.bloom_level || 'Understand');\n return idx > max ? idx : max;\n }, 0);\n\n // Position ratio: 0 = first concept, 1 = last concept\n const positionRatio = totalConcepts > 1 ? position / (totalConcepts - 1) : 0;\n\n // Score: higher = deeper\n const depthScore = (prereqCount * 0.3) + (maxBloom * 0.15) + (positionRatio * 0.3);\n\n if (depthScore < 0.3) {\n return { suggestedDepth: 'ulo', rationale: `Low complexity (${prereqCount} prereqs, bloom=${maxBloom}, position=${(positionRatio * 100).toFixed(0)}%)` };\n } else if (depthScore < 0.6) {\n return { suggestedDepth: 'cio', rationale: `Medium complexity (${prereqCount} prereqs, bloom=${maxBloom}, position=${(positionRatio * 100).toFixed(0)}%)` };\n } else {\n return { suggestedDepth: 'sio', rationale: `High complexity (${prereqCount} prereqs, bloom=${maxBloom}, position=${(positionRatio * 100).toFixed(0)}%)` };\n }\n}\n\n// ─── Main Pipeline ───────────────────────────────────────────────────────────\n\n/**\n * Generate a KnowledgeGraph from syllabus/description via LLM.\n */\nexport async function generateKnowledgeGraph(\n options: KnowledgeGraphPipelineOptions,\n): Promise<KnowledgeGraphPipelineResult> {\n const { subject, description, syllabusText, gradeBand, domain, techStack, llmConfig, onProgress } = options;\n const warnings: string[] = [];\n\n const log = (step: string, msg: string) => {\n console.log(`[KG-${step}] ${msg}`);\n onProgress?.(step, msg);\n };\n\n // ─── Step 1: Decompose subject into concepts ─────────────────────────────\n log('STEP_1', 'Decomposing subject into concepts...');\n\n const client = createLlmClient(llmConfig);\n\n // Truncate syllabus with warning\n const maxSyllabusChars = parseInt(process.env.KG_MAX_SYLLABUS_CHARS || '16000', 10);\n let truncatedSyllabus = '';\n if (syllabusText) {\n if (syllabusText.length > maxSyllabusChars) {\n truncatedSyllabus = syllabusText.slice(0, maxSyllabusChars);\n warnings.push(`Syllabus truncated from ${syllabusText.length} to ${maxSyllabusChars} chars — may miss some concepts`);\n } else {\n truncatedSyllabus = syllabusText;\n }\n }\n\n const systemPrompt = (\n 'You are an expert curriculum designer. Decompose the given subject into a structured '\n + 'knowledge graph with concepts, prerequisites, and problem types.\\n\\n'\n + 'CRITICAL RULES:\\n'\n + '1. Each concept MUST have the three depth layers, authored against this CONTRACT:\\n'\n + ' - ulo (WHAT + WHY): bound to the CONCEPT\\u0027s intrinsic NATURE. It explains what the\\n'\n + ' concept is and why it exists — the problem it solves in principle. It must be\\n'\n + ' TECHNOLOGY-AGNOSTIC: never name a concrete library, API, function, file format,\\n'\n + ' tool or language feature. Typical assessment level: Remember / Understand.\\n'\n + ' - cio (HOW): the MECHANISM — how the concept works and solves that problem, step\\n'\n + ' by step. Still bound to the concept\\u0027s nature: more concrete than the ULO, but\\n'\n + ' NOT tied to one specific technology (no concrete API names). CIO capability is\\n'\n + ' assessed INDIRECTLY, through completing contextual work, not in isolation.\\n'\n + ' - sio (IMPLEMENTATION): an array of 2-4 items. EVERY item MUST reference concrete\\n'\n + ' KEYWORDS/technologies (a real API, function, module, file, or named pattern) and\\n'\n + ' describe a completable, context-specific implementation task. Application,\\n'\n + ' Analysis and Creation skills are assessed INDIRECTLY through completing these\\n'\n + ' items. There is NO fixed Bloom ceiling for a layer — but concreteness MUST\\n'\n + ' strictly increase: SIO more technology-bound than CIO, CIO more concrete than ULO.\\n'\n + ' - prerequisites: concept IDs that must be learned first (MUST NOT create cycles)\\n'\n + ' - problem_types: 2-4 problem types with bloom_level and difficulty. Remember and\\n'\n + ' Understand problem types test the ULO/CIO directly; Apply-and-above types are\\n'\n + ' proxies for SIO completion in context.\\n'\n + ' - techniques: methods, formulas, tools\\n'\n + '2. Prerequisite chains MUST be acyclic (no concept can depend on itself or create a loop)\\n'\n + '3. Concepts should be ordered by prerequisite dependency (topological sort)\\n'\n + '4. Problem types should range from Remember to Apply (not all at same level)\\n'\n + '5. Group concepts into categories (chapters/sections)\\n'\n + '6. ALL text in ENGLISH (even if input is Vietnamese)\\n'\n + '7. NEVER invent concepts not present in the syllabus\\n'\n + '8. Return JSON matching the KnowledgeGraphSchema'\n );\n\n const userPrompt = `Subject: ${subject}\\n${description ? `Description: ${description}` : ''}\\n${truncatedSyllabus ? `Syllabus:\\n${truncatedSyllabus}` : ''}\\n${gradeBand ? `Grade band: ${gradeBand[0]}-${gradeBand[1]}` : ''}\\n${domain ? `Domain: ${domain}` : ''}\\n\\nReturn JSON:\\n{\\n \"subject\": {\\n \"id\": \"${subject.toLowerCase().replace(/\\s+/g, '-').slice(0, 30)}\",\\n \"name\": \"${subject}\",\\n \"description\": \"...\",\\n \"domain\": \"${domain || 'other'}\",\\n \"grade_band\": ${gradeBand ? `[${gradeBand[0]}, ${gradeBand[1]}]` : '[6, 12]'}\\n },\\n \"concepts\": [\\n {\\n \"id\": \"C1\",\\n \"name\": \"Concept name\",\\n \"description\": \"Brief description\",\\n \"category\": \"category_id\",\\n \"ulo\": \"WHAT + WHY in technology-agnostic language: what the concept is and the problem it exists to solve. No library/API/tool names.\",\\n \"cio\": \"HOW the mechanism works, still technology-agnostic but more concrete than the ULO.\",\\n \"sio\": [\"Concrete task naming a REAL API/function/module/file from the target technology, completable end to end\", \"Another technology-bound task using a different concrete keyword\"],\\n \"prerequisites\": [],\\n \"estimated_minutes\": 30,\\n \"problem_types\": [\\n {\\n \"id\": \"PT-C1-01\",\\n \"name\": \"Problem type name\",\\n \"description\": \"What this problem type tests\",\\n \"bloom_level\": \"Remember\",\\n \"difficulty\": \"easy\",\\n \"estimated_minutes\": 10\\n }\\n ],\\n \"techniques\": [\"technique 1\", \"technique 2\"],\\n \"common_mistakes\": [\"mistake 1\"]\\n }\\n ],\\n \"categories\": [\\n {\\n \"id\": \"cat1\",\\n \"name\": \"Category name\",\\n \"description\": \"Category description\",\\n \"concept_ids\": [\"C1\", \"C2\"],\\n \"order\": 1\\n }\\n ],\\n \"learning_path\": [\\n {\"concept_id\": \"C1\", \"order\": 1, \"depends_on\": []},\\n {\"concept_id\": \"C2\", \"order\": 2, \"depends_on\": [\"C1\"]}\\n ]\\n}`;\n\n const result = await llmChatJson(client, systemPrompt, userPrompt, {\n temperature: 0.1,\n maxTokens: parseInt(process.env.KG_MAX_TOKENS || '65536', 10),\n });\n\n // ─── Step 2: Validate and clean ──────────────────────────────────────────\n log('STEP_2', 'Validating and cleaning knowledge graph...');\n\n const concepts = (result.concepts || []) as Concept[];\n const categories = (result.categories || []) as ConceptCategory[];\n // Keyword registry (fail-closed): every concept MUST carry a non-empty\n // keyword set — it drives the keyword-progression ledger and the SIO binding\n // audit downstream. LLM output is top-up (description tokens), never empty.\n {\n const STOP = new Set(['and', 'the', 'for', 'with', 'from', 'that', 'this', 'into', 'when', 'while', 'using', 'their', 'your', 'each', 'how', 'why', 'what', 'between', 'through', 'about']);\n const tokensFrom = (text: string): string[] => text\n .toLowerCase()\n .replace(/[^a-z0-9\\s-]/g, ' ')\n .split(/\\s+/)\n .filter(w => w.length >= 4 && !STOP.has(w));\n for (const c of concepts) {\n const existing = (c.keywords || []).map(k => String(k).trim()).filter(Boolean);\n if (existing.length === 0) {\n const derived = [...new Set([...tokensFrom(c.name), ...tokensFrom(c.description || '')])].slice(0, 5);\n if (derived.length === 0) {\n throw new Error('Concept ' + c.id + ' (' + c.name + ') has no keywords and none could be derived from name/description — fail-closed');\n }\n c.keywords = derived;\n warnings.push('Concept ' + c.id + ': empty keyword set - derived ' + derived.join(', ') + ' from name/description');\n } else {\n c.keywords = existing;\n }\n }\n }\n const rawPath = result.learning_path as Array<Record<string, unknown>> | undefined;\n let learningPath: LearningPathStep[] = (rawPath || []).map((s: Record<string, unknown>) => ({\n concept_id: String(s.concept_id || ''),\n order: Number(s.order || 0),\n depends_on: Array.isArray(s.depends_on) ? s.depends_on.map(String) : [],\n milestone_name: String(s.milestone_name || ''),\n }));\n\n // Validate prerequisites reference existing concepts\n const conceptIds = new Set(concepts.map(c => c.id));\n for (const concept of concepts) {\n for (const prereq of concept.prerequisites || []) {\n if (!conceptIds.has(prereq)) {\n warnings.push(`Concept ${concept.id} references non-existent prerequisite ${prereq} — removed`);\n concept.prerequisites = (concept.prerequisites || []).filter(p => p !== prereq);\n }\n }\n }\n\n // ─── Step 2.5: Standardize concepts against the knowledge tree ───────────\n // keyword -> escalate -> concept (upstream) -> HERE: LLM standardization vs\n // tree catalog (deterministic category pre-filter) -> downstream steps use\n // standardized / proposed codes. Fail-closed.\n if (options.knowledgeTreePath) {\n const catalog = loadKnowledgeTreeCatalog(options.knowledgeTreePath);\n log('STEP_2_5', 'Knowledge tree loaded: ' + catalog.concepts.length + ' concepts from ' + catalog.path.split('/').pop());\n const std = await standardizeConcepts({\n client,\n concepts: concepts.map((c) => ({\n id: c.id,\n name: c.name,\n description: c.description || '',\n keywords: c.keywords || [],\n })),\n catalog,\n techStack,\n proposalsPath: options.proposalsPath,\n onProgress: log,\n });\n warnings.push(...std.warnings);\n const codeByStd = new Map(std.decisions.map((d) => [d.id, d]));\n for (const c of concepts) {\n const d = codeByStd.get(c.id);\n if (!d) throw new Error('Concept ' + c.id + ' missing standardization decision — fail-closed');\n if (d.decision === 'standardized') {\n c.standardization = 'standardized';\n c.tree_code = d.tree_code;\n c.code = d.tree_code;\n const tc = catalog.concepts.find((x) => x.code === d.tree_code);\n if (tc) {\n // Keyword enrichment is LLM-driven: only the keywords the standardizer\n // ADOPTED for this tech stack join the registry (no code-side blacklist).\n for (const k of d.adopted_keywords || []) {\n if (!(c.keywords || []).some((x) => x.toLowerCase() === k.toLowerCase())) {\n c.keywords = [...(c.keywords || []), k];\n }\n }\n c.tree_prerequisites = tc.prerequisiteCodes;\n }\n } else {\n c.standardization = 'proposed_new';\n c.code = d.proposed_code;\n }\n }\n // Seed internal prerequisite edges from the tree's prerequisite codes:\n // only mapped when the referenced tree concept is part of THIS analysis.\n const idByTreeCode = new Map(concepts.filter((c) => c.tree_code).map((c) => [c.tree_code as string, c.id]));\n for (const c of concepts) {\n for (const tp of c.tree_prerequisites || []) {\n const target = idByTreeCode.get(tp);\n if (target && target !== c.id && !(c.prerequisites || []).includes(target)) {\n c.prerequisites = [...(c.prerequisites || []), target];\n warnings.push('Prereq seeded from tree: ' + c.id + ' <- ' + tp + ' (' + target + ')');\n }\n }\n }\n log('STEP_2_5', 'Standardized: ' + std.decisions.filter((d) => d.decision === 'standardized').length\n + ', proposed new: ' + std.decisions.filter((d) => d.decision === 'proposed_new').length);\n }\n\n // ─── Step 3: Cycle Detection ─────────────────────────────────────────────\n log('STEP_3', 'Checking for prerequisite cycles...');\n\n const cycles = detectCycles(concepts);\n if (cycles.length > 0) {\n log('STEP_3', `Found ${cycles.length} cycle(s) in prerequisite chain — breaking cycles`);\n for (const cycle of cycles) {\n warnings.push(`Cycle detected: ${cycle.join(' → ')} — breaking at weakest edge`);\n }\n\n const { fixed, removed } = breakCycles(concepts, cycles);\n // Replace concepts with cycle-free versions\n for (let i = 0; i < concepts.length; i++) {\n const fixedConcept = fixed.find(f => f.id === concepts[i].id);\n if (fixedConcept) {\n concepts[i] = { ...concepts[i], prerequisites: fixedConcept.prerequisites };\n }\n }\n\n for (const { from, to } of removed) {\n warnings.push(`Removed prerequisite edge: ${from} → ${to} (cycle breaker)`);\n }\n }\n\n // ─── Step 4: Topological Sort ────────────────────────────────────────────\n log('STEP_4', 'Topological sort of concepts...');\n\n const sortedIds = topologicalSort(concepts);\n\n // Rebuild learning_path from topological sort\n learningPath = sortedIds.map((id, idx) => {\n const concept = concepts.find(c => c.id === id);\n return {\n concept_id: id,\n order: idx + 1,\n depends_on: concept?.prerequisites || [],\n milestone_name: '',\n };\n });\n\n // ─── Step 5: Hierarchical ULO/CIO/SIO authoring (ported from knowledge-tree) ──\n log('STEP_5', 'Authoring ULO/CIO/SIO depth layers hierarchically...');\n\n {\n const lo = await authorDepthLayersHierarchically(\n client,\n concepts.map((c) => ({ id: c.id, name: c.name, description: c.description, keywords: c.keywords })),\n techStack || (domain === 'software' || domain === 'technology' ? 'python' : (domain || 'general')),\n warnings,\n );\n const codeByConceptId = assignConceptCodes(concepts.map((c) => ({ id: c.id, name: c.name })));\n const techTag = techTagFor(techStack || (domain === 'software' || domain === 'technology' ? 'python' : (domain || 'general')));\n for (const concept of concepts) {\n concept.ulo = lo.uloByConcept[concept.id] || concept.ulo || '';\n concept.cio = lo.cioByConcept[concept.id] || concept.cio || '';\n if (lo.sioByConcept[concept.id] && lo.sioByConcept[concept.id].length > 0) {\n concept.sio = lo.sioByConcept[concept.id];\n }\n // Production-standard codes + statement clause (deterministic post-pass).\n // A tree-standardized or proposed code from STEP_2_5 wins — the generated\n // code only fills concepts the standardizer never saw.\n concept.code = concept.code || codeByConceptId[concept.id];\n concept.ulo_code = concept.ulo ? uloCode(concept.code!) : concept.ulo_code;\n concept.cio_code = concept.cio ? cioCode(concept.code!, 1, cioActionSlug(concept.cio)) : concept.cio_code;\n concept.sio_codes = concept.sio.length > 0\n ? concept.sio.map((_, i) => sioCode(techTag, concept.code!, i + 1))\n : concept.sio_codes;\n }\n log('STEP_5', 'Depth layers authored: ' + concepts.length + ' concepts, audit ' +\n (lo.audits.filter((a) => a.passed).length) + '/' + concepts.length + ' passed');\n }\n\n // Validate learning_path references\n for (const step of learningPath) {\n if (!conceptIds.has(step.concept_id)) {\n warnings.push(`Learning path references non-existent concept ${step.concept_id}`);\n }\n }\n\n log('STEP_2', `Validated ${concepts.length} concepts, ${categories.length} categories, ${learningPath.length} learning path steps`);\n\n return {\n knowledgeGraph: {\n schema_version: 1,\n type: 'knowledge_graph',\n subject: result.subject as KnowledgeGraph['subject'],\n concepts,\n categories,\n learning_path: learningPath,\n },\n warnings,\n };\n}\n","/**\n * Hybrid Graph Pipeline - generates hybrid_graph combining project + knowledge.\n *\n * STEP_1 generates feature-concept links. STEP_2 decomposes the build into\n * PROGRESSIVE COMPLETION PHASES (cross-feature): each phase describes what the\n * product can demonstrably do once complete, owns every feature built in it\n * (each feature in EXACTLY one phase), and declares which concepts are\n * introduced (new) or revisited at higher depth (advanced) at the phase start.\n * Later phases depend on earlier ones and may only raise the knowledge level -\n * verified against the concept prerequisite graph (fail-closed).\n */\n\nimport { createLlmClient, llmChatJson, type LlmClientConfig } from '../utils/llmClient';\nimport type { ProjectGraph } from '../schemas/projectGraphSchema';\nimport type { KnowledgeGraph } from '../schemas/knowledgeGraphSchema';\nimport type {\n HybridGraph, ProjectConceptLink, DevelopmentPhase, ConceptIntroduction,\n} from '../schemas/hybridGraphSchema';\n\nexport interface HybridGraphPipelineOptions {\n projectGraph: ProjectGraph;\n knowledgeGraph: KnowledgeGraph;\n llmConfig?: LlmClientConfig;\n onProgress?: (step: string, message: string) => void;\n}\n\nexport interface HybridGraphPipelineResult {\n hybridGraph: HybridGraph;\n warnings: string[];\n}\n\nexport async function generateHybridGraph(\n options: HybridGraphPipelineOptions,\n): Promise<HybridGraphPipelineResult> {\n const { projectGraph, knowledgeGraph, llmConfig, onProgress } = options;\n const warnings: string[] = [];\n\n const log = (step: string, msg: string) => {\n console.log('[HG-' + step + '] ' + msg);\n onProgress?.(step, msg);\n };\n\n const features = projectGraph.features || [];\n const concepts = knowledgeGraph.concepts || [];\n\n if (features.length === 0 || concepts.length === 0) {\n warnings.push('No features or concepts to link');\n return {\n hybridGraph: {\n schema_version: 1,\n type: 'hybrid_graph',\n project_graph: projectGraph,\n knowledge_graph: knowledgeGraph,\n links: [],\n phases: [],\n description: '',\n total_project_minutes: 0,\n total_concept_minutes: 0,\n estimated_total_minutes: 0,\n },\n warnings,\n };\n }\n\n const client = createLlmClient(llmConfig);\n\n const featuresList = features.map(f =>\n '- ' + f.id + ': ' + f.name + ' - ' + (f.description || '') +\n ' (keywords: ' + (f.steps || []).flatMap(s => s.keywords || []).slice(0, 5).join(', ') + ')',\n ).join('\\n');\n\n const conceptsList = concepts.map(c =>\n '- ' + c.id + ': ' + c.name + ' - ULO: ' + (c.ulo || '').slice(0, 100) +\n ' (prerequisites: ' + (c.prerequisites || []).join(', ') + ')',\n ).join('\\n');\n\n const systemPrompt = (\n 'You are a curriculum architect. Link project features to knowledge concepts.\\n'\n + 'For each feature, determine which concepts it requires or demonstrates.\\n\\n'\n + 'RULES:\\n'\n + '1. Each link must have a relationship type: requires | demonstrates | applies | extends\\n'\n + '2. depth indicates how deeply the feature needs the concept:\\n'\n + ' - ulo: feature only needs WHAT+WHY understanding\\n'\n + ' - cio: feature needs HOW understanding\\n'\n + ' - sio: feature needs specific implementation knowledge\\n'\n + '3. estimated_prereq_minutes: how many minutes of concept learning before this feature\\n'\n + '4. Not every feature needs every concept - only create meaningful links\\n'\n + '5. Return JSON object with a links array'\n );\n\n const userPrompt = 'FEATURES:\\n' + featuresList + '\\n\\nCONCEPTS:\\n' + conceptsList + '\\n\\n'\n + 'Create links between features and concepts. Return JSON.\\n';\n\n const result = await llmChatJson(client, systemPrompt, userPrompt, {\n temperature: 0.1,\n maxTokens: 16384,\n });\n\n const rawLinks = (result.links || []) as Array<Record<string, unknown>>;\n\n const featureIds = new Set(features.map(f => f.id));\n const conceptIds = new Set(concepts.map(c => c.id));\n const validLinks: ProjectConceptLink[] = [];\n\n for (const link of rawLinks) {\n const fid = String(link.feature_id || '');\n const cid = String(link.concept_id || '');\n if (!featureIds.has(fid)) {\n warnings.push('Link references non-existent feature ' + fid);\n continue;\n }\n if (!conceptIds.has(cid)) {\n warnings.push('Link references non-existent concept ' + cid);\n continue;\n }\n validLinks.push({\n feature_id: fid,\n concept_id: cid,\n relationship: (link.relationship as 'requires' | 'demonstrates' | 'applies' | 'extends') || 'requires',\n depth: (link.depth as 'ulo' | 'cio' | 'sio') || 'cio',\n description: String(link.description || ''),\n estimated_prereq_minutes: Number(link.estimated_prereq_minutes) || 0,\n phase_id: '',\n });\n }\n\n log('STEP_1', 'Generated ' + validLinks.length + ' feature-concept links');\n\n const phases = await decomposePhases({\n features, concepts, links: validLinks, client, log, warnings,\n });\n const phaseByFeature = new Map<string, string>();\n for (const ph of phases) {\n for (const fid of ph.feature_ids) phaseByFeature.set(fid, ph.id);\n }\n for (const link of validLinks) link.phase_id = phaseByFeature.get(link.feature_id) || '';\n\n log('STEP_3', 'Calculating totals...');\n\n const totalProjectMinutes = features.reduce((sum, f) => {\n const featureMinutes = (f.steps || []).reduce((s, step) => s + (step.effort?.estimated_minutes || 15), 0);\n return sum + featureMinutes;\n }, 0);\n\n const totalConceptMinutes = concepts.reduce((sum, c) => sum + (c.estimated_minutes || 30), 0);\n\n const prereqMinutesByConcept = new Map<string, number>();\n for (const link of validLinks) {\n const mins = link.estimated_prereq_minutes || 0;\n if (mins > 0) {\n const existing = prereqMinutesByConcept.get(link.concept_id) || 0;\n prereqMinutesByConcept.set(link.concept_id, Math.max(existing, mins));\n }\n }\n const totalPrereqMinutes = Array.from(prereqMinutesByConcept.values()).reduce((a, b) => a + b, 0);\n\n return {\n hybridGraph: {\n schema_version: 1,\n type: 'hybrid_graph',\n project_graph: projectGraph,\n knowledge_graph: knowledgeGraph,\n links: validLinks,\n phases,\n description: 'Progressive completion path: ' + phases.length + ' phases, ' + features.length + ' features, ' + concepts.length + ' concepts',\n total_project_minutes: totalProjectMinutes,\n total_concept_minutes: totalConceptMinutes,\n estimated_total_minutes: totalProjectMinutes + totalPrereqMinutes,\n },\n warnings,\n };\n}\n\ninterface DecomposePhasesArgs {\n features: ProjectGraph['features'];\n concepts: KnowledgeGraph['concepts'];\n links: ProjectConceptLink[];\n client: ReturnType<typeof createLlmClient>;\n log: (step: string, msg: string) => void;\n warnings: string[];\n}\nfunction auditPhasePlan(\n plan: Array<Record<string, unknown>>,\n features: Array<{ id: string }>,\n concepts: Array<{ id: string; prerequisites?: string[] }>,\n links: Array<{ feature_id: string; concept_id: string }>,\n warnings: string[],\n log: (step: string, msg: string) => void,\n): { phases: DevelopmentPhase[]; errors: string[] } {\n const knownFeatureIds = new Set(features.map(f => f.id));\n const knownConceptIds = new Set(concepts.map(c => c.id));\n const prereqOf = new Map<string, string[]>();\n for (const c of concepts) prereqOf.set(c.id, (c.prerequisites || []).filter(p => knownConceptIds.has(p)));\n\n const phases: DevelopmentPhase[] = [];\n const featurePhase = new Map<string, string>();\n const newIntroPhase = new Map<string, number>();\n const errors: string[] = [];\n\n plan.forEach((rp, idx) => {\n const id = String(rp.id || ('PH' + (idx + 1)));\n const order = idx + 1;\n const name = String(rp.name || ('Phase ' + order)).slice(0, 80);\n const productCompletion = String(rp.product_completion || '').trim();\n const rawFeatureIds = Array.isArray(rp.feature_ids) ? rp.feature_ids.map(String) : [];\n const rawIntros = Array.isArray(rp.introduces) ? (rp.introduces as Array<Record<string, unknown>>) : [];\n\n if (!productCompletion) {\n errors.push('Phase ' + id + ': product_completion is empty - every phase must describe the product completion level');\n }\n\n const featureIdsForPhase: string[] = [];\n for (const fid of rawFeatureIds) {\n if (!knownFeatureIds.has(fid)) {\n errors.push('Phase ' + id + ': unknown feature ' + fid);\n continue;\n }\n if (featurePhase.has(fid)) {\n errors.push('Feature ' + fid + ' assigned to both ' + featurePhase.get(fid) + ' and ' + id + ' - each feature must belong to exactly one phase');\n continue;\n }\n featurePhase.set(fid, id);\n featureIdsForPhase.push(fid);\n }\n\n const introductions: ConceptIntroduction[] = [];\n for (const ri of rawIntros) {\n const cid = String(ri.concept_id || '');\n if (!knownConceptIds.has(cid)) {\n errors.push('Phase ' + id + ': introduces unknown concept ' + cid);\n continue;\n }\n const aspect = String(ri.aspect || 'new') === 'advanced' ? 'advanced' : 'new';\n if (aspect === 'advanced') {\n const first = newIntroPhase.get(cid);\n if (first === undefined) {\n errors.push('Phase ' + id + ': advanced introduction of ' + cid + ' before any new introduction - revisit requires prior introduction');\n continue;\n }\n if (first >= order) {\n errors.push('Phase ' + id + ': advanced introduction of ' + cid + ' must come after its new introduction in phase ' + first);\n continue;\n }\n } else if (newIntroPhase.has(cid)) {\n errors.push('Phase ' + id + ': duplicate new introduction of ' + cid + ' (already introduced in phase ' + newIntroPhase.get(cid) + ')');\n continue;\n } else {\n newIntroPhase.set(cid, order);\n }\n for (const pre of prereqOf.get(cid) || []) {\n if (!newIntroPhase.has(pre)) {\n errors.push('Phase ' + id + ': concept ' + cid + ' introduced before its prerequisite ' + pre + ' is introduced - violates the prerequisite chain');\n }\n }\n introductions.push({ concept_id: cid, aspect, note: String(ri.note || '') });\n }\n\n phases.push({\n id, order, name,\n product_completion: productCompletion,\n feature_ids: featureIdsForPhase,\n introduces: introductions,\n });\n });\n\n const missing = features.map(f => f.id).filter(fid => !featurePhase.has(fid));\n if (missing.length > 0) {\n errors.push('Features not assigned to any phase: ' + missing.join(', '));\n }\n const firstConsumerPhase = new Map<string, number>();\n const phaseOrderByFeature = new Map<string, number>();\n for (const ph of phases) for (const fid of ph.feature_ids) phaseOrderByFeature.set(fid, ph.order);\n for (const l of links) {\n const po = phaseOrderByFeature.get(l.feature_id);\n if (po === undefined) continue;\n const cur = firstConsumerPhase.get(l.concept_id);\n if (cur === undefined || po < cur) firstConsumerPhase.set(l.concept_id, po);\n }\n for (const [cid, consumerOrder] of firstConsumerPhase) {\n const intro = newIntroPhase.get(cid);\n if (intro === undefined) {\n errors.push('Concept ' + cid + ' is consumed from phase ' + consumerOrder + ' but never introduced in any phase');\n } else if (intro > consumerOrder) {\n errors.push('Concept ' + cid + ' introduced in phase ' + intro + ' but first consumed in phase ' + consumerOrder + ' - introduction must come no later than first consumption');\n }\n }\n\n return { phases, errors };\n}\n\nasync function decomposePhases(args: DecomposePhasesArgs): Promise<DevelopmentPhase[]> {\n const { features, concepts, links, client, log, warnings } = args;\n\n const featureList = features.map(f =>\n '- ' + f.id + ': ' + f.name + ' - ' + (f.description || '').slice(0, 120),\n ).join('\\n');\n\n const conceptList = concepts.map(c =>\n '- ' + c.id + ': ' + c.name + ' (prerequisites: ' + ((c.prerequisites || []).join(', ') || 'none') + ')',\n ).join('\\n');\n\n const linkList = links.map(l =>\n '- ' + l.feature_id + ' -> ' + l.concept_id + ' (' + l.depth + ')',\n ).join('\\n') || '(none)';\n\n const systemPrompt = (\n 'You decompose a software project build into PROGRESSIVE COMPLETION PHASES for learning purposes.\\n\\n'\n + 'A phase is NOT a feature and NOT a milestone list: it is a cross-feature slice of the\\n'\n + 'product whose completion yields a DEMONSTRABLY more complete product. Build up gradually:\\n'\n + 'the product grows feature by feature across phases, and each phase adds its features to\\n'\n + 'what previous phases already built.\\n\\n'\n + 'RULES:\\n'\n + '1. Every feature must be assigned to EXACTLY ONE phase (no feature reused, none skipped).\\n'\n + '2. Phases are ordered; later phases depend on earlier ones and yield a more complete product.\\n'\n + '3. product_completion describes concretely what the product can DO once the phase is done.\\n'\n + '4. introduces lists which concepts the phase must teach BEFORE its feature work starts:\\n'\n + ' - aspect new: first time the concept appears in the course\\n'\n + ' - aspect advanced: a concept introduced in an EARLIER phase, revisited here at a\\n'\n + ' higher depth (an advanced aspect of the same concept, e.g. validation rules on top\\n'\n + ' of basic data modeling). Use the note field to say which aspect.\\n'\n + '5. A concept MUST be introduced (new) no later than the first phase that consumes it.\\n'\n + '6. A concept must not be introduced before its own prerequisites are introduced.\\n'\n + '7. Typically 3-6 phases for a small project; keep phases balanced.\\n'\n + '8. Phase 1 usually covers project setup/foundation features plus the first minimal slice.\\n'\n + '9. Return JSON only.'\n );\n\n const baseUserPrompt = 'FEATURES:\\n' + featureList + '\\n\\nCONCEPTS:\\n' + conceptList\n + '\\n\\nFEATURE-CONCEPT LINKS:\\n' + linkList + '\\n\\n'\n + 'Return JSON with a phases array. Each phase: { id: PH1, name, product_completion, feature_ids: [F0, F1], introduces: [{ concept_id: C1, aspect: new or advanced, note }] }.\\n';\n\n // Repair loop (same fail-closed philosophy as STEP_5 depth authoring): the audit below is\n // deterministic, so violations are fed back verbatim and the model rewrites the plan.\n const MAX_DECOMPOSE_ATTEMPTS = 3;\n let auditErrors: string[] = [];\n let phases: DevelopmentPhase[] = [];\n let rawPhases: Array<Record<string, unknown>> = [];\n for (let attempt = 1; attempt <= MAX_DECOMPOSE_ATTEMPTS; attempt++) {\n const userPrompt = attempt === 1\n ? baseUserPrompt\n : baseUserPrompt\n + '\\nYOUR PREVIOUS PLAN VIOLATED THESE CONTRACT RULES (fix ALL of them):\\n'\n + auditErrors.map((e) => '- ' + e).join('\\n')\n + '\\nReturn a corrected full phases array.\\n';\n\n const result = await llmChatJson(client, systemPrompt, userPrompt, {\n temperature: 0.1,\n maxTokens: 16384,\n });\n\n rawPhases = (result.phases || []) as Array<Record<string, unknown>>;\n if (rawPhases.length === 0) {\n if (attempt === MAX_DECOMPOSE_ATTEMPTS) {\n throw new Error('Phase decomposition returned zero phases - fail-closed abort');\n }\n auditErrors = ['Returned zero phases'];\n continue;\n }\n\n ({ phases, errors: auditErrors } = auditPhasePlan(rawPhases, features, concepts, links, warnings, log));\n if (auditErrors.length === 0) break;\n if (attempt < MAX_DECOMPOSE_ATTEMPTS) {\n log('STEP_2', 'Contract violations (' + auditErrors.length + ') - repairing (attempt ' + (attempt + 1) + '/' + MAX_DECOMPOSE_ATTEMPTS + ')');\n }\n }\n if (auditErrors.length > 0) {\n throw new Error(\n 'Phase decomposition violated the progressive-completion contract (' + auditErrors.length + ' issue(s)):\\n'\n + auditErrors.map((e) => ' - ' + e).join('\\n')\n + '\\nRe-run the pipeline - a phase model that cannot be trusted is worse than no output.',\n );\n }\n\n if (phases.length === 1 && features.length > 2) {\n warnings.push('Only one phase for ' + features.length + ' features - progressive decomposition likely too coarse');\n }\n\n log('STEP_2', 'Decomposed into ' + phases.length + ' phases: '\n + phases.map(p => p.id + '(' + p.feature_ids.length + 'F/' + p.introduces.length + 'K)').join(', '));\n return phases;\n}\n"]}
|
package/dist/chunk-F4RZNBOE.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/extractors/fileSelector.ts","../src/utils/fileUtils.ts","../src/pipeline/projectGraphPipeline.ts"],"names":["relative"],"mappings":";;;;;;;;;;AAsBA,eAAsB,kBAAA,CACpB,SAAA,EACA,IAAA,EACA,SAAA,EACA,SAAA,EAC8B;AAE9B,EAAA,IAAI,SAAA,CAAU,UAAU,EAAA,EAAI;AAC1B,IAAA,OAAO,EAAE,QAAA,EAAU,SAAA,EAAW,SAAA,EAAW,yBAAA,EAA0B;AAAA,EACrE;AAEA,EAAA,MAAM,MAAA,GAAS,gBAAgB,SAAS,CAAA;AAGxC,EAAA,MAAM,SAAA,GAAY,cAAc,SAAS,CAAA;AAEzC,EAAA,MAAM,YAAA,GACJ,wyBAAA;AAcF,EAAA,MAAM,UAAA,GACJ,iBAAiB,IAAI;AAAA,YAAA,EACJ,SAAS;;AAAA,WAAA,EACV,UAAU,MAAM,CAAA;AAAA,EAAa,SAAS;;AAAA,wDAAA,CAAA;AAIxD,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,MAAM,WAAA,CAAY,MAAA,EAAQ,cAAc,UAAA,EAAY;AAAA,MACjE,WAAA,EAAa,GAAA;AAAA,MACb,SAAA,EAAW;AAAA,KACZ,CAAA;AAED,IAAA,MAAM,QAAA,GAAW,MAAM,OAAA,CAAQ,MAAA,CAAO,QAAQ,CAAA,GAAI,MAAA,CAAO,WAAuB,EAAC;AACjF,IAAA,MAAM,SAAA,GAAY,MAAA,CAAO,MAAA,CAAO,SAAA,IAAa,EAAE,CAAA;AAG/C,IAAA,MAAM,OAAA,GAAU,IAAI,GAAA,CAAI,SAA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,GACtB,CAAA;AACD,EAAA,GAAA,CAAI,UAAU,CAAA,mBAAA,EAAsB,OAAA,CAAQ,OAAO,MAAM,CAAA,SAAA,EAAY,QAAQ,MAAA,CAAO,MAAA,CAAO,CAAC,CAAA,EAAG,MAAM,CAAA,GAAI,CAAA,CAAE,WAAW,MAAA,EAAQ,CAAC,CAAC,CAAA,WAAA,CAAa,CAAA;AAE7I,EAAA,OAAO;AAAA,IACL,YAAA,EAAc,aAAA;AAAA,IACd,gBAAA;AAAA,IACA,OAAA;AAAA,IACA,cAAA;AAAA,IACA,QAAA,EAAU,WAAA;AAAA,IACV;AAAA,GACF;AACF","file":"chunk-GEUDHZE7.mjs","sourcesContent":["/**\n * LLM-based File Selector — sends file tree to LLM, asks it to pick\n * which files are most relevant to the project goal.\n *\n * This mirrors knowledge-tree's approach:\n * 1. git_tracker generates project_structure.txt (file tree)\n * 2. Agent/LLM reads tree → selects important files\n * 3. Only selected files are read for analysis\n */\n\nimport { createLlmClient, llmChatJson, type LlmClientConfig } from '../utils/llmClient';\n\nexport interface FileSelectionResult {\n selected: string[];\n reasoning: string;\n}\n\n/**\n * Ask LLM to select which files from the file tree are relevant to the goal.\n * Input: file tree (names only, very small) + goal\n * Output: list of file paths to analyze\n */\nexport async function selectFilesWithLlm(\n filePaths: string[],\n goal: string,\n techStack: string,\n llmConfig?: LlmClientConfig,\n): Promise<FileSelectionResult> {\n // If very few files, no need to filter\n if (filePaths.length <= 15) {\n return { selected: filePaths, reasoning: 'Too few files to filter' };\n }\n\n const client = createLlmClient(llmConfig);\n\n // Build file tree for LLM (just names, grouped by directory)\n const treeLines = buildFileTree(filePaths);\n\n const systemPrompt = (\n 'You are a software architect analyzing a project repository.\\n'\n + 'Given a file tree and a project goal, select which files are MOST IMPORTANT '\n + 'to read for understanding the project architecture and implementation.\\n\\n'\n + 'RULES:\\n'\n + '1. Prioritize source code files (Swift, TS, Python, C++) over config/docs\\n'\n + '2. Include entry points (App.swift, main.py, index.ts)\\n'\n + '3. Include core domain files (models, services, views, controllers)\\n'\n + '4. EXCLUDE test files, mock files, generated files\\n'\n + '5. EXCLUDE config files (package.json, Podfile, etc.) unless they reveal architecture\\n'\n + '6. Include files that directly implement the features mentioned in the goal\\n'\n + '7. Return 20-40 files maximum (fewer is better if the project is small)\\n\\n'\n + 'Return JSON: {\"selected\": [\"path/to/file1\", \"path/to/file2\"], \"reasoning\": \"brief explanation\"}'\n );\n\n const userPrompt = (\n `Project goal: ${goal}\\n`\n + `Tech stack: ${techStack}\\n\\n`\n + `FILE TREE (${filePaths.length} files):\\n${treeLines}\\n\\n`\n + 'Select the most important files to analyze. Return JSON.'\n );\n\n try {\n const result = await llmChatJson(client, systemPrompt, userPrompt, {\n temperature: 0.1,\n maxTokens: 4096,\n });\n\n const selected = Array.isArray(result.selected) ? result.selected as string[] : [];\n const reasoning = String(result.reasoning || '');\n\n // Validate: only keep files that exist in the original list\n const pathSet = new Set(filePaths);\n const validSelected = selected.filter(p => pathSet.has(p));\n\n if (validSelected.length === 0) {\n // LLM returned nothing valid — fallback to all files\n return { selected: filePaths, reasoning: 'LLM selection empty, using all files' };\n }\n\n return { selected: validSelected, reasoning };\n } catch (err) {\n console.warn(`[WARN] LLM file selection failed (${err}), using all files`);\n return { selected: filePaths, reasoning: `LLM failed: ${err}` };\n }\n}\n\n/**\n * Build a compact file tree string for LLM consumption.\n * Groups files by top-level directory, shows only filenames.\n */\nfunction buildFileTree(filePaths: string[]): string {\n const byDir = new Map<string, string[]>();\n\n for (const fp of filePaths) {\n const parts = fp.split('/');\n const dir = parts.length > 1 ? parts.slice(0, -1).join('/') : '(root)';\n const file = parts[parts.length - 1];\n if (!byDir.has(dir)) byDir.set(dir, []);\n byDir.get(dir)!.push(file);\n }\n\n const lines: string[] = [];\n for (const [dir, files] of byDir) {\n lines.push(`${dir}/`);\n for (const f of files.sort()) {\n lines.push(` ${f}`);\n }\n }\n\n return lines.join('\\n');\n}\n","/**\n * File I/O utilities for domain-kit pipeline.\n */\n\nimport { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, statSync } from 'node:fs';\nimport { join, extname, relative, resolve } from 'node:path';\nimport { execSync } from 'node:child_process';\n\n/**\n * Read JSON file safely, returns null if not found or invalid.\n */\nexport function readJsonFile<T = unknown>(filePath: string): T | null {\n try {\n if (!existsSync(filePath)) return null;\n const content = readFileSync(filePath, 'utf-8');\n return JSON.parse(content) as T;\n } catch {\n return null;\n }\n}\n\n/**\n * Write JSON file, creating parent directories if needed.\n */\nexport function writeJsonFile(filePath: string, data: unknown): void {\n mkdirSync(join(filePath, '..'), { recursive: true });\n writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');\n}\n\n/**\n * Read text file safely, returns null if not found.\n */\nexport function readTextFile(filePath: string): string | null {\n try {\n if (!existsSync(filePath)) return null;\n return readFileSync(filePath, 'utf-8');\n } catch {\n return null;\n }\n}\n\n/**\n * Collect source files from a directory, filtering by allowed extensions.\n */\nexport function collectSourceFiles(\n dir: string,\n options?: {\n allowedExtensions?: string[];\n skipDirs?: string[];\n maxFiles?: number;\n },\n): string[] {\n const allowedExts = options?.allowedExtensions || ['.swift', '.ts', '.tsx', '.js', '.jsx', '.py', '.ino', '.cpp', '.c', '.h', '.hpp'];\n const maxFiles = options?.maxFiles || 70;\n\n // Try git ls-files first — respects .gitignore, handles submodules, symlinks\n const gitFiles = collectViaGit(dir, allowedExts, maxFiles);\n if (gitFiles.length > 0) return gitFiles;\n\n // Fallback: filesystem walk (non-git directories)\n return collectViaFilesystem(dir, allowedExts, maxFiles, options?.skipDirs);\n}\n\n/**\n * Collect source files using `git ls-files`.\n * Respects .gitignore, handles symlinks, much faster than walk.\n */\nfunction collectViaGit(dir: string, allowedExts: string[], maxFiles: number): string[] {\n try {\n const raw = execSync('git ls-files --cached --others --exclude-standard', {\n cwd: dir,\n encoding: 'utf-8',\n timeout: 5000,\n maxBuffer: 1024 * 1024,\n });\n const extSet = new Set(allowedExts.map(e => e.toLowerCase()));\n return raw\n .split('\\n')\n .filter(line => line.length > 0)\n .filter(line => extSet.has(extname(line).toLowerCase()))\n .slice(0, maxFiles)\n .map(rel => join(dir, rel));\n } catch {\n // Not a git repo or git not available — fall through to filesystem walk\n return [];\n }\n}\n\n/**\n * Collect source files using recursive directory walk (non-git fallback).\n */\nfunction collectViaFilesystem(\n dir: string,\n allowedExts: string[],\n maxFiles: number,\n skipDirs?: string[],\n): string[] {\n const skipSet = new Set(skipDirs || [\n 'node_modules', '.build', 'Pods', '.git', '.venv', 'venv',\n '__pycache__', 'build', 'dist', '.idea', '.vscode',\n 'test', 'tests', 'demo', 'sample', 'example', 'playground',\n ]);\n const extSet = new Set(allowedExts.map(e => e.toLowerCase()));\n const result: string[] = [];\n\n function walk(currentDir: string) {\n if (result.length >= maxFiles) return;\n let entries;\n try {\n entries = readdirSync(currentDir, { withFileTypes: true });\n } catch {\n return; // permission error\n }\n for (const entry of entries) {\n if (result.length >= maxFiles) return;\n const fullPath = join(currentDir, entry.name);\n if (entry.isDirectory()) {\n if (!skipSet.has(entry.name)) {\n walk(fullPath);\n }\n } else if (entry.isFile()) {\n const ext = extname(entry.name).toLowerCase();\n if (extSet.has(ext)) {\n result.push(fullPath);\n }\n }\n }\n }\n\n walk(dir);\n return result;\n}\n\n/**\n * Collect file contents map (relative path → content).\n */\nexport function collectFileContents(\n dir: string,\n options?: {\n allowedExtensions?: string[];\n skipDirs?: string[];\n maxFiles?: number;\n maxChars?: number;\n },\n): { paths: string[]; contents: Map<string, string> } {\n const maxChars = options?.maxChars || 500000;\n const files = collectSourceFiles(dir, options);\n const contents = new Map<string, string>();\n let totalChars = 0;\n\n for (const filePath of files) {\n const relPath = relative(dir, filePath);\n try {\n const content = readFileSync(filePath, 'utf-8');\n if (totalChars + content.length > maxChars) {\n const remaining = maxChars - totalChars;\n if (remaining > 100) {\n contents.set(relPath, content.slice(0, remaining));\n totalChars += remaining;\n }\n break;\n }\n contents.set(relPath, content);\n totalChars += content.length;\n } catch {\n // Skip unreadable files\n }\n }\n\n return { paths: files.map(f => relative(dir, f)), contents };\n}\n\n/**\n * Read contents of SPECIFIC files (by relative path) — no directory scan.\n * Used for 2-pass approach: scan tree first, then read only selected files.\n */\nexport function collectSpecificFileContents(\n dir: string,\n relativePaths: string[],\n maxChars: number = 500000,\n): Map<string, string> {\n const contents = new Map<string, string>();\n let totalChars = 0;\n\n for (const relPath of relativePaths) {\n const fullPath = join(dir, relPath);\n try {\n const content = readFileSync(fullPath, 'utf-8');\n if (totalChars + content.length > maxChars) {\n const remaining = maxChars - totalChars;\n if (remaining > 100) {\n contents.set(relPath, content.slice(0, remaining));\n totalChars += remaining;\n }\n break;\n }\n contents.set(relPath, content);\n totalChars += content.length;\n } catch {\n // Skip unreadable files\n }\n }\n\n return contents;\n}\n\n/**\n * Detect primary language from file extensions.\n */\nexport function detectPrimaryLanguage(filePaths: string[]): string {\n const counts = new Map<string, number>();\n for (const fp of filePaths) {\n const ext = extname(fp).toLowerCase();\n let lang = 'unknown';\n if (ext === '.swift') lang = 'Swift';\n else if (ext === '.ts' || ext === '.tsx') lang = 'TypeScript';\n else if (ext === '.js' || ext === '.jsx') lang = 'JavaScript';\n else if (ext === '.py') lang = 'Python';\n else if (ext === '.ino' || ext === '.cpp' || ext === '.c' || ext === '.h') lang = 'C++';\n else if (ext === '.kt' || ext === '.kts') lang = 'Kotlin';\n counts.set(lang, (counts.get(lang) || 0) + 1);\n }\n\n let maxCount = 0;\n let primary = 'unknown';\n for (const [lang, count] of counts) {\n if (count > maxCount) {\n maxCount = count;\n primary = lang;\n }\n }\n return primary;\n}\n\n/**\n * Read README.md and extract project description.\n */\nexport function readReadmeDescription(repoDir: string): string | null {\n const readmePath = join(repoDir, 'README.md');\n if (!existsSync(readmePath)) return null;\n try {\n const content = readFileSync(readmePath, 'utf-8');\n const lines = content.split('\\n').map(l => l.trim()).filter(Boolean);\n // Skip patterns: badges, images, table of contents, HTML tags\n const skipPatterns = [/^\\[!/, /^<img/, /^<a /, /^#+\\s+Table of/i, /^---$/];\n let foundTitle = false;\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (line.startsWith('#') && !line.startsWith('##')) {\n foundTitle = true;\n continue;\n }\n if (!foundTitle) continue;\n // Skip empty lines, badges, images, TOC, horizontal rules\n if (skipPatterns.some(p => p.test(line))) continue;\n if (line.startsWith('#')) return null; // hit next heading — no description found\n if (line.startsWith('```')) return null; // code block\n if (line.startsWith('|')) return null; // table\n if (line.length > 15) return line;\n }\n return null;\n } catch {\n return null;\n }\n}\n","/**\n * Project Graph Pipeline — full orchestrator.\n *\n * Ported from knowledge-tree/generate_roadmap_v3.py PipelineOrchestrator\n * Coordinates: AST analysis → keyword extraction → LLM graph generation →\n * verification → concept escalation → concept resolution → assembly.\n */\n\nimport type { ProjectGraph, Feature } from '../schemas/projectGraphSchema';\nimport { parseSwiftFile, mergeSwiftResults, type SwiftParseResult } from '../parsers/swift';\nimport { parseTsFile, mergeTsResults, type TsParseResult } from '../parsers/typescript';\nimport { parsePythonFile, mergePythonResults, type PythonParseResult } from '../parsers/python';\nimport { parseCppFile, mergeCppResults, type CppParseResult } from '../parsers/cpp';\nimport { extractKeywords, type Keyword, type SourceContext } from '../extractors/keywordExtractor';\nimport { extractScaffold } from '../graph/scaffoldExtractor';\nimport { extractProjectOverview } from '../graph/overviewExtractor';\nimport { extractFeatureSteps, extractFeatureStepsBatched } from '../graph/stepExtractor';\nimport { verifyProjectGraph, type Hallucination } from '../graph/graphVerifier';\nimport { escalateAndMapConcepts, type ConceptMapping } from '../graph/conceptEscalator';\nimport { resolveConcepts, type ResolveConceptsResult } from '../concepts/conceptResolver';\nimport { assembleRoadmap, type AssembledRoadmap } from '../assembly/roadmapAssembler';\nimport { selectFilesWithLlm } from '../extractors/fileSelector';\nimport { collectSourceFiles, collectSpecificFileContents, detectPrimaryLanguage, readReadmeDescription } from '../utils/fileUtils';\nimport { relative } from 'node:path';\nimport { createLlmClient, type LlmClientConfig } from '../utils/llmClient';\n\nexport interface PipelineOptions {\n repoDir: string;\n goal: string;\n techStack: string;\n llmConfig?: LlmClientConfig;\n embeddings?: Record<string, { embedding?: number[]; name?: string; description?: string; keywords?: string }>;\n onProgress?: (step: string, message: string) => void;\n}\n\nexport interface PipelineResult {\n projectGraph: ProjectGraph;\n resolvedConcepts: ResolveConceptsResult;\n roadmap: AssembledRoadmap;\n hallucinations: Hallucination[];\n keywords: Keyword[];\n featureConcepts: Map<string, ConceptMapping[]>;\n}\n\n/**\n * Run the full project graph generation pipeline.\n */\nexport async function runProjectGraphPipeline(\n options: PipelineOptions,\n): Promise<PipelineResult> {\n const { repoDir, goal, techStack, llmConfig, embeddings, onProgress } = options;\n\n const log = (step: string, msg: string) => {\n console.log(`[${step}] ${msg}`);\n onProgress?.(step, msg);\n };\n\n // ─── STEP 1A: File Tree Scan (names only — no content reading) ─────────\n log('STEP_1', 'Scanning file tree (names only)...');\n\n const allFilePaths = collectSourceFiles(repoDir);\n const allRelPaths = allFilePaths.map(fp => relative(repoDir, fp));\n log('STEP_1', `Found ${allRelPaths.length} source files in repository`);\n\n // ─── STEP 1B: LLM File Selection (sends tiny file tree to LLM) ────────\n log('STEP_1', 'Asking LLM to select relevant files from file tree...');\n\n const { selected: selectedPaths, reasoning } = await selectFilesWithLlm(\n allRelPaths, goal, techStack, llmConfig,\n );\n log('STEP_1', `LLM selected ${selectedPaths.length}/${allRelPaths.length} files: ${reasoning.slice(0, 100)}`);\n\n // ─── STEP 1C: Read content only for LLM-selected files ─────────────────\n log('STEP_1', 'Reading content for selected files...');\n\n const fileContentsMap = collectSpecificFileContents(repoDir, selectedPaths);\n const filePaths = selectedPaths;\n const primaryLang = detectPrimaryLanguage(filePaths);\n log('STEP_1', `Primary language: ${primaryLang}, ${filePaths.length} files loaded (${fileContentsMap.size} with content)`);\n\n // Parse source files\n log('STEP_1', 'Parsing source files with AST-level analysis...');\n\n const allParseResults: SourceContext[] = [];\n for (const [relPath, content] of fileContentsMap) {\n const fullPath = relPath;\n if (fullPath.endsWith('.swift')) {\n allParseResults.push(parseSwiftFile(fullPath, content));\n } else if (fullPath.endsWith('.ts') || fullPath.endsWith('.tsx') || fullPath.endsWith('.js') || fullPath.endsWith('.jsx')) {\n allParseResults.push(parseTsFile(fullPath, content));\n } else if (fullPath.endsWith('.py')) {\n allParseResults.push(parsePythonFile(fullPath, content));\n } else if (fullPath.endsWith('.ino') || fullPath.endsWith('.cpp') || fullPath.endsWith('.c') || fullPath.endsWith('.h')) {\n allParseResults.push(parseCppFile(fullPath, content));\n }\n }\n\n // Merge parse results by language\n let mergedContext: SourceContext;\n if (primaryLang === 'Swift') {\n mergedContext = mergeSwiftResults(allParseResults.filter((r): r is SwiftParseResult => 'property_wrappers' in r));\n } else if (primaryLang === 'TypeScript' || primaryLang === 'JavaScript') {\n mergedContext = mergeTsResults(allParseResults.filter((r): r is TsParseResult => !('docstrings' in r) && !('property_wrappers' in r) && !('frameworks_used' in r)));\n } else if (primaryLang === 'Python') {\n mergedContext = mergePythonResults(allParseResults.filter((r): r is PythonParseResult => 'docstrings' in r));\n } else {\n mergedContext = mergeCppResults(allParseResults.filter((r): r is CppParseResult => 'error_handling' in r && !('docstrings' in r) && !('property_wrappers' in r)));\n }\n\n // ─── STEP 2: Keyword Extraction ──────────────────────────────────────────\n log('STEP_2', 'Extracting keywords from AST analysis...');\n\n const astKeywords = extractKeywords(mergedContext);\n log('STEP_2', `Extracted ${astKeywords.length} keywords`);\n\n // ─── STEP 3: Build SDK API Index (simplified — use AST keywords as proxy) ──\n log('STEP_3', 'Building SDK API index...');\n\n const sdkApiIndex = {\n sdk_apis: astKeywords.map(kw => ({\n name: kw.keyword,\n kind: kw.source,\n used_in_demo: true,\n })),\n };\n\n // ─── STEP 4: LLM Project Graph Generation ────────────────────────────────\n log('STEP_4', 'Generating project graph via LLM (C0: Scaffold, C1: Overview, C2: Steps)...');\n\n // C0: Scaffold (F0) — uses file list (names only, not content)\n log('STEP_4_C0', 'Extracting FOUNDATION & SETUP feature (F0)...');\n const scaffoldFeature = await extractScaffold({\n goal,\n techStack,\n fileList: filePaths,\n llmConfig,\n });\n\n // C1: Overview (features meta) — uses already-filtered fileContentsMap\n log('STEP_4_C1', 'Extracting project overview (features meta)...');\n const overview = await extractProjectOverview({\n goal,\n techStack,\n sdkApiIndex,\n fileContentsMap,\n astKeywords,\n llmConfig,\n });\n\n // Build PBL step (Design Thinking)\n const product = overview.product as Record<string, unknown> | undefined;\n const pblStep: Feature['steps'] extends (infer T)[] ? T : never = {\n id: 'F0-S1',\n sequence: 1,\n name: 'Frame the problem & understand user needs (Design Thinking)',\n description: 'BEFORE CODING — frame the problem and understand what the user needs',\n files: [],\n api_usage: [],\n keywords: ['Design Thinking', 'User Needs', 'Problem Statement', 'User Journey', 'PBL'],\n completion_level: 'base',\n platform: 'app',\n intent: 'Understand user needs and frame problem before writing code',\n outcome: { user_visible: 'Defined problem statement', technical: 'Problem frame context' },\n acceptance: ['Problem statement is clear', 'Primary users identified'],\n requirement_ids: [],\n concept_codes: [],\n effort: { estimated_minutes: 15, complexity: 'low' },\n };\n\n // Merge scaffold F0 with PBL step\n let featuresFull: Feature[] = [];\n if (scaffoldFeature) {\n const scaffoldSteps = [pblStep, ...(scaffoldFeature.steps || [])].map((s, i) => ({\n ...s,\n id: `F0-S${i + 1}`,\n sequence: i + 1,\n }));\n featuresFull.push({\n ...scaffoldFeature,\n id: 'F0',\n name: 'FOUNDATION & SETUP',\n steps: scaffoldSteps,\n });\n } else {\n featuresFull.push({\n id: 'F0',\n name: 'FOUNDATION & SETUP',\n description: 'Frame the problem, get familiar with the tools',\n steps: [pblStep],\n } as Feature);\n }\n\n // Add features from overview\n const overviewFeatures = (product?.features || []) as Feature[];\n featuresFull = [...featuresFull, ...overviewFeatures];\n\n // C2: Extract steps per feature\n log('STEP_4_C2', `Extracting steps for ${overviewFeatures.length} features...`);\n\n const nonF0Features = overviewFeatures.filter(f => f.id !== 'F0');\n if (nonF0Features.length > 0) {\n try {\n const batchedSteps = await extractFeatureStepsBatched(\n goal, techStack, sdkApiIndex, fileContentsMap, nonF0Features, llmConfig,\n );\n for (const feature of nonF0Features) {\n const steps = batchedSteps.get(feature.id || '');\n if (steps) feature.steps = steps;\n }\n } catch (err) {\n log('STEP_4_C2', `Batch extraction failed (${err}), falling back to per-feature...`);\n for (const feature of nonF0Features) {\n try {\n const steps = await extractFeatureSteps({\n goal, techStack, sdkApiIndex, fileContentsMap, feature, llmConfig,\n });\n feature.steps = steps;\n } catch (e) {\n log('STEP_4_C2', `Failed for ${feature.id}: ${e}`);\n }\n }\n }\n }\n\n // Build project graph\n const projectGraph: ProjectGraph = {\n schema_version: 3,\n project: {\n id: (overview.project as Record<string, unknown>)?.name?.toString().toLowerCase().replace(/\\s+/g, '-') || 'project',\n name: (overview.project as Record<string, unknown>)?.name?.toString() || 'Project',\n purpose: goal,\n version: '0.1.0',\n project_type: 'app',\n platform: ((overview.project as Record<string, unknown>)?.platforms as string[]) || ['ios'],\n tech_stack: techStack.split(',').reduce((acc, t) => {\n const key = t.trim().toLowerCase();\n if (key) acc[key] = [t.trim()];\n return acc;\n }, {} as Record<string, string[]>),\n architecture: (overview.architecture as Record<string, unknown>)?.layers as string[] || [],\n },\n product: {\n goals: (product?.goals as Array<{ id: string; description: string }>) || [],\n users: (product?.users as Array<{ id: string; goals: string[] }>) || [],\n journeys: (product?.user_journeys as Array<{ id: string; name: string; requirement_ids: string[]; steps: string[]; feature_ids: string[] }>) || [],\n requirements: [],\n development_stages: (product?.development_stages as Array<{ stage: string; product_state: string; need: string[]; learn: string[]; validation: string; cross_feature_value: string; temporary_approach: string }>) || [],\n purpose: String(product?.purpose || ''),\n problem_statement: String(product?.problem_statement || ''),\n primary_users: (product?.primary_users as string[]) || [],\n },\n features: featuresFull,\n capabilities: [],\n implementation: {\n tasks: [],\n },\n missing_gaps: [],\n tech_debt: [],\n };\n\n // ─── STEP 5: Verification ────────────────────────────────────────────────\n log('STEP_5', 'Verifying project graph against source code...');\n\n const { graph: verifiedGraph, hallucinations } = verifyProjectGraph(projectGraph, {\n repoDir,\n sdkApiIndex,\n fileContentsMap,\n });\n log('STEP_5', `Verification complete: ${hallucinations.length} hallucinations found`);\n\n // ─── STEP 6: Concept Escalation ──────────────────────────────────────────\n log('STEP_6', 'Escalating keywords to neutral concepts...');\n\n const featureConcepts = await escalateAndMapConcepts({\n projectGraph: verifiedGraph,\n fileContentsMap,\n llmConfig,\n });\n log('STEP_6', `Concept mapping complete: ${featureConcepts.size} features mapped`);\n\n // Propagate concept_codes back into verified graph steps\n for (const feature of verifiedGraph.features || []) {\n const fid = feature.id || '';\n const fConcepts = featureConcepts.get(fid) || [];\n for (const step of feature.steps || []) {\n const stepConcepts = fConcepts\n .filter(cm => {\n // Match concept to step: check if step contains the keyword\n const stepKws = [...(step.keywords || []), ...(step.api_usage || [])];\n return stepKws.some(k => k === cm.keyword);\n })\n .map(cm => cm.concept_code);\n // Merge with any existing concept_codes from LLM\n const existing = step.concept_codes || [];\n step.concept_codes = [...new Set([...existing, ...stepConcepts])];\n }\n }\n\n // ─── STEP 7: Concept Resolution ──────────────────────────────────────────\n log('STEP_7', 'Resolving keywords to Master Tree concepts...');\n\n // Collect LLM-generated keywords from verified graph (not just AST)\n const llmKeywords: Keyword[] = [];\n const seenKw = new Set<string>();\n for (const feature of verifiedGraph.features || []) {\n for (const step of feature.steps || []) {\n for (const kw of [...(step.keywords || []), ...(step.api_usage || [])]) {\n if (!seenKw.has(kw.toLowerCase())) {\n seenKw.add(kw.toLowerCase());\n llmKeywords.push({ keyword: kw, source: 'llm_step', platform: 'app', weight: 1.0, context: 'LLM-generated step keyword' });\n }\n }\n }\n }\n // Merge with AST keywords (AST takes precedence for source/weight)\n const astKwMap = new Map(astKeywords.map(k => [k.keyword.toLowerCase(), k]));\n const mergedKeywords: Keyword[] = [];\n const mergedSeen = new Set<string>();\n for (const kw of [...astKeywords, ...llmKeywords]) {\n const key = kw.keyword.toLowerCase();\n if (!mergedSeen.has(key)) {\n mergedSeen.add(key);\n mergedKeywords.push(astKwMap.get(key) || kw);\n }\n }\n\n // Build depth overrides from concept escalation\n const depthOverrides = new Map<string, 'ulo' | 'cio' | 'sio'>();\n for (const mappings of featureConcepts.values()) {\n for (const cm of mappings) {\n if (!depthOverrides.has(cm.keyword)) {\n depthOverrides.set(cm.keyword, cm.depth);\n }\n }\n }\n\n const resolvedConcepts = await resolveConcepts({\n keywords: mergedKeywords,\n goal,\n embeddings,\n depthOverrides,\n llmConfig,\n });\n log('STEP_7', `Resolved: ${resolvedConcepts.summary.resolved_count}, Proposed: ${resolvedConcepts.summary.proposed_count} (${resolvedConcepts.summary.search_mode})`);\n\n // ─── STEP 8: Assembly ────────────────────────────────────────────────────\n log('STEP_8', 'Assembling roadmap with keyword tracking...');\n\n const roadmap = assembleRoadmap({\n projectGraph: verifiedGraph,\n featureConcepts,\n sessionMinutes: 90,\n overheadFactor: 1.15,\n maxMilestoneMinutes: 120,\n });\n log('STEP_8', `Roadmap assembled: ${roadmap.phases.length} phases, ${roadmap.phases.reduce((s, p) => s + p.milestones.length, 0)} milestones`);\n\n return {\n projectGraph: verifiedGraph,\n resolvedConcepts,\n roadmap,\n hallucinations,\n keywords: astKeywords,\n featureConcepts,\n };\n}\n"]}
|