@thanh01.pmt/domain-kit 0.1.0

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.
Files changed (108) hide show
  1. package/README.md +1101 -0
  2. package/dist/assembly/index.cjs +213 -0
  3. package/dist/assembly/index.cjs.map +1 -0
  4. package/dist/assembly/index.d.cts +66 -0
  5. package/dist/assembly/index.d.ts +66 -0
  6. package/dist/assembly/index.mjs +4 -0
  7. package/dist/assembly/index.mjs.map +1 -0
  8. package/dist/chunk-3H2HX7PR.mjs +324 -0
  9. package/dist/chunk-3H2HX7PR.mjs.map +1 -0
  10. package/dist/chunk-3VVPSRAM.mjs +1297 -0
  11. package/dist/chunk-3VVPSRAM.mjs.map +1 -0
  12. package/dist/chunk-DRVOV5ZD.mjs +314 -0
  13. package/dist/chunk-DRVOV5ZD.mjs.map +1 -0
  14. package/dist/chunk-F4RZNBOE.mjs +3 -0
  15. package/dist/chunk-F4RZNBOE.mjs.map +1 -0
  16. package/dist/chunk-GEUDHZE7.mjs +446 -0
  17. package/dist/chunk-GEUDHZE7.mjs.map +1 -0
  18. package/dist/chunk-HH4UX65C.mjs +100 -0
  19. package/dist/chunk-HH4UX65C.mjs.map +1 -0
  20. package/dist/chunk-KMYENICQ.mjs +3 -0
  21. package/dist/chunk-KMYENICQ.mjs.map +1 -0
  22. package/dist/chunk-KNDBODUQ.mjs +153 -0
  23. package/dist/chunk-KNDBODUQ.mjs.map +1 -0
  24. package/dist/chunk-MM2RWYNW.mjs +3 -0
  25. package/dist/chunk-MM2RWYNW.mjs.map +1 -0
  26. package/dist/chunk-MOKNFLUD.mjs +851 -0
  27. package/dist/chunk-MOKNFLUD.mjs.map +1 -0
  28. package/dist/chunk-ONQHJ4OH.mjs +211 -0
  29. package/dist/chunk-ONQHJ4OH.mjs.map +1 -0
  30. package/dist/chunk-PM42MMDJ.mjs +516 -0
  31. package/dist/chunk-PM42MMDJ.mjs.map +1 -0
  32. package/dist/chunk-RKRNOVKO.mjs +166 -0
  33. package/dist/chunk-RKRNOVKO.mjs.map +1 -0
  34. package/dist/chunk-VFART56O.mjs +884 -0
  35. package/dist/chunk-VFART56O.mjs.map +1 -0
  36. package/dist/chunk-XMHKWHVK.mjs +218 -0
  37. package/dist/chunk-XMHKWHVK.mjs.map +1 -0
  38. package/dist/conceptEscalator-YfMKIKCZ.d.ts +40 -0
  39. package/dist/conceptEscalator-ltRLtPhf.d.cts +40 -0
  40. package/dist/concepts/index.cjs +155 -0
  41. package/dist/concepts/index.cjs.map +1 -0
  42. package/dist/concepts/index.d.cts +79 -0
  43. package/dist/concepts/index.d.ts +79 -0
  44. package/dist/concepts/index.mjs +4 -0
  45. package/dist/concepts/index.mjs.map +1 -0
  46. package/dist/curriculumFeedSchema-TEeQg2bY.d.cts +549 -0
  47. package/dist/curriculumFeedSchema-TEeQg2bY.d.ts +549 -0
  48. package/dist/detector/index.cjs +889 -0
  49. package/dist/detector/index.cjs.map +1 -0
  50. package/dist/detector/index.d.cts +112 -0
  51. package/dist/detector/index.d.ts +112 -0
  52. package/dist/detector/index.mjs +3 -0
  53. package/dist/detector/index.mjs.map +1 -0
  54. package/dist/domainProfileSchema-CwT3Ffsw.d.cts +105 -0
  55. package/dist/domainProfileSchema-CwT3Ffsw.d.ts +105 -0
  56. package/dist/extractors/index.cjs +387 -0
  57. package/dist/extractors/index.cjs.map +1 -0
  58. package/dist/extractors/index.d.cts +46 -0
  59. package/dist/extractors/index.d.ts +46 -0
  60. package/dist/extractors/index.mjs +4 -0
  61. package/dist/extractors/index.mjs.map +1 -0
  62. package/dist/feed/index.cjs +421 -0
  63. package/dist/feed/index.cjs.map +1 -0
  64. package/dist/feed/index.d.cts +23 -0
  65. package/dist/feed/index.d.ts +23 -0
  66. package/dist/feed/index.mjs +4 -0
  67. package/dist/feed/index.mjs.map +1 -0
  68. package/dist/graph/index.cjs +2167 -0
  69. package/dist/graph/index.cjs.map +1 -0
  70. package/dist/graph/index.d.cts +226 -0
  71. package/dist/graph/index.d.ts +226 -0
  72. package/dist/graph/index.mjs +4 -0
  73. package/dist/graph/index.mjs.map +1 -0
  74. package/dist/graphVerifier-DsTP9uAN.d.ts +37 -0
  75. package/dist/graphVerifier-QjgDAJce.d.cts +37 -0
  76. package/dist/hybridGraphSchema-BCgXicgA.d.cts +2840 -0
  77. package/dist/hybridGraphSchema-BCgXicgA.d.ts +2840 -0
  78. package/dist/index.cjs +5539 -0
  79. package/dist/index.cjs.map +1 -0
  80. package/dist/index.d.cts +18 -0
  81. package/dist/index.d.ts +18 -0
  82. package/dist/index.mjs +17 -0
  83. package/dist/index.mjs.map +1 -0
  84. package/dist/keywordExtractor-CKaXqSku.d.ts +34 -0
  85. package/dist/keywordExtractor-zPAz2isq.d.cts +34 -0
  86. package/dist/llmClient-ysPhLjcH.d.cts +16 -0
  87. package/dist/llmClient-ysPhLjcH.d.ts +16 -0
  88. package/dist/parsers/index.cjs +323 -0
  89. package/dist/parsers/index.cjs.map +1 -0
  90. package/dist/parsers/index.d.cts +98 -0
  91. package/dist/parsers/index.d.ts +98 -0
  92. package/dist/parsers/index.mjs +4 -0
  93. package/dist/parsers/index.mjs.map +1 -0
  94. package/dist/pipeline/index.cjs +2166 -0
  95. package/dist/pipeline/index.cjs.map +1 -0
  96. package/dist/pipeline/index.d.cts +45 -0
  97. package/dist/pipeline/index.d.ts +45 -0
  98. package/dist/pipeline/index.mjs +8 -0
  99. package/dist/pipeline/index.mjs.map +1 -0
  100. package/dist/projectGraphSchema-DnD7orZV.d.cts +2581 -0
  101. package/dist/projectGraphSchema-DnD7orZV.d.ts +2581 -0
  102. package/dist/schemas/index.cjs +675 -0
  103. package/dist/schemas/index.cjs.map +1 -0
  104. package/dist/schemas/index.d.cts +253 -0
  105. package/dist/schemas/index.d.ts +253 -0
  106. package/dist/schemas/index.mjs +4 -0
  107. package/dist/schemas/index.mjs.map +1 -0
  108. package/package.json +71 -0
@@ -0,0 +1,1297 @@
1
+ import { createLlmClient, llmChatJson, parseJsonFromLlm } from './chunk-MOKNFLUD.mjs';
2
+ import { readFileSync, mkdirSync, writeFileSync } from 'fs';
3
+ import { tmpdir } from 'os';
4
+ import { join } from 'path';
5
+
6
+ // src/graph/loCodeStandard.ts
7
+ var TECH_TAG_MAP = {
8
+ python: "PY",
9
+ swift: "SW",
10
+ typescript: "TS",
11
+ javascript: "JV",
12
+ java: "JAVA",
13
+ kotlin: "KT",
14
+ go: "GO",
15
+ rust: "RUST",
16
+ csharp: "CS",
17
+ cpp: "CPP",
18
+ dart: "DT",
19
+ php: "PHP",
20
+ ruby: "RB",
21
+ sql: "SQL",
22
+ html: "HTML",
23
+ css: "CSS"
24
+ };
25
+ function techTagFor(techStack) {
26
+ const primary = (techStack || "").trim().toLowerCase();
27
+ for (const [key, tag] of Object.entries(TECH_TAG_MAP)) {
28
+ if (primary.includes(key)) return tag;
29
+ }
30
+ const first = primary.split(/[\s,+/]+/)[0] ?? "";
31
+ if (!/^[a-z]/.test(first)) return "GEN";
32
+ return first.length <= 4 ? first.toUpperCase() : first.slice(0, 3).toUpperCase();
33
+ }
34
+ var SMALL_WORDS = /* @__PURE__ */ new Set(["and", "or", "the", "of", "for", "in", "on", "a", "an", "vs"]);
35
+ function conceptCodeFromName(name) {
36
+ const words = name.replace(/[^A-Za-z0-9]+/g, " ").trim().split(/\s+/).filter((w) => w.length > 0 && !SMALL_WORDS.has(w.toLowerCase()));
37
+ const base = words.join("_").toUpperCase().replace(/^_+|_+$/g, "").replace(/_{2,}/g, "_");
38
+ const trimmed = (base || "CONCEPT").slice(0, 60).replace(/_+$/g, "");
39
+ return trimmed;
40
+ }
41
+ function assignConceptCodes(concepts) {
42
+ const used = /* @__PURE__ */ new Map();
43
+ const out = {};
44
+ for (const c of concepts) {
45
+ const base = conceptCodeFromName(c.name);
46
+ const n = (used.get(base) ?? 0) + 1;
47
+ used.set(base, n);
48
+ out[c.id] = n === 1 ? base : base + "_" + n;
49
+ }
50
+ return out;
51
+ }
52
+ var pad2 = (n) => String(n).padStart(2, "0");
53
+ function uloCode(conceptCode, seq = 1) {
54
+ return "ULO-" + conceptCode + "-" + pad2(seq);
55
+ }
56
+ var CIO_STOPWORDS = /* @__PURE__ */ new Set([
57
+ // clause boilerplate
58
+ "learner",
59
+ "will",
60
+ "be",
61
+ "able",
62
+ // generic fillers
63
+ "a",
64
+ "an",
65
+ "the",
66
+ "of",
67
+ "to",
68
+ "and",
69
+ "or",
70
+ "in",
71
+ "on",
72
+ "for",
73
+ "by",
74
+ "with",
75
+ "is",
76
+ "are",
77
+ "that",
78
+ "it",
79
+ "its",
80
+ "their",
81
+ "when",
82
+ "how",
83
+ "as",
84
+ "into",
85
+ "from"
86
+ ]);
87
+ function cioActionSlug(cioText) {
88
+ const body = cioText.startsWith(LEARNER_CLAUSE) ? cioText.slice(LEARNER_CLAUSE.length) : cioText;
89
+ const words = body.replace(/[^A-Za-z0-9]+/g, " ").trim().split(/\s+/).map((w) => w.toLowerCase()).filter((w) => w.length > 2 && !CIO_STOPWORDS.has(w));
90
+ const seen = /* @__PURE__ */ new Set();
91
+ const picked = [];
92
+ for (const w of words) {
93
+ if (!seen.has(w)) {
94
+ seen.add(w);
95
+ picked.push(w);
96
+ }
97
+ if (picked.length === 3) break;
98
+ }
99
+ return (picked.length > 0 ? picked : ["apply"]).join("_").toUpperCase();
100
+ }
101
+ function cioCode(conceptCode, uloSeq, actionSlug) {
102
+ return "CIO-" + conceptCode + "-" + pad2(uloSeq) + "-" + actionSlug;
103
+ }
104
+ function sioCode(techTag, conceptCode, seq) {
105
+ return "SIO-" + techTag + "-" + conceptCode + "-" + pad2(seq);
106
+ }
107
+ var LEARNER_CLAUSE = "The learner will be able to ";
108
+ function standardStatement(text) {
109
+ let body = (text || "").trim().replace(/^the learner (will be able to|can)\s*/i, "").replace(/\s+/g, " ");
110
+ if (body.length === 0) return "";
111
+ const firstWord = body.split(" ")[0] ?? "";
112
+ const looksAcronym = /^[A-Z0-9_.`]+$/.test(firstWord) && firstWord.length > 1;
113
+ if (!looksAcronym) body = body.charAt(0).toLowerCase() + body.slice(1);
114
+ body = body.replace(/[.\s]+$/, "");
115
+ return LEARNER_CLAUSE + body + ".";
116
+ }
117
+ var CONCEPT_CODE_RE = /^[A-Z][A-Z0-9_]*$/;
118
+ var ULO_CODE_RE = /^ULO-[A-Z][A-Z0-9_]*-\d{2}$/;
119
+ var CIO_CODE_RE = /^CIO-[A-Z][A-Z0-9_]*-\d{2}-[A-Z][A-Z0-9_]*$/;
120
+ var SIO_CODE_RE = /^SIO-[A-Z0-9]+-[A-Z][A-Z0-9_]*-\d{2}$/;
121
+
122
+ // src/graph/loExemplars.ts
123
+ var ULO_EXEMPLARS = [
124
+ // Calibrated against production learning_objectives (UNIVERSAL rows, neutral)
125
+ "The learner will be able to recall the key concepts, terminology, and characteristics of layers of abstraction.",
126
+ "The learner will be able to explain how layers of abstraction hide implementation details while exposing essential behavior.",
127
+ "The learner will be able to explain how a program changes state through statements and control flow.",
128
+ "The learner will be able to differentiate local from global scope and describe how return values affect data flow.",
129
+ "The learner will be able to describe the mechanism of a loop, including its condition, step and stopping rule.",
130
+ "The learner will be able to explain why a representation format must balance readability against processing efficiency."
131
+ ];
132
+ var CIO_EXEMPLARS = [
133
+ // Production CONCEPTUAL_IMPL rows: mechanism behind the clause, Marr 2-Language neutral
134
+ "The learner will be able to develop a conceptual model that explains the internal mechanism by which the representation produces its effect.",
135
+ "The learner will be able to compare alternative approaches for the same operation and describe the trade-offs between them.",
136
+ "The learner will be able to decompose the choice of representation into decisive criteria such as cost, fidelity and tolerance to change.",
137
+ "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."
138
+ ];
139
+ var SIO_EXEMPLARS = [
140
+ // Production SPECIFIC_IMPL style: keyword-bound completable tasks, tech-tagged tier
141
+ "The learner will be able to use argparse.ArgumentParser with add_subparsers to register add, done and list commands in a Python CLI.",
142
+ "The learner will be able to define a @dataclass with type hints and a __post_init__ method that raises ValueError on invariant violation.",
143
+ "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.",
144
+ "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."
145
+ ];
146
+
147
+ // src/graph/depthAudit.ts
148
+ var TECH_SIGNAL_RES = [
149
+ /`[^`]+`/,
150
+ /\b[a-zA-Z_][A-Za-z0-9_]*\(\)/,
151
+ // call-with-arguments: Status(enum.Enum), field(default_factory=list)
152
+ /\b[A-Za-z_][A-Za-z0-9_]*\([^)]+\)/,
153
+ // attribute access glued to a value: enum.Enum, os.path, tasks.json
154
+ /[A-Za-z0-9_)\]]\.[A-Za-z_][A-Za-z0-9_]+/,
155
+ /[a-z]+_[a-z]+/,
156
+ /[a-z]+[A-Z][A-Za-z]*/,
157
+ /\.[a-z]{2,4}\b/,
158
+ /\b(?:API|SDK|JSON|XML|YAML|HTTP|SQL|UUID|URL|DOM|CLI|TUI|CSV|UTF|CRUD|DSL)\b/,
159
+ // Exception/error class names: Exception, ValueError, CustomError
160
+ /\b[A-Z][a-zA-Z0-9_]*(?:Error|Exception|Warning|Fault)\b/,
161
+ // class declarations or references: class Status, static methods on types
162
+ /\bclass\s+[A-Za-z_][A-Za-z0-9_]*/,
163
+ // inheritance/derivation mentions: inheriting from Exception, subclass of Base
164
+ /\b(?:inherit(?:ing|s)?|subclass(?:ing)?|deriv(?:ing|ed|es)?)\s+(?:from|of)\s+[A-Z][A-Za-z0-9_]*/
165
+ ];
166
+ var GENERIC_STOP = /* @__PURE__ */ new Set(["e", "g", "i"]);
167
+ function techSignalHits(text) {
168
+ const hits = [];
169
+ for (const re of TECH_SIGNAL_RES) {
170
+ const found = text.match(new RegExp(re.source, "g")) ?? [];
171
+ for (const m of found) if (!GENERIC_STOP.has(m.toLowerCase())) hits.push(m);
172
+ }
173
+ return hits;
174
+ }
175
+ function auditDepthLayers(concepts) {
176
+ return concepts.map((c) => {
177
+ const ulo = (c.ulo ?? "").trim();
178
+ const cio = (c.cio ?? "").trim();
179
+ const sioItems = (c.sio ?? []).map((s) => (s ?? "").trim()).filter(Boolean);
180
+ const uloTechSignals = techSignalHits(ulo);
181
+ const uloHasTechSignals = uloTechSignals.length > 0;
182
+ const IMPL_VERBS = /\b(implement|refactor|debug|serialize)\b/i;
183
+ const uloHasImplementationVerbs = IMPL_VERBS.test(ulo);
184
+ const registryKeywords = (c.keywords ?? []).map((k) => String(k).toLowerCase()).filter((k) => k.length >= 3);
185
+ const nameTokens = String(c.name ?? "").toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length >= 4);
186
+ const boundToConcept = (s) => {
187
+ const lower = s.toLowerCase();
188
+ return registryKeywords.some((k) => lower.includes(k)) || nameTokens.some((w) => lower.includes(w));
189
+ };
190
+ const sioUnboundItems = sioItems.filter((s) => {
191
+ if (techSignalHits(s).length > 0) return false;
192
+ return !boundToConcept(s);
193
+ });
194
+ const conceptKeywords = (c.keywords ?? []).map((k) => k.toLowerCase()).filter(Boolean);
195
+ const sioOffConceptItems = conceptKeywords.length > 0 ? sioItems.filter((s) => !boundToConcept(s)) : [];
196
+ 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;
197
+ const sioNotCompletable = sioItems.filter((s) => !COMPLETABLE.test(s) && !/`[^`]+`/.test(s));
198
+ const density = (text) => {
199
+ if (!text) return 0;
200
+ return techSignalHits(text).length / Math.max(1, text.split(/\s+/).length) * 100;
201
+ };
202
+ const dUlo = density(ulo);
203
+ density(cio);
204
+ const dSio = sioItems.length > 0 ? Math.max(...sioItems.map(density)) : 0;
205
+ const concretenessIncreases = dSio > dUlo;
206
+ const clauseOk = ulo.startsWith(LEARNER_CLAUSE) && cio.startsWith(LEARNER_CLAUSE) && sioItems.every((t) => t.startsWith(LEARNER_CLAUSE));
207
+ const codeIssues = [];
208
+ const conceptCode = c.code;
209
+ if (conceptCode !== void 0 && !CONCEPT_CODE_RE.test(conceptCode)) codeIssues.push("concept code not UPPER_SNAKE: " + conceptCode);
210
+ const uloCodeVal = c.ulo_code;
211
+ if (uloCodeVal !== void 0 && uloCodeVal !== "" && !ULO_CODE_RE.test(uloCodeVal)) codeIssues.push("ULO code malformed: " + uloCodeVal);
212
+ const cioCodeVal = c.cio_code;
213
+ if (cioCodeVal !== void 0 && cioCodeVal !== "" && !CIO_CODE_RE.test(cioCodeVal)) codeIssues.push("CIO code malformed: " + cioCodeVal);
214
+ const sioCodeVals = c.sio_codes;
215
+ if (sioCodeVals !== void 0) {
216
+ if (sioCodeVals.length !== sioItems.length) codeIssues.push("SIO codes count mismatch");
217
+ for (const sc of sioCodeVals) if (!SIO_CODE_RE.test(sc)) codeIssues.push("SIO code malformed: " + sc);
218
+ }
219
+ const codesOk = codeIssues.length === 0;
220
+ const passed = !uloHasTechSignals && !uloHasImplementationVerbs && sioUnboundItems.length === 0 && sioOffConceptItems.length === 0 && sioNotCompletable.length === 0 && concretenessIncreases && clauseOk && codesOk;
221
+ return {
222
+ conceptId: c.id,
223
+ uloHasTechSignals,
224
+ uloTechSignals,
225
+ uloHasImplementationVerbs,
226
+ sioAllKeywordBound: sioUnboundItems.length === 0,
227
+ sioUnboundItems,
228
+ sioConceptKeywordBound: sioOffConceptItems.length === 0,
229
+ sioOffConceptItems,
230
+ sioAllCompletable: sioNotCompletable.length === 0,
231
+ sioNotCompletable,
232
+ concretenessIncreases,
233
+ clauseOk,
234
+ codesOk,
235
+ codeIssues,
236
+ passed
237
+ };
238
+ });
239
+ }
240
+
241
+ // src/graph/hierarchicalLoAuthoring.ts
242
+ function excerpt(text, max) {
243
+ const t = (text || "").trim();
244
+ return t.length > max ? t.slice(0, max) + "..." : t;
245
+ }
246
+ async function chatJson(client, system, user) {
247
+ const r = await client.chat(
248
+ [{ role: "system", content: system }, { role: "user", content: user }],
249
+ { temperature: 0.1, maxTokens: parseInt(process.env.KG_MAX_TOKENS || "65536", 10) }
250
+ );
251
+ return parseJsonFromLlm(r.content);
252
+ }
253
+ var LO_BATCH_SIZE = 6;
254
+ function chunkConcepts(items, size) {
255
+ const out = [];
256
+ for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
257
+ return out;
258
+ }
259
+ var JSON_ONLY = "Return EXACTLY JSON. No markdown, no explanations.";
260
+ async function authorDepthLayersHierarchically(client, concepts, techStack, warnings) {
261
+ const uloByConcept = {};
262
+ const cioByConcept = {};
263
+ const sioByConcept = {};
264
+ concepts.map((c) => "- " + c.id + ": " + c.name + (c.description ? " \u2014 " + excerpt(c.description, 160) : "")).join("\n");
265
+ const uloSystem = [
266
+ "You are a Curriculum Design Expert writing Universal Learning Objectives (ULO).",
267
+ "",
268
+ "ULO = Computational Tier: the CORE COMPETENCY \u2014 WHAT the concept is and WHY it exists \u2014",
269
+ "completely independent of any technology, language, framework, library, file format or tool.",
270
+ "",
271
+ "Rules:",
272
+ "1. NEVER mention a concrete technology, API, library, file name or syntax in a ULO.",
273
+ "2. Bind the ULO to the concept intrinsic nature: the problem it solves in principle.",
274
+ "3. Typical assessment level: Remember or Understand. Use pragmatic, measurable verbs",
275
+ " (Explain, Differentiate, Identify, Describe) instead of Know/Understand/Summarize.",
276
+ "4. Cognitive Ceiling: do NOT force Analyze/Evaluate/Create ULOs \u2014 if the concept is",
277
+ " foundational, its core competency is low-level. Higher levels are exercised later",
278
+ " INDIRECTLY through implementation work, not in the ULO itself.",
279
+ "5. One ULO per concept; 1-2 sentences covering WHAT + WHY.",
280
+ "6. Statement form (mandatory): every ULO MUST read 'The learner will be able to ...' \u2014",
281
+ " a lowercase actionable verb follows the clause (explain ..., differentiate ...).",
282
+ " Do not prefix any other phrasing.",
283
+ "",
284
+ "Approved style exemplars (production bank):",
285
+ ULO_EXEMPLARS.map((e) => "- " + e).join("\n"),
286
+ "",
287
+ JSON_ONLY
288
+ ].join("\n");
289
+ for (const batch of chunkConcepts(concepts, LO_BATCH_SIZE)) {
290
+ const batchList = batch.map((c) => "- " + c.id + " (" + c.name + ")" + (c.description ? ": " + excerpt(c.description, 160) : "")).join("\n");
291
+ const batchUser = "Concepts:\n" + batchList + '\n\nReturn JSON:\n{"ulos":[{"concept_id":"C1","ulo":"..."}]}';
292
+ const uloRes = await chatJson(client, uloSystem, batchUser);
293
+ for (const u of uloRes.ulos ?? []) {
294
+ if (u.concept_id && u.ulo) uloByConcept[u.concept_id] = standardStatement(u.ulo);
295
+ }
296
+ }
297
+ for (const c of concepts) {
298
+ if (!uloByConcept[c.id]) {
299
+ warnings.push("Phase A: no ULO generated for " + c.id + " \u2014 kept empty (audit will fail)");
300
+ uloByConcept[c.id] = "";
301
+ }
302
+ }
303
+ concepts.map((c) => "- " + c.id + " (" + c.name + "): " + uloByConcept[c.id]).join("\n");
304
+ const cioSystem = [
305
+ "You are a Curriculum Design Expert writing Concept-level Instructional Objectives (CIO).",
306
+ "",
307
+ "CIO = Algorithmic Tier: the MECHANISM \u2014 HOW the concept works, step by step, at a",
308
+ "procedural level. CIOs are derived from approved ULOs.",
309
+ "",
310
+ "Rules:",
311
+ "1. Still technology-agnostic: describe the neutral pattern/approach WITHOUT concrete",
312
+ " API names, libraries, file formats or syntax.",
313
+ "2. Marr 2-Language Test: the CIO must read as true and implementable regardless of",
314
+ " whether the learner uses Python, Swift, JavaScript or any other language. If it",
315
+ " only makes sense in one language, rewrite it more neutrally.",
316
+ "3. More concrete than the ULO: reference stages, conditions, ordering or trade-offs",
317
+ " of the underlying process.",
318
+ "4. One CIO per concept; 1-3 sentences describing the mechanism.",
319
+ "5. Statement form (mandatory): every CIO MUST read 'The learner will be able to ...' \u2014",
320
+ " the mechanism is described after the clause.",
321
+ "",
322
+ "Approved style exemplars (production bank):",
323
+ CIO_EXEMPLARS.map((e) => "- " + e).join("\n"),
324
+ "",
325
+ JSON_ONLY
326
+ ].join("\n");
327
+ for (const batch of chunkConcepts(concepts, LO_BATCH_SIZE)) {
328
+ new Set(batch.map((c) => c.id));
329
+ const batchUloContext = batch.map((c) => "- " + c.id + " (" + c.name + "): " + (uloByConcept[c.id] || "(missing)")).join("\n");
330
+ const batchCioUser = "Approved ULOs:\n" + batchUloContext + '\n\nReturn JSON:\n{"cios":[{"concept_id":"C1","cio":"..."}]}';
331
+ const cioRes = await chatJson(client, cioSystem, batchCioUser);
332
+ for (const x of cioRes.cios ?? []) {
333
+ if (x.concept_id && x.cio) cioByConcept[x.concept_id] = standardStatement(x.cio);
334
+ }
335
+ }
336
+ for (const c of concepts) {
337
+ if (!cioByConcept[c.id]) {
338
+ warnings.push("Phase B: no CIO generated for " + c.id + " \u2014 kept empty (audit will fail)");
339
+ cioByConcept[c.id] = "";
340
+ }
341
+ }
342
+ concepts.map((c) => "- " + c.id + " (" + c.name + "): CIO=" + cioByConcept[c.id] + " | ULO=" + uloByConcept[c.id]).join("\n");
343
+ const sioSystem = [
344
+ "You are a Curriculum Design Expert writing Specific Instructional Objectives (SIO).",
345
+ "",
346
+ "SIO = Implementation Tier: completable, context-specific implementation tasks derived",
347
+ "from approved CIOs, bound to the TARGET technology of the course.",
348
+ "",
349
+ "Rules:",
350
+ "1. EVERY SIO item MUST name concrete keywords/technologies: a real API, function,",
351
+ " decorator, module, class, file or command of the target technology.",
352
+ "2. Each item is a completable task: an actionable verb + the concrete construct + the",
353
+ " context where it is used. Application/Analysis/Creation skills are assessed",
354
+ " INDIRECTLY through completing these tasks \u2014 there is no fixed Bloom ceiling.",
355
+ " MACHINE CHECK: every item MUST contain at least one ACTION VERB from this whitelist",
356
+ " (build, create, implement, write, configure, add, use, apply, display, store, load,",
357
+ " save, handle, parse, validate, test, register, compute, generate, print, format,",
358
+ " convert, extend, define, execute, run, read, fetch, wrap, log, call, raise, install,",
359
+ " import, export, declare, embed, model, represent, override, customize, enforce, mock,",
360
+ " assert, query, index, cache, stream, split, join, strip, encode, decode, traverse,",
361
+ " measure, evaluate, benchmark, diagnose, demonstrate, verify, organize, structure,",
362
+ " choose, select, compare, distinguish, attach, annotate, expose, accept, manage, group,",
363
+ " sort, filter, map, reduce, catch, throw, migrate, inspect, trace, parameterize,",
364
+ " construct, design, capture) \u2014 OR wrap the concrete construct in backticks.",
365
+ " Items with abstract verbs (understand, learn, know, grasp, appreciate, explore) and",
366
+ " no backtick construct FAIL the audit. Prefer starting the task phrase with the verb.",
367
+ "3. 2-3 items per concept, each referencing a DIFFERENT concrete construct.",
368
+ "4. Statement form (mandatory): every SIO MUST read 'The learner will be able to ...' \u2014",
369
+ " the concrete task follows the clause.",
370
+ "",
371
+ "Approved style exemplars (production bank):",
372
+ SIO_EXEMPLARS.map((e) => "- " + e).join("\n"),
373
+ "",
374
+ JSON_ONLY
375
+ ].join("\n");
376
+ concepts.map((c) => "- " + c.id + " (" + c.name + "): " + ((c.keywords ?? []).slice(0, 10).join(", ") || "(none listed \u2014 use concrete constructs of " + techStack + ")")).join("\n");
377
+ for (const batch of chunkConcepts(concepts, LO_BATCH_SIZE)) {
378
+ const batchKw = batch.map((c) => "- " + c.id + " (" + c.name + "): " + ((c.keywords ?? []).slice(0, 10).join(", ") || "(none listed \u2014 use concrete constructs of " + techStack + ")")).join("\n");
379
+ const batchCioCtx = batch.map((c) => "- " + c.id + " (" + c.name + "): CIO=" + (cioByConcept[c.id] || "(missing)") + " | ULO=" + (uloByConcept[c.id] || "(missing)")).join("\n");
380
+ const batchSioUser = [
381
+ "Target technology: " + techStack,
382
+ "",
383
+ "Concept keywords (each SIO item MUST contain at least one of its concept's keywords):",
384
+ batchKw,
385
+ "",
386
+ "Approved CIOs and ULOs:",
387
+ batchCioCtx,
388
+ "",
389
+ "Return JSON:",
390
+ '{"sios":[{"concept_id":"C1","sio":["...","..."]}]}'
391
+ ].join("\n");
392
+ const sioRes = await chatJson(client, sioSystem, batchSioUser);
393
+ for (const x of sioRes.sios ?? []) {
394
+ if (x.concept_id && Array.isArray(x.sio)) sioByConcept[x.concept_id] = x.sio.map((item) => standardStatement(String(item)));
395
+ }
396
+ }
397
+ for (const c of concepts) {
398
+ if (!sioByConcept[c.id] || sioByConcept[c.id].length === 0) {
399
+ warnings.push("Phase C: no SIO generated for " + c.id + " \u2014 kept empty (audit will fail)");
400
+ sioByConcept[c.id] = [];
401
+ }
402
+ }
403
+ concepts.map((c) => c.id);
404
+ const auditOnce = () => auditDepthLayers(concepts.map((c) => ({
405
+ id: c.id,
406
+ name: c.name,
407
+ keywords: c.keywords ?? [],
408
+ ulo: uloByConcept[c.id],
409
+ cio: cioByConcept[c.id],
410
+ sio: sioByConcept[c.id]
411
+ })));
412
+ let audits = auditOnce();
413
+ const repairRound = async (round) => {
414
+ const failingNow = audits.filter((a) => !a.passed);
415
+ if (failingNow.length === 0) return false;
416
+ if (round > 1) warnings.push("Depth audit repair round " + round + ": " + failingNow.length + " concept(s) still failing");
417
+ const failing = failingNow;
418
+ {
419
+ warnings.push("Depth audit: " + failing.length + "/" + concepts.length + " concepts failed first audit \u2014 targeted repair");
420
+ const repairTargets = failing.map((a) => {
421
+ const c = concepts.find((x) => x.id === a.conceptId);
422
+ const issues = [];
423
+ if (a.uloHasTechSignals) issues.push("ULO names concrete technology (remove: " + a.uloTechSignals.join(", ") + ")");
424
+ if (a.uloHasImplementationVerbs) issues.push("ULO reads as an implementation task (rewrite as WHAT+WHY competency)");
425
+ for (const item of a.sioUnboundItems) issues.push("SIO not keyword-bound: " + excerpt(item, 120));
426
+ for (const item of a.sioOffConceptItems) issues.push("SIO does not reference any of this concept's keywords (" + (c?.keywords ?? []).join(", ") + "): " + excerpt(item, 120));
427
+ for (const item of a.sioNotCompletable) issues.push("SIO not a completable task: " + excerpt(item, 120));
428
+ if (!a.concretenessIncreases) issues.push("SIO is not more concrete than the ULO \u2014 bind it to concrete constructs");
429
+ return {
430
+ concept_id: a.conceptId,
431
+ name: c?.name ?? a.conceptId,
432
+ keywords: c?.keywords ?? [],
433
+ current: { ulo: uloByConcept[a.conceptId], cio: cioByConcept[a.conceptId], sio: sioByConcept[a.conceptId] },
434
+ issues
435
+ };
436
+ });
437
+ const repairSystem = [
438
+ "You repair depth-layer learning objectives that failed a deterministic contract audit.",
439
+ "For each concept, rewrite ONLY the layers mentioned in issues, keeping the others as-is.",
440
+ "Contract:",
441
+ "- ULO: WHAT+WHY, concept-bound, technology-agnostic, Remember/Understand verbs.",
442
+ "- CIO: HOW mechanism, technology-agnostic, more concrete than ULO, Marr 2-Language neutral.",
443
+ "- SIO: keyword-bound completable implementation tasks naming real constructs of " + techStack + ".",
444
+ "- 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).",
445
+ "- 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 \u2014 abstract verbs (understand, learn, know, grasp, explore, appreciate) always fail.",
446
+ "",
447
+ JSON_ONLY
448
+ ].join("\n");
449
+ const repairUser = [
450
+ "Failing concepts:",
451
+ JSON.stringify(repairTargets, null, 2),
452
+ "",
453
+ "Return the FULL repaired set for these concepts in the same 3-layer JSON shape:",
454
+ '{"repairs":[{"concept_id":"C1","ulo":"...","cio":"...","sio":["..."]}]}'
455
+ ].join("\n");
456
+ try {
457
+ const repairRes = await chatJson(client, repairSystem, repairUser);
458
+ for (const r of repairRes.repairs ?? []) {
459
+ if (!r.concept_id) continue;
460
+ if (r.ulo) uloByConcept[r.concept_id] = standardStatement(r.ulo);
461
+ if (r.cio) cioByConcept[r.concept_id] = standardStatement(r.cio);
462
+ if (Array.isArray(r.sio) && r.sio.length > 0) sioByConcept[r.concept_id] = r.sio.map((t) => standardStatement(String(t)));
463
+ }
464
+ audits = auditOnce();
465
+ } catch (err) {
466
+ warnings.push("Depth repair round failed: " + (err instanceof Error ? err.message : String(err)));
467
+ }
468
+ }
469
+ return audits.every((a) => a.passed);
470
+ };
471
+ for (let round = 1; round <= 2; round++) {
472
+ const allPass = await repairRound(round);
473
+ if (allPass) break;
474
+ }
475
+ const stillFailing = audits.filter((a) => !a.passed);
476
+ if (stillFailing.length > 0) {
477
+ try {
478
+ const { mkdirSync: mkdirSync2, writeFileSync: writeFileSync2 } = await import('fs');
479
+ const dumpDir = (await import('os')).tmpdir() + "/domain-kit-debug/";
480
+ mkdirSync2(dumpDir, { recursive: true });
481
+ writeFileSync2(dumpDir + "depth-audit-debug.json", JSON.stringify(
482
+ stillFailing.map((a) => ({ audit: a, ulo: uloByConcept[a.conceptId], cio: cioByConcept[a.conceptId], sio: sioByConcept[a.conceptId] })),
483
+ null,
484
+ 2
485
+ ));
486
+ } catch {
487
+ }
488
+ 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(", ");
489
+ throw new Error(
490
+ "Depth-layer contract audit failed after repair for: " + detail + " \u2014 regenerate or fix the prompt contract (fail-closed, no silent fallback)"
491
+ );
492
+ }
493
+ return { uloByConcept, cioByConcept, sioByConcept, audits, warnings };
494
+ }
495
+ function cell(v) {
496
+ return (v || "").split(",").map((s) => s.trim()).filter(Boolean);
497
+ }
498
+ function loadKnowledgeTreeCatalog(tsvPath) {
499
+ const text = readFileSync(tsvPath, "utf8");
500
+ const lines = text.split("\n").filter((l) => l.trim().length > 0);
501
+ if (lines.length === 0) throw new Error("Knowledge tree TSV is empty: " + tsvPath);
502
+ const header = lines[0].split(" ").map((h) => h.trim());
503
+ const col = (name) => header.indexOf(name);
504
+ const iT = col("item_type");
505
+ const iC = col("code");
506
+ const iN = col("name");
507
+ const iD = col("description");
508
+ const iCat = col("category_codes");
509
+ const iTpc = col("topic_codes");
510
+ const iPre = col("prerequisite_concept_codes");
511
+ const iKw = col("keywords");
512
+ for (const [name, idx] of [["item_type", iT], ["code", iC], ["name", iN]]) {
513
+ if (idx < 0) throw new Error("Knowledge tree TSV missing column: " + name);
514
+ }
515
+ const categories = /* @__PURE__ */ new Map();
516
+ const topics = /* @__PURE__ */ new Map();
517
+ const concepts = [];
518
+ for (const line of lines.slice(1)) {
519
+ const c = line.split(" ");
520
+ const type = (c[iT] || "").trim();
521
+ const code = (c[iC] || "").trim();
522
+ const name = (c[iN] || "").trim();
523
+ if (!code || !name) continue;
524
+ if (type === "CATEGORY") categories.set(code, name);
525
+ if (type === "TOPIC") topics.set(code, { name, categoryCodes: cell(c[iCat]) });
526
+ if (type !== "CONCEPT") continue;
527
+ const topicCodes = cell(c[iTpc]);
528
+ const categoryCodes = /* @__PURE__ */ new Set();
529
+ for (const t of topicCodes) for (const cc of topics.get(t)?.categoryCodes || []) categoryCodes.add(cc);
530
+ concepts.push({
531
+ code,
532
+ name,
533
+ description: (c[iD] || "").trim(),
534
+ keywords: cell(c[iKw]),
535
+ topicCodes,
536
+ categoryCodes: [...categoryCodes],
537
+ prerequisiteCodes: cell(c[iPre])
538
+ });
539
+ }
540
+ if (concepts.length === 0) throw new Error("Knowledge tree TSV has no CONCEPT rows: " + tsvPath);
541
+ return { path: tsvPath, concepts, categories, topics };
542
+ }
543
+ function tokens(s) {
544
+ return new Set(
545
+ s.toLowerCase().replace(/[^a-z0-9\s-]/g, " ").split(/\s+/).filter((w) => w.length >= 4)
546
+ );
547
+ }
548
+ function filterBySelection(catalog, selectedCategories, selectedTopics, analysisConcepts, maxConcepts = 120) {
549
+ const tps = new Set(selectedTopics.map((c) => c.trim().toUpperCase()).filter(Boolean));
550
+ const cats = new Set(selectedCategories.map((c) => c.trim().toUpperCase()).filter(Boolean));
551
+ const probe = analysisConcepts.map((c) => tokens(c.name + " " + c.keywords.join(" ")));
552
+ const probeAll = /* @__PURE__ */ new Set();
553
+ for (const p of probe) for (const w of p) probeAll.add(w);
554
+ const inSelection = (tc) => tc.topicCodes.some((t) => tps.has(t)) || tc.categoryCodes.some((c) => cats.has(c));
555
+ const overlapScore = (tc) => {
556
+ const tcTok = tokens(tc.name + " " + tc.description.slice(0, 300) + " " + tc.keywords.join(" "));
557
+ let overlap = 0;
558
+ for (const w of tcTok) if (probeAll.has(w)) overlap++;
559
+ const kwDirect = tc.keywords.filter((k) => {
560
+ const kl = k.toLowerCase();
561
+ return [...probeAll].some((w) => w === kl || w.length >= 5 && kl.includes(w));
562
+ }).length;
563
+ return overlap * 2 + kwDirect * 3;
564
+ };
565
+ const kept = catalog.concepts.filter((tc) => inSelection(tc) || overlapScore(tc) >= 6);
566
+ return kept.map((tc) => ({ tc, s: overlapScore(tc) })).sort((a, b) => b.s - a.s).slice(0, maxConcepts).map((x) => x.tc);
567
+ }
568
+ function renderShortlist(shortlist) {
569
+ return shortlist.map((tc) => "- " + tc.code + " | " + tc.name + " | kw: " + tc.keywords.slice(0, 8).join(", ") + (tc.prerequisiteCodes.length ? " | prereqs: " + tc.prerequisiteCodes.join(",") : "")).join("\n");
570
+ }
571
+ function renderCategoryTopicIndex(catalog) {
572
+ const topicToConcepts = /* @__PURE__ */ new Map();
573
+ for (const tc of catalog.concepts) for (const t of tc.topicCodes) topicToConcepts.set(t, (topicToConcepts.get(t) || 0) + 1);
574
+ const byCat = /* @__PURE__ */ new Map();
575
+ for (const [code, info] of catalog.topics) {
576
+ for (const cat of info.categoryCodes) {
577
+ const arr = byCat.get(cat) || [];
578
+ arr.push(code + " " + info.name + " (" + (topicToConcepts.get(code) || 0) + " concepts)");
579
+ byCat.set(cat, arr);
580
+ }
581
+ }
582
+ const out = [];
583
+ for (const [code, name] of catalog.categories) {
584
+ out.push("CATEGORY " + code + " \u2014 " + name);
585
+ for (const t of byCat.get(code) || []) out.push(" TOPIC: " + t);
586
+ }
587
+ return out.join("\n");
588
+ }
589
+ var JSON_ONLY2 = "Return ONLY a JSON object, no markdown fences, no commentary.";
590
+ function parseJsonBlock(text) {
591
+ const start = text.indexOf("{");
592
+ const end = text.lastIndexOf("}");
593
+ if (start < 0 || end <= start) throw new Error("LLM standardization response has no JSON object");
594
+ return JSON.parse(text.slice(start, end + 1));
595
+ }
596
+ async function standardizeConcepts(opts) {
597
+ const { client, catalog, techStack = "python", proposalsPath } = opts;
598
+ const log = opts.onProgress ?? (() => {
599
+ });
600
+ const warnings = [];
601
+ const hasTopics = catalog.topics.size > 0;
602
+ const selSystem = [
603
+ "You pre-select relevant areas of an institutional knowledge tree before a detailed concept alignment pass.",
604
+ hasTopics ? "Given the analysis concepts, pick the TOPICS that could contain matching concepts. Concepts are filed under topics, so topics are the filter dimension." : "Given the analysis concepts, pick the CATEGORIES that could contain matching concepts.",
605
+ "- Be generous: missing a relevant topic corrupts the alignment; an extra topic only costs attention.",
606
+ "- Only codes that appear in the index are valid.",
607
+ JSON_ONLY2
608
+ ].join("\n");
609
+ const selUser = [
610
+ "ANALYSIS CONCEPTS:",
611
+ opts.concepts.map((c) => "- " + c.name + ": " + c.description.slice(0, 160)).join("\n"),
612
+ "",
613
+ "KNOWLEDGE TREE INDEX:",
614
+ renderCategoryTopicIndex(catalog),
615
+ "",
616
+ hasTopics ? 'Return JSON: {"relevant_topics":["TOPIC_CODE"]}' : 'Return JSON: {"relevant_categories":["CATEGORY_CODE"]}'
617
+ ].join("\n");
618
+ const selRes = await client.chat(
619
+ [{ role: "system", content: selSystem }, { role: "user", content: selUser }],
620
+ { temperature: 0, maxTokens: 4096 }
621
+ );
622
+ const sel = parseJsonBlock(selRes.content);
623
+ const selTps = hasTopics ? (sel.relevant_topics || []).map(String).filter(Boolean) : [];
624
+ const selCats = hasTopics ? [] : (sel.relevant_categories || []).map(String).filter(Boolean);
625
+ log("STEP_2_5", "LLM relevance pre-selection (" + (hasTopics ? "topics" : "categories") + "): " + (hasTopics ? selTps.join(",") : selCats.join(",")));
626
+ const shortlist = filterBySelection(catalog, selCats, selTps, opts.concepts);
627
+ log("STEP_2_5", "Filtered tree concepts: " + shortlist.length + "/" + catalog.concepts.length + " shortlisted for alignment");
628
+ if (shortlist.length === 0) throw new Error("Topic/category pre-selection eliminated every tree concept \u2014 fail-closed");
629
+ const system = [
630
+ "You align auto-derived learning concepts with an institutional knowledge tree.",
631
+ "For EACH input concept decide exactly one of:",
632
+ ` 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.`,
633
+ " Adopt the tree's terminology. Only propose new when the tree genuinely has NO concept teaching that knowledge (broader AND narrower both fail).",
634
+ ' 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.',
635
+ " If between 1 and 3 tree concepts are CLOSE but not exact, list their codes in possible_tree_matches for human review.",
636
+ `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) \u2014 keep conceptual keywords even when spelled generically. Maximum 8, ordered most-relevant first.`,
637
+ "Rules:",
638
+ "- Judge by MEANING (definition + keywords), not by string similarity.",
639
+ '- COVERAGE RULE: a "standardized" match must cover ALL primary dimensions of the input concept \u2014 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.',
640
+ "- Context-specific wording does NOT make a new concept: new concept = knowledge absent from the tree, not knowledge applied elsewhere.",
641
+ "- Every input concept MUST receive exactly one decision. Never merge two input concepts into one tree code.",
642
+ "- Prefer proposed_new over a wrong standardized match: a false match corrupts the curriculum.",
643
+ JSON_ONLY2
644
+ ].join("\n");
645
+ const user = [
646
+ "TECH STACK: " + techStack,
647
+ "",
648
+ "ANALYSIS CONCEPTS (to standardize):",
649
+ 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),
650
+ "",
651
+ "KNOWLEDGE TREE SHORTLIST (pre-filtered, " + shortlist.length + " candidate concepts):",
652
+ renderShortlist(shortlist),
653
+ "",
654
+ 'Return JSON: {"decisions":[{"id":"<input id>","decision":"standardized","tree_code":"TREE_CODE","adopted_keywords":["kw1","kw2"],"note":"one sentence"},',
655
+ ' {"id":"<input id>","decision":"proposed_new","proposed_code":"PROPOSED_CODE","proposed_definition":"...","possible_tree_matches":["CODE"]}]}'
656
+ ].join("\n");
657
+ const res = await client.chat(
658
+ [{ role: "system", content: system }, { role: "user", content: user }],
659
+ { temperature: 0, maxTokens: 8192 }
660
+ );
661
+ log("STEP_2_5", "Standardization response received (provider " + res.provider + ")");
662
+ const parsed = parseJsonBlock(res.content);
663
+ const decisions = parsed.decisions ?? [];
664
+ const byId = new Map(decisions.map((d) => [String(d.id), d]));
665
+ const finalDecisions = [];
666
+ const proposals = [];
667
+ for (const c of opts.concepts) {
668
+ const d = byId.get(c.id);
669
+ if (!d || d.decision !== "standardized" && d.decision !== "proposed_new") {
670
+ throw new Error("Concept " + c.id + " (" + c.name + ") has no standardization decision \u2014 fail-closed");
671
+ }
672
+ if (d.decision === "standardized") {
673
+ const tc = catalog.concepts.find((x) => x.code === d.tree_code);
674
+ if (!tc) throw new Error("Concept " + c.id + " standardized to unknown tree code " + d.tree_code + " \u2014 fail-closed");
675
+ const treeKw = new Set(tc.keywords.map((k) => k.toLowerCase()));
676
+ const adopted = (d.adopted_keywords || []).map((k) => String(k)).filter((k) => {
677
+ if (treeKw.has(k.toLowerCase())) return true;
678
+ throw new Error("Concept " + c.id + ' adopted keyword "' + k + '" not in tree concept ' + tc.code + " \u2014 fail-closed");
679
+ });
680
+ if (tc.keywords.length > 0 && adopted.length === 0) {
681
+ throw new Error("Concept " + c.id + " standardized to " + tc.code + " without adopted_keywords \u2014 fail-closed");
682
+ }
683
+ finalDecisions.push({ ...d, id: c.id, tree_code: tc.code, adopted_keywords: adopted });
684
+ warnings.push("Concept " + c.id + " standardized as " + tc.code + " (" + tc.name + "), adopted keywords: " + adopted.join(", ") + (d.note ? " \u2014 " + d.note : ""));
685
+ } else {
686
+ const code = (d.proposed_code || "").toUpperCase().replace(/[^A-Z0-9_]/g, "_");
687
+ if (!/^[A-Z][A-Z0-9_]*$/.test(code)) {
688
+ throw new Error("Concept " + c.id + ' proposed invalid code "' + d.proposed_code + '" \u2014 fail-closed');
689
+ }
690
+ finalDecisions.push({ ...d, id: c.id, proposed_code: code });
691
+ proposals.push({
692
+ code,
693
+ name: c.name,
694
+ description: d.proposed_definition || c.description.slice(0, 300),
695
+ keywords: c.keywords,
696
+ subject_codes: "PY",
697
+ category_codes: "",
698
+ topic_codes: "",
699
+ prerequisite_concept_codes: [],
700
+ status: "proposed",
701
+ source_concept_id: c.id,
702
+ possible_tree_matches: (d.possible_tree_matches || []).filter(Boolean)
703
+ });
704
+ warnings.push("Concept " + c.id + " proposed as NEW: " + code + (d.possible_tree_matches?.length ? " (near matches: " + d.possible_tree_matches.join(", ") + ")" : ""));
705
+ }
706
+ }
707
+ const outPath = proposalsPath || join(tmpdir(), "domain-kit-debug", "concept-proposals.json");
708
+ try {
709
+ mkdirSync(outPath.slice(0, outPath.lastIndexOf("/")), { recursive: true });
710
+ writeFileSync(outPath, JSON.stringify({ generated_at: (/* @__PURE__ */ new Date()).toISOString(), proposals }, null, 2));
711
+ log("STEP_2_5", "Proposals written: " + proposals.length + " -> " + outPath);
712
+ } catch (e) {
713
+ warnings.push("Could not write proposals artifact: " + (e instanceof Error ? e.message : String(e)));
714
+ }
715
+ return { decisions: finalDecisions, proposals, warnings, shortlistSize: shortlist.length, catalogSize: catalog.concepts.length };
716
+ }
717
+
718
+ // src/graph/knowledgeGraphPipeline.ts
719
+ function detectCycles(concepts) {
720
+ const cycles = [];
721
+ const visited = /* @__PURE__ */ new Set();
722
+ const inStack = /* @__PURE__ */ new Set();
723
+ const path = [];
724
+ function dfs(conceptId, prereqMap2) {
725
+ if (inStack.has(conceptId)) {
726
+ const cycleStart = path.indexOf(conceptId);
727
+ if (cycleStart >= 0) {
728
+ cycles.push([...path.slice(cycleStart), conceptId]);
729
+ }
730
+ return;
731
+ }
732
+ if (visited.has(conceptId)) return;
733
+ visited.add(conceptId);
734
+ inStack.add(conceptId);
735
+ path.push(conceptId);
736
+ const prereqs = prereqMap2.get(conceptId) || [];
737
+ for (const prereq of prereqs) {
738
+ dfs(prereq, prereqMap2);
739
+ }
740
+ path.pop();
741
+ inStack.delete(conceptId);
742
+ }
743
+ const prereqMap = /* @__PURE__ */ new Map();
744
+ for (const concept of concepts) {
745
+ prereqMap.set(concept.id, concept.prerequisites || []);
746
+ }
747
+ for (const concept of concepts) {
748
+ if (!visited.has(concept.id)) {
749
+ dfs(concept.id, prereqMap);
750
+ }
751
+ }
752
+ return cycles;
753
+ }
754
+ function breakCycles(concepts, cycles) {
755
+ const removed = [];
756
+ const fixed = concepts.map((c) => ({ ...c, prerequisites: [...c.prerequisites || []] }));
757
+ for (const cycle of cycles) {
758
+ if (cycle.length >= 2) {
759
+ const breaker = cycle[cycle.length - 2];
760
+ const target = cycle[cycle.length - 1];
761
+ for (const concept of fixed) {
762
+ if (concept.id === breaker) {
763
+ concept.prerequisites = concept.prerequisites.filter((p) => p !== target);
764
+ removed.push({ from: breaker, to: target });
765
+ }
766
+ }
767
+ }
768
+ }
769
+ return { fixed, removed };
770
+ }
771
+ function topologicalSort(concepts) {
772
+ const inDegree = /* @__PURE__ */ new Map();
773
+ const adjacency = /* @__PURE__ */ new Map();
774
+ for (const concept of concepts) {
775
+ inDegree.set(concept.id, 0);
776
+ adjacency.set(concept.id, []);
777
+ }
778
+ for (const concept of concepts) {
779
+ for (const prereq of concept.prerequisites || []) {
780
+ adjacency.get(prereq)?.push(concept.id);
781
+ inDegree.set(concept.id, (inDegree.get(concept.id) || 0) + 1);
782
+ }
783
+ }
784
+ const queue = [];
785
+ for (const [id, degree] of inDegree) {
786
+ if (degree === 0) queue.push(id);
787
+ }
788
+ const sorted = [];
789
+ while (queue.length > 0) {
790
+ const current = queue.shift();
791
+ sorted.push(current);
792
+ for (const neighbor of adjacency.get(current) || []) {
793
+ const newDegree = (inDegree.get(neighbor) || 1) - 1;
794
+ inDegree.set(neighbor, newDegree);
795
+ if (newDegree === 0) queue.push(neighbor);
796
+ }
797
+ }
798
+ if (sorted.length !== concepts.length) {
799
+ console.warn(`[WARN] Topological sort incomplete: ${sorted.length}/${concepts.length} concepts sorted`);
800
+ }
801
+ return sorted;
802
+ }
803
+ async function generateKnowledgeGraph(options) {
804
+ const { subject, description, syllabusText, gradeBand, domain, techStack, llmConfig, onProgress } = options;
805
+ const warnings = [];
806
+ const log = (step, msg) => {
807
+ console.log(`[KG-${step}] ${msg}`);
808
+ onProgress?.(step, msg);
809
+ };
810
+ log("STEP_1", "Decomposing subject into concepts...");
811
+ const client = createLlmClient(llmConfig);
812
+ const maxSyllabusChars = parseInt(process.env.KG_MAX_SYLLABUS_CHARS || "16000", 10);
813
+ let truncatedSyllabus = "";
814
+ if (syllabusText) {
815
+ if (syllabusText.length > maxSyllabusChars) {
816
+ truncatedSyllabus = syllabusText.slice(0, maxSyllabusChars);
817
+ warnings.push(`Syllabus truncated from ${syllabusText.length} to ${maxSyllabusChars} chars \u2014 may miss some concepts`);
818
+ } else {
819
+ truncatedSyllabus = syllabusText;
820
+ }
821
+ }
822
+ const systemPrompt = "You are an expert curriculum designer. Decompose the given subject into a structured knowledge graph with concepts, prerequisites, and problem types.\n\nCRITICAL RULES:\n1. Each concept MUST have the three depth layers, authored against this CONTRACT:\n - ulo (WHAT + WHY): bound to the CONCEPT's intrinsic NATURE. It explains what the\n concept is and why it exists \u2014 the problem it solves in principle. It must be\n TECHNOLOGY-AGNOSTIC: never name a concrete library, API, function, file format,\n tool or language feature. Typical assessment level: Remember / Understand.\n - cio (HOW): the MECHANISM \u2014 how the concept works and solves that problem, step\n by step. Still bound to the concept's nature: more concrete than the ULO, but\n NOT tied to one specific technology (no concrete API names). CIO capability is\n assessed INDIRECTLY, through completing contextual work, not in isolation.\n - sio (IMPLEMENTATION): an array of 2-4 items. EVERY item MUST reference concrete\n KEYWORDS/technologies (a real API, function, module, file, or named pattern) and\n describe a completable, context-specific implementation task. Application,\n Analysis and Creation skills are assessed INDIRECTLY through completing these\n items. There is NO fixed Bloom ceiling for a layer \u2014 but concreteness MUST\n strictly increase: SIO more technology-bound than CIO, CIO more concrete than ULO.\n - prerequisites: concept IDs that must be learned first (MUST NOT create cycles)\n - problem_types: 2-4 problem types with bloom_level and difficulty. Remember and\n Understand problem types test the ULO/CIO directly; Apply-and-above types are\n proxies for SIO completion in context.\n - techniques: methods, formulas, tools\n2. Prerequisite chains MUST be acyclic (no concept can depend on itself or create a loop)\n3. Concepts should be ordered by prerequisite dependency (topological sort)\n4. Problem types should range from Remember to Apply (not all at same level)\n5. Group concepts into categories (chapters/sections)\n6. ALL text in ENGLISH (even if input is Vietnamese)\n7. NEVER invent concepts not present in the syllabus\n8. Return JSON matching the KnowledgeGraphSchema";
823
+ const userPrompt = `Subject: ${subject}
824
+ ${description ? `Description: ${description}` : ""}
825
+ ${truncatedSyllabus ? `Syllabus:
826
+ ${truncatedSyllabus}` : ""}
827
+ ${gradeBand ? `Grade band: ${gradeBand[0]}-${gradeBand[1]}` : ""}
828
+ ${domain ? `Domain: ${domain}` : ""}
829
+
830
+ Return JSON:
831
+ {
832
+ "subject": {
833
+ "id": "${subject.toLowerCase().replace(/\s+/g, "-").slice(0, 30)}",
834
+ "name": "${subject}",
835
+ "description": "...",
836
+ "domain": "${domain || "other"}",
837
+ "grade_band": ${gradeBand ? `[${gradeBand[0]}, ${gradeBand[1]}]` : "[6, 12]"}
838
+ },
839
+ "concepts": [
840
+ {
841
+ "id": "C1",
842
+ "name": "Concept name",
843
+ "description": "Brief description",
844
+ "category": "category_id",
845
+ "ulo": "WHAT + WHY in technology-agnostic language: what the concept is and the problem it exists to solve. No library/API/tool names.",
846
+ "cio": "HOW the mechanism works, still technology-agnostic but more concrete than the ULO.",
847
+ "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"],
848
+ "prerequisites": [],
849
+ "estimated_minutes": 30,
850
+ "problem_types": [
851
+ {
852
+ "id": "PT-C1-01",
853
+ "name": "Problem type name",
854
+ "description": "What this problem type tests",
855
+ "bloom_level": "Remember",
856
+ "difficulty": "easy",
857
+ "estimated_minutes": 10
858
+ }
859
+ ],
860
+ "techniques": ["technique 1", "technique 2"],
861
+ "common_mistakes": ["mistake 1"]
862
+ }
863
+ ],
864
+ "categories": [
865
+ {
866
+ "id": "cat1",
867
+ "name": "Category name",
868
+ "description": "Category description",
869
+ "concept_ids": ["C1", "C2"],
870
+ "order": 1
871
+ }
872
+ ],
873
+ "learning_path": [
874
+ {"concept_id": "C1", "order": 1, "depends_on": []},
875
+ {"concept_id": "C2", "order": 2, "depends_on": ["C1"]}
876
+ ]
877
+ }`;
878
+ const result = await llmChatJson(client, systemPrompt, userPrompt, {
879
+ temperature: 0.1,
880
+ maxTokens: parseInt(process.env.KG_MAX_TOKENS || "65536", 10)
881
+ });
882
+ log("STEP_2", "Validating and cleaning knowledge graph...");
883
+ const concepts = result.concepts || [];
884
+ const categories = result.categories || [];
885
+ {
886
+ const STOP = /* @__PURE__ */ new Set(["and", "the", "for", "with", "from", "that", "this", "into", "when", "while", "using", "their", "your", "each", "how", "why", "what", "between", "through", "about"]);
887
+ const tokensFrom = (text) => text.toLowerCase().replace(/[^a-z0-9\s-]/g, " ").split(/\s+/).filter((w) => w.length >= 4 && !STOP.has(w));
888
+ for (const c of concepts) {
889
+ const existing = (c.keywords || []).map((k) => String(k).trim()).filter(Boolean);
890
+ if (existing.length === 0) {
891
+ const derived = [.../* @__PURE__ */ new Set([...tokensFrom(c.name), ...tokensFrom(c.description || "")])].slice(0, 5);
892
+ if (derived.length === 0) {
893
+ throw new Error("Concept " + c.id + " (" + c.name + ") has no keywords and none could be derived from name/description \u2014 fail-closed");
894
+ }
895
+ c.keywords = derived;
896
+ warnings.push("Concept " + c.id + ": empty keyword set - derived " + derived.join(", ") + " from name/description");
897
+ } else {
898
+ c.keywords = existing;
899
+ }
900
+ }
901
+ }
902
+ const rawPath = result.learning_path;
903
+ let learningPath = (rawPath || []).map((s) => ({
904
+ concept_id: String(s.concept_id || ""),
905
+ order: Number(s.order || 0),
906
+ depends_on: Array.isArray(s.depends_on) ? s.depends_on.map(String) : [],
907
+ milestone_name: String(s.milestone_name || "")
908
+ }));
909
+ const conceptIds = new Set(concepts.map((c) => c.id));
910
+ for (const concept of concepts) {
911
+ for (const prereq of concept.prerequisites || []) {
912
+ if (!conceptIds.has(prereq)) {
913
+ warnings.push(`Concept ${concept.id} references non-existent prerequisite ${prereq} \u2014 removed`);
914
+ concept.prerequisites = (concept.prerequisites || []).filter((p) => p !== prereq);
915
+ }
916
+ }
917
+ }
918
+ if (options.knowledgeTreePath) {
919
+ const catalog = loadKnowledgeTreeCatalog(options.knowledgeTreePath);
920
+ log("STEP_2_5", "Knowledge tree loaded: " + catalog.concepts.length + " concepts from " + catalog.path.split("/").pop());
921
+ const std = await standardizeConcepts({
922
+ client,
923
+ concepts: concepts.map((c) => ({
924
+ id: c.id,
925
+ name: c.name,
926
+ description: c.description || "",
927
+ keywords: c.keywords || []
928
+ })),
929
+ catalog,
930
+ techStack,
931
+ proposalsPath: options.proposalsPath,
932
+ onProgress: log
933
+ });
934
+ warnings.push(...std.warnings);
935
+ const codeByStd = new Map(std.decisions.map((d) => [d.id, d]));
936
+ for (const c of concepts) {
937
+ const d = codeByStd.get(c.id);
938
+ if (!d) throw new Error("Concept " + c.id + " missing standardization decision \u2014 fail-closed");
939
+ if (d.decision === "standardized") {
940
+ c.standardization = "standardized";
941
+ c.tree_code = d.tree_code;
942
+ c.code = d.tree_code;
943
+ const tc = catalog.concepts.find((x) => x.code === d.tree_code);
944
+ if (tc) {
945
+ for (const k of d.adopted_keywords || []) {
946
+ if (!(c.keywords || []).some((x) => x.toLowerCase() === k.toLowerCase())) {
947
+ c.keywords = [...c.keywords || [], k];
948
+ }
949
+ }
950
+ c.tree_prerequisites = tc.prerequisiteCodes;
951
+ }
952
+ } else {
953
+ c.standardization = "proposed_new";
954
+ c.code = d.proposed_code;
955
+ }
956
+ }
957
+ const idByTreeCode = new Map(concepts.filter((c) => c.tree_code).map((c) => [c.tree_code, c.id]));
958
+ for (const c of concepts) {
959
+ for (const tp of c.tree_prerequisites || []) {
960
+ const target = idByTreeCode.get(tp);
961
+ if (target && target !== c.id && !(c.prerequisites || []).includes(target)) {
962
+ c.prerequisites = [...c.prerequisites || [], target];
963
+ warnings.push("Prereq seeded from tree: " + c.id + " <- " + tp + " (" + target + ")");
964
+ }
965
+ }
966
+ }
967
+ log("STEP_2_5", "Standardized: " + std.decisions.filter((d) => d.decision === "standardized").length + ", proposed new: " + std.decisions.filter((d) => d.decision === "proposed_new").length);
968
+ }
969
+ log("STEP_3", "Checking for prerequisite cycles...");
970
+ const cycles = detectCycles(concepts);
971
+ if (cycles.length > 0) {
972
+ log("STEP_3", `Found ${cycles.length} cycle(s) in prerequisite chain \u2014 breaking cycles`);
973
+ for (const cycle of cycles) {
974
+ warnings.push(`Cycle detected: ${cycle.join(" \u2192 ")} \u2014 breaking at weakest edge`);
975
+ }
976
+ const { fixed, removed } = breakCycles(concepts, cycles);
977
+ for (let i = 0; i < concepts.length; i++) {
978
+ const fixedConcept = fixed.find((f) => f.id === concepts[i].id);
979
+ if (fixedConcept) {
980
+ concepts[i] = { ...concepts[i], prerequisites: fixedConcept.prerequisites };
981
+ }
982
+ }
983
+ for (const { from, to } of removed) {
984
+ warnings.push(`Removed prerequisite edge: ${from} \u2192 ${to} (cycle breaker)`);
985
+ }
986
+ }
987
+ log("STEP_4", "Topological sort of concepts...");
988
+ const sortedIds = topologicalSort(concepts);
989
+ learningPath = sortedIds.map((id, idx) => {
990
+ const concept = concepts.find((c) => c.id === id);
991
+ return {
992
+ concept_id: id,
993
+ order: idx + 1,
994
+ depends_on: concept?.prerequisites || [],
995
+ milestone_name: ""
996
+ };
997
+ });
998
+ log("STEP_5", "Authoring ULO/CIO/SIO depth layers hierarchically...");
999
+ {
1000
+ const lo = await authorDepthLayersHierarchically(
1001
+ client,
1002
+ concepts.map((c) => ({ id: c.id, name: c.name, description: c.description, keywords: c.keywords })),
1003
+ techStack || (domain === "software" || domain === "technology" ? "python" : domain || "general"),
1004
+ warnings
1005
+ );
1006
+ const codeByConceptId = assignConceptCodes(concepts.map((c) => ({ id: c.id, name: c.name })));
1007
+ const techTag = techTagFor(techStack || (domain === "software" || domain === "technology" ? "python" : domain || "general"));
1008
+ for (const concept of concepts) {
1009
+ concept.ulo = lo.uloByConcept[concept.id] || concept.ulo || "";
1010
+ concept.cio = lo.cioByConcept[concept.id] || concept.cio || "";
1011
+ if (lo.sioByConcept[concept.id] && lo.sioByConcept[concept.id].length > 0) {
1012
+ concept.sio = lo.sioByConcept[concept.id];
1013
+ }
1014
+ concept.code = concept.code || codeByConceptId[concept.id];
1015
+ concept.ulo_code = concept.ulo ? uloCode(concept.code) : concept.ulo_code;
1016
+ concept.cio_code = concept.cio ? cioCode(concept.code, 1, cioActionSlug(concept.cio)) : concept.cio_code;
1017
+ concept.sio_codes = concept.sio.length > 0 ? concept.sio.map((_, i) => sioCode(techTag, concept.code, i + 1)) : concept.sio_codes;
1018
+ }
1019
+ log("STEP_5", "Depth layers authored: " + concepts.length + " concepts, audit " + lo.audits.filter((a) => a.passed).length + "/" + concepts.length + " passed");
1020
+ }
1021
+ for (const step of learningPath) {
1022
+ if (!conceptIds.has(step.concept_id)) {
1023
+ warnings.push(`Learning path references non-existent concept ${step.concept_id}`);
1024
+ }
1025
+ }
1026
+ log("STEP_2", `Validated ${concepts.length} concepts, ${categories.length} categories, ${learningPath.length} learning path steps`);
1027
+ return {
1028
+ knowledgeGraph: {
1029
+ schema_version: 1,
1030
+ type: "knowledge_graph",
1031
+ subject: result.subject,
1032
+ concepts,
1033
+ categories,
1034
+ learning_path: learningPath
1035
+ },
1036
+ warnings
1037
+ };
1038
+ }
1039
+
1040
+ // src/graph/hybridGraphPipeline.ts
1041
+ async function generateHybridGraph(options) {
1042
+ const { projectGraph, knowledgeGraph, llmConfig, onProgress } = options;
1043
+ const warnings = [];
1044
+ const log = (step, msg) => {
1045
+ console.log("[HG-" + step + "] " + msg);
1046
+ onProgress?.(step, msg);
1047
+ };
1048
+ const features = projectGraph.features || [];
1049
+ const concepts = knowledgeGraph.concepts || [];
1050
+ if (features.length === 0 || concepts.length === 0) {
1051
+ warnings.push("No features or concepts to link");
1052
+ return {
1053
+ hybridGraph: {
1054
+ schema_version: 1,
1055
+ type: "hybrid_graph",
1056
+ project_graph: projectGraph,
1057
+ knowledge_graph: knowledgeGraph,
1058
+ links: [],
1059
+ phases: [],
1060
+ description: "",
1061
+ total_project_minutes: 0,
1062
+ total_concept_minutes: 0,
1063
+ estimated_total_minutes: 0
1064
+ },
1065
+ warnings
1066
+ };
1067
+ }
1068
+ const client = createLlmClient(llmConfig);
1069
+ const featuresList = features.map(
1070
+ (f) => "- " + f.id + ": " + f.name + " - " + (f.description || "") + " (keywords: " + (f.steps || []).flatMap((s) => s.keywords || []).slice(0, 5).join(", ") + ")"
1071
+ ).join("\n");
1072
+ const conceptsList = concepts.map(
1073
+ (c) => "- " + c.id + ": " + c.name + " - ULO: " + (c.ulo || "").slice(0, 100) + " (prerequisites: " + (c.prerequisites || []).join(", ") + ")"
1074
+ ).join("\n");
1075
+ const systemPrompt = "You are a curriculum architect. Link project features to knowledge concepts.\nFor each feature, determine which concepts it requires or demonstrates.\n\nRULES:\n1. Each link must have a relationship type: requires | demonstrates | applies | extends\n2. depth indicates how deeply the feature needs the concept:\n - ulo: feature only needs WHAT+WHY understanding\n - cio: feature needs HOW understanding\n - sio: feature needs specific implementation knowledge\n3. estimated_prereq_minutes: how many minutes of concept learning before this feature\n4. Not every feature needs every concept - only create meaningful links\n5. Return JSON object with a links array";
1076
+ const userPrompt = "FEATURES:\n" + featuresList + "\n\nCONCEPTS:\n" + conceptsList + "\n\nCreate links between features and concepts. Return JSON.\n";
1077
+ const result = await llmChatJson(client, systemPrompt, userPrompt, {
1078
+ temperature: 0.1,
1079
+ maxTokens: 16384
1080
+ });
1081
+ const rawLinks = result.links || [];
1082
+ const featureIds = new Set(features.map((f) => f.id));
1083
+ const conceptIds = new Set(concepts.map((c) => c.id));
1084
+ const validLinks = [];
1085
+ for (const link of rawLinks) {
1086
+ const fid = String(link.feature_id || "");
1087
+ const cid = String(link.concept_id || "");
1088
+ if (!featureIds.has(fid)) {
1089
+ warnings.push("Link references non-existent feature " + fid);
1090
+ continue;
1091
+ }
1092
+ if (!conceptIds.has(cid)) {
1093
+ warnings.push("Link references non-existent concept " + cid);
1094
+ continue;
1095
+ }
1096
+ validLinks.push({
1097
+ feature_id: fid,
1098
+ concept_id: cid,
1099
+ relationship: link.relationship || "requires",
1100
+ depth: link.depth || "cio",
1101
+ description: String(link.description || ""),
1102
+ estimated_prereq_minutes: Number(link.estimated_prereq_minutes) || 0,
1103
+ phase_id: ""
1104
+ });
1105
+ }
1106
+ log("STEP_1", "Generated " + validLinks.length + " feature-concept links");
1107
+ const phases = await decomposePhases({
1108
+ features,
1109
+ concepts,
1110
+ links: validLinks,
1111
+ client,
1112
+ log,
1113
+ warnings
1114
+ });
1115
+ const phaseByFeature = /* @__PURE__ */ new Map();
1116
+ for (const ph of phases) {
1117
+ for (const fid of ph.feature_ids) phaseByFeature.set(fid, ph.id);
1118
+ }
1119
+ for (const link of validLinks) link.phase_id = phaseByFeature.get(link.feature_id) || "";
1120
+ log("STEP_3", "Calculating totals...");
1121
+ const totalProjectMinutes = features.reduce((sum, f) => {
1122
+ const featureMinutes = (f.steps || []).reduce((s, step) => s + (step.effort?.estimated_minutes || 15), 0);
1123
+ return sum + featureMinutes;
1124
+ }, 0);
1125
+ const totalConceptMinutes = concepts.reduce((sum, c) => sum + (c.estimated_minutes || 30), 0);
1126
+ const prereqMinutesByConcept = /* @__PURE__ */ new Map();
1127
+ for (const link of validLinks) {
1128
+ const mins = link.estimated_prereq_minutes || 0;
1129
+ if (mins > 0) {
1130
+ const existing = prereqMinutesByConcept.get(link.concept_id) || 0;
1131
+ prereqMinutesByConcept.set(link.concept_id, Math.max(existing, mins));
1132
+ }
1133
+ }
1134
+ const totalPrereqMinutes = Array.from(prereqMinutesByConcept.values()).reduce((a, b) => a + b, 0);
1135
+ return {
1136
+ hybridGraph: {
1137
+ schema_version: 1,
1138
+ type: "hybrid_graph",
1139
+ project_graph: projectGraph,
1140
+ knowledge_graph: knowledgeGraph,
1141
+ links: validLinks,
1142
+ phases,
1143
+ description: "Progressive completion path: " + phases.length + " phases, " + features.length + " features, " + concepts.length + " concepts",
1144
+ total_project_minutes: totalProjectMinutes,
1145
+ total_concept_minutes: totalConceptMinutes,
1146
+ estimated_total_minutes: totalProjectMinutes + totalPrereqMinutes
1147
+ },
1148
+ warnings
1149
+ };
1150
+ }
1151
+ function auditPhasePlan(plan, features, concepts, links, warnings, log) {
1152
+ const knownFeatureIds = new Set(features.map((f) => f.id));
1153
+ const knownConceptIds = new Set(concepts.map((c) => c.id));
1154
+ const prereqOf = /* @__PURE__ */ new Map();
1155
+ for (const c of concepts) prereqOf.set(c.id, (c.prerequisites || []).filter((p) => knownConceptIds.has(p)));
1156
+ const phases = [];
1157
+ const featurePhase = /* @__PURE__ */ new Map();
1158
+ const newIntroPhase = /* @__PURE__ */ new Map();
1159
+ const errors = [];
1160
+ plan.forEach((rp, idx) => {
1161
+ const id = String(rp.id || "PH" + (idx + 1));
1162
+ const order = idx + 1;
1163
+ const name = String(rp.name || "Phase " + order).slice(0, 80);
1164
+ const productCompletion = String(rp.product_completion || "").trim();
1165
+ const rawFeatureIds = Array.isArray(rp.feature_ids) ? rp.feature_ids.map(String) : [];
1166
+ const rawIntros = Array.isArray(rp.introduces) ? rp.introduces : [];
1167
+ if (!productCompletion) {
1168
+ errors.push("Phase " + id + ": product_completion is empty - every phase must describe the product completion level");
1169
+ }
1170
+ const featureIdsForPhase = [];
1171
+ for (const fid of rawFeatureIds) {
1172
+ if (!knownFeatureIds.has(fid)) {
1173
+ errors.push("Phase " + id + ": unknown feature " + fid);
1174
+ continue;
1175
+ }
1176
+ if (featurePhase.has(fid)) {
1177
+ errors.push("Feature " + fid + " assigned to both " + featurePhase.get(fid) + " and " + id + " - each feature must belong to exactly one phase");
1178
+ continue;
1179
+ }
1180
+ featurePhase.set(fid, id);
1181
+ featureIdsForPhase.push(fid);
1182
+ }
1183
+ const introductions = [];
1184
+ for (const ri of rawIntros) {
1185
+ const cid = String(ri.concept_id || "");
1186
+ if (!knownConceptIds.has(cid)) {
1187
+ errors.push("Phase " + id + ": introduces unknown concept " + cid);
1188
+ continue;
1189
+ }
1190
+ const aspect = String(ri.aspect || "new") === "advanced" ? "advanced" : "new";
1191
+ if (aspect === "advanced") {
1192
+ const first = newIntroPhase.get(cid);
1193
+ if (first === void 0) {
1194
+ errors.push("Phase " + id + ": advanced introduction of " + cid + " before any new introduction - revisit requires prior introduction");
1195
+ continue;
1196
+ }
1197
+ if (first >= order) {
1198
+ errors.push("Phase " + id + ": advanced introduction of " + cid + " must come after its new introduction in phase " + first);
1199
+ continue;
1200
+ }
1201
+ } else if (newIntroPhase.has(cid)) {
1202
+ errors.push("Phase " + id + ": duplicate new introduction of " + cid + " (already introduced in phase " + newIntroPhase.get(cid) + ")");
1203
+ continue;
1204
+ } else {
1205
+ newIntroPhase.set(cid, order);
1206
+ }
1207
+ for (const pre of prereqOf.get(cid) || []) {
1208
+ if (!newIntroPhase.has(pre)) {
1209
+ errors.push("Phase " + id + ": concept " + cid + " introduced before its prerequisite " + pre + " is introduced - violates the prerequisite chain");
1210
+ }
1211
+ }
1212
+ introductions.push({ concept_id: cid, aspect, note: String(ri.note || "") });
1213
+ }
1214
+ phases.push({
1215
+ id,
1216
+ order,
1217
+ name,
1218
+ product_completion: productCompletion,
1219
+ feature_ids: featureIdsForPhase,
1220
+ introduces: introductions
1221
+ });
1222
+ });
1223
+ const missing = features.map((f) => f.id).filter((fid) => !featurePhase.has(fid));
1224
+ if (missing.length > 0) {
1225
+ errors.push("Features not assigned to any phase: " + missing.join(", "));
1226
+ }
1227
+ const firstConsumerPhase = /* @__PURE__ */ new Map();
1228
+ const phaseOrderByFeature = /* @__PURE__ */ new Map();
1229
+ for (const ph of phases) for (const fid of ph.feature_ids) phaseOrderByFeature.set(fid, ph.order);
1230
+ for (const l of links) {
1231
+ const po = phaseOrderByFeature.get(l.feature_id);
1232
+ if (po === void 0) continue;
1233
+ const cur = firstConsumerPhase.get(l.concept_id);
1234
+ if (cur === void 0 || po < cur) firstConsumerPhase.set(l.concept_id, po);
1235
+ }
1236
+ for (const [cid, consumerOrder] of firstConsumerPhase) {
1237
+ const intro = newIntroPhase.get(cid);
1238
+ if (intro === void 0) {
1239
+ errors.push("Concept " + cid + " is consumed from phase " + consumerOrder + " but never introduced in any phase");
1240
+ } else if (intro > consumerOrder) {
1241
+ errors.push("Concept " + cid + " introduced in phase " + intro + " but first consumed in phase " + consumerOrder + " - introduction must come no later than first consumption");
1242
+ }
1243
+ }
1244
+ return { phases, errors };
1245
+ }
1246
+ async function decomposePhases(args) {
1247
+ const { features, concepts, links, client, log, warnings } = args;
1248
+ const featureList = features.map(
1249
+ (f) => "- " + f.id + ": " + f.name + " - " + (f.description || "").slice(0, 120)
1250
+ ).join("\n");
1251
+ const conceptList = concepts.map(
1252
+ (c) => "- " + c.id + ": " + c.name + " (prerequisites: " + ((c.prerequisites || []).join(", ") || "none") + ")"
1253
+ ).join("\n");
1254
+ const linkList = links.map(
1255
+ (l) => "- " + l.feature_id + " -> " + l.concept_id + " (" + l.depth + ")"
1256
+ ).join("\n") || "(none)";
1257
+ const systemPrompt = "You decompose a software project build into PROGRESSIVE COMPLETION PHASES for learning purposes.\n\nA phase is NOT a feature and NOT a milestone list: it is a cross-feature slice of the\nproduct whose completion yields a DEMONSTRABLY more complete product. Build up gradually:\nthe product grows feature by feature across phases, and each phase adds its features to\nwhat previous phases already built.\n\nRULES:\n1. Every feature must be assigned to EXACTLY ONE phase (no feature reused, none skipped).\n2. Phases are ordered; later phases depend on earlier ones and yield a more complete product.\n3. product_completion describes concretely what the product can DO once the phase is done.\n4. introduces lists which concepts the phase must teach BEFORE its feature work starts:\n - aspect new: first time the concept appears in the course\n - aspect advanced: a concept introduced in an EARLIER phase, revisited here at a\n higher depth (an advanced aspect of the same concept, e.g. validation rules on top\n of basic data modeling). Use the note field to say which aspect.\n5. A concept MUST be introduced (new) no later than the first phase that consumes it.\n6. A concept must not be introduced before its own prerequisites are introduced.\n7. Typically 3-6 phases for a small project; keep phases balanced.\n8. Phase 1 usually covers project setup/foundation features plus the first minimal slice.\n9. Return JSON only.";
1258
+ const baseUserPrompt = "FEATURES:\n" + featureList + "\n\nCONCEPTS:\n" + conceptList + "\n\nFEATURE-CONCEPT LINKS:\n" + linkList + "\n\nReturn 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";
1259
+ const MAX_DECOMPOSE_ATTEMPTS = 3;
1260
+ let auditErrors = [];
1261
+ let phases = [];
1262
+ let rawPhases = [];
1263
+ for (let attempt = 1; attempt <= MAX_DECOMPOSE_ATTEMPTS; attempt++) {
1264
+ const userPrompt = attempt === 1 ? baseUserPrompt : baseUserPrompt + "\nYOUR PREVIOUS PLAN VIOLATED THESE CONTRACT RULES (fix ALL of them):\n" + auditErrors.map((e) => "- " + e).join("\n") + "\nReturn a corrected full phases array.\n";
1265
+ const result = await llmChatJson(client, systemPrompt, userPrompt, {
1266
+ temperature: 0.1,
1267
+ maxTokens: 16384
1268
+ });
1269
+ rawPhases = result.phases || [];
1270
+ if (rawPhases.length === 0) {
1271
+ if (attempt === MAX_DECOMPOSE_ATTEMPTS) {
1272
+ throw new Error("Phase decomposition returned zero phases - fail-closed abort");
1273
+ }
1274
+ auditErrors = ["Returned zero phases"];
1275
+ continue;
1276
+ }
1277
+ ({ phases, errors: auditErrors } = auditPhasePlan(rawPhases, features, concepts, links));
1278
+ if (auditErrors.length === 0) break;
1279
+ if (attempt < MAX_DECOMPOSE_ATTEMPTS) {
1280
+ log("STEP_2", "Contract violations (" + auditErrors.length + ") - repairing (attempt " + (attempt + 1) + "/" + MAX_DECOMPOSE_ATTEMPTS + ")");
1281
+ }
1282
+ }
1283
+ if (auditErrors.length > 0) {
1284
+ throw new Error(
1285
+ "Phase decomposition violated the progressive-completion contract (" + auditErrors.length + " issue(s)):\n" + auditErrors.map((e) => " - " + e).join("\n") + "\nRe-run the pipeline - a phase model that cannot be trusted is worse than no output."
1286
+ );
1287
+ }
1288
+ if (phases.length === 1 && features.length > 2) {
1289
+ warnings.push("Only one phase for " + features.length + " features - progressive decomposition likely too coarse");
1290
+ }
1291
+ log("STEP_2", "Decomposed into " + phases.length + " phases: " + phases.map((p) => p.id + "(" + p.feature_ids.length + "F/" + p.introduces.length + "K)").join(", "));
1292
+ return phases;
1293
+ }
1294
+
1295
+ export { CIO_CODE_RE, CONCEPT_CODE_RE, LEARNER_CLAUSE, SIO_CODE_RE, ULO_CODE_RE, assignConceptCodes, auditDepthLayers, cioActionSlug, cioCode, conceptCodeFromName, generateHybridGraph, generateKnowledgeGraph, sioCode, standardStatement, techTagFor, uloCode };
1296
+ //# sourceMappingURL=chunk-3VVPSRAM.mjs.map
1297
+ //# sourceMappingURL=chunk-3VVPSRAM.mjs.map