@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,2167 @@
1
+ 'use strict';
2
+
3
+ var fs = require('fs');
4
+ var os = require('os');
5
+ var path = require('path');
6
+
7
+ // src/utils/llmClient.ts
8
+ var LlmClientError = class extends Error {
9
+ constructor(message, status, cause) {
10
+ super(message);
11
+ this.status = status;
12
+ this.cause = cause;
13
+ this.name = "LlmClientError";
14
+ }
15
+ };
16
+ function resolveProviderChain(config) {
17
+ const chain = [];
18
+ const push = (label, baseUrl, apiKey, model) => {
19
+ if (apiKey && baseUrl && model && !chain.some((c) => c.baseUrl === baseUrl && c.model === model)) {
20
+ chain.push({ label, baseUrl, apiKey, model });
21
+ }
22
+ };
23
+ if (config?.apiKey) {
24
+ push("config", config.baseUrl || "https://api.openai.com/v1", config.apiKey, config.model || "gpt-4o-mini");
25
+ }
26
+ push("legacy", process.env.LLM_BASE_URL || process.env.OPENAI_BASE_URL || "", process.env.LLM_API_KEY || process.env.OPENAI_API_KEY || "", process.env.LLM_MODEL || process.env.LLM_TIER_FAST || "");
27
+ push("dashscope", process.env.DASHSCOPE_BASE_URL || process.env.ALIBABA_BASE_URL || "", process.env.DASHSCOPE_API_KEY || process.env.ALIBABA_API_KEY || "", process.env.DASHSCOPE_MODEL || process.env.DEFAULT_AI_MODEL || "");
28
+ push("nvidia", "https://integrate.api.nvidia.com/v1", process.env.NVIDIA_API_KEY || "", process.env.NVIDIA_MODEL || "nvidia/nemotron-3-ultra-550b-a55b");
29
+ push("openrouter", "https://openrouter.ai/api/v1", process.env.OPENROUTER_API_KEY || "", process.env.OPENROUTER_MODEL || "nvidia/nemotron-3-ultra-550b-a55b");
30
+ if (process.env.OPENROUTER_MODEL) {
31
+ const or = chain.find((c) => c.label === "openrouter");
32
+ if (or) {
33
+ const rest = chain.filter((c) => c !== or);
34
+ return [or, ...rest];
35
+ }
36
+ }
37
+ return chain;
38
+ }
39
+ var MIN_REQUEST_INTERVAL_MS = 2500;
40
+ var lastRequestAt = 0;
41
+ async function pacedDelay() {
42
+ const wait = lastRequestAt + MIN_REQUEST_INTERVAL_MS - Date.now();
43
+ if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));
44
+ lastRequestAt = Date.now();
45
+ }
46
+ function createLlmClient(config) {
47
+ const chain = resolveProviderChain(config);
48
+ const primary = chain[0];
49
+ if (!primary) {
50
+ throw new LlmClientError(
51
+ "No LLM provider configured. Set NVIDIA_API_KEY (primary) and/or OPENROUTER_API_KEY (fallback), or pass llmConfig."
52
+ );
53
+ }
54
+ primary.apiKey;
55
+ primary.baseUrl;
56
+ const model = primary.model;
57
+ async function chat(messages, options) {
58
+ const temperature = options?.temperature ?? config?.temperature ?? 0.1;
59
+ const maxTokens = options?.maxTokens ?? config?.maxTokens ?? parseInt(process.env.LLM_MAX_TOKENS || "65536", 10);
60
+ const attempts = [];
61
+ let lastError = null;
62
+ const TRANSIENT = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
63
+ const REQUEST_TIMEOUT_MS = Number(process.env.LLM_REQUEST_TIMEOUT_MS || 3e5);
64
+ const MAX_CHAIN_ROUNDS = 3;
65
+ for (let round = 1; round <= MAX_CHAIN_ROUNDS; round++) {
66
+ if (round > 1) {
67
+ attempts.push("round " + (round - 1) + " failed \u2014 backing off 20s before rewalking the chain");
68
+ await new Promise((resolve) => setTimeout(resolve, 2e4));
69
+ }
70
+ for (const provider of chain) {
71
+ try {
72
+ const headers = {
73
+ "Content-Type": "application/json",
74
+ "Authorization": `Bearer ${provider.apiKey}`
75
+ };
76
+ const payload = {
77
+ model: provider.model,
78
+ messages,
79
+ temperature,
80
+ max_tokens: maxTokens
81
+ };
82
+ await pacedDelay();
83
+ const doFetch = () => fetch(`${provider.baseUrl}/chat/completions`, {
84
+ method: "POST",
85
+ headers: {
86
+ "Content-Type": "application/json",
87
+ "Authorization": `Bearer ${provider.apiKey}`
88
+ },
89
+ body: JSON.stringify({
90
+ model: provider.model,
91
+ messages,
92
+ temperature,
93
+ max_tokens: maxTokens
94
+ }),
95
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
96
+ });
97
+ let response;
98
+ try {
99
+ response = await doFetch();
100
+ } catch (netErr) {
101
+ attempts.push(`${provider.label}: network error (${netErr instanceof Error ? netErr.message : String(netErr)}) \u2014 retrying once`);
102
+ await new Promise((r) => setTimeout(r, 5e3));
103
+ lastRequestAt = Date.now();
104
+ response = await doFetch();
105
+ }
106
+ if (!response.ok) {
107
+ const body = await response.text().catch(() => "");
108
+ const err = new LlmClientError(
109
+ `[${provider.label}] LLM API error: ${response.status} ${response.statusText} \u2014 ${body.slice(0, 200)}`,
110
+ response.status
111
+ );
112
+ if (response.status === 429) {
113
+ const retryAfterRaw = response.headers.get("retry-after");
114
+ const retryAfterMs = Math.min(
115
+ 6e4,
116
+ Math.max(15e3, (Number.isFinite(Number(retryAfterRaw)) ? Number(retryAfterRaw) : 20) * 1e3)
117
+ );
118
+ attempts.push(`${provider.label}: 429 rate-limited \u2014 backing off ${Math.round(retryAfterMs / 1e3)}s`);
119
+ await new Promise((resolve) => setTimeout(resolve, retryAfterMs));
120
+ lastRequestAt = Date.now();
121
+ const retry = await fetch(`${provider.baseUrl}/chat/completions`, {
122
+ method: "POST",
123
+ headers,
124
+ body: JSON.stringify(payload),
125
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
126
+ });
127
+ if (!retry.ok) throw err;
128
+ const retryData = await retry.json();
129
+ const retryContent2 = retryData.choices?.[0]?.message?.content || "";
130
+ if (!retryContent2.trim()) throw err;
131
+ return {
132
+ content: retryContent2,
133
+ model: retryData.model || provider.model,
134
+ provider: provider.label,
135
+ attempts: attempts.slice(),
136
+ usage: retryData.usage,
137
+ finishReason: retryData.choices?.[0]?.finish_reason
138
+ };
139
+ }
140
+ if (TRANSIENT.has(response.status)) {
141
+ await new Promise((r) => setTimeout(r, 3e3));
142
+ const retry = await fetch(`${provider.baseUrl}/chat/completions`, {
143
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
144
+ method: "POST",
145
+ headers: {
146
+ "Content-Type": "application/json",
147
+ "Authorization": `Bearer ${provider.apiKey}`
148
+ },
149
+ body: JSON.stringify({
150
+ model: provider.model,
151
+ messages,
152
+ temperature,
153
+ max_tokens: maxTokens
154
+ })
155
+ });
156
+ if (!retry.ok) throw err;
157
+ const retryData = await retry.json();
158
+ const retryContent = retryData.choices?.[0]?.message?.content || "";
159
+ return {
160
+ content: retryContent,
161
+ model: retryData.model || provider.model,
162
+ provider: provider.label,
163
+ attempts: attempts.slice(),
164
+ usage: retryData.usage,
165
+ finishReason: retryData.choices?.[0]?.finish_reason
166
+ };
167
+ }
168
+ throw err;
169
+ }
170
+ const data = await response.json();
171
+ const wrappedError = data.error;
172
+ if (wrappedError) {
173
+ throw new LlmClientError("[" + provider.label + "] upstream error " + (wrappedError.code ?? "") + ": " + (wrappedError.message ?? "unknown"));
174
+ }
175
+ const content = data.choices?.[0]?.message?.content || "";
176
+ if (!content.trim()) {
177
+ throw new LlmClientError("[" + provider.label + "] empty completion returned");
178
+ }
179
+ return {
180
+ content,
181
+ model: data.model || provider.model,
182
+ provider: provider.label,
183
+ attempts: attempts.slice(),
184
+ usage: data.usage,
185
+ finishReason: data.choices?.[0]?.finish_reason
186
+ };
187
+ } catch (err) {
188
+ const msg = err instanceof Error ? err.message : String(err);
189
+ attempts.push(`${provider.label}: ${msg}`);
190
+ lastError = err instanceof LlmClientError ? err : new LlmClientError(`[${provider.label}] ${msg}`);
191
+ }
192
+ }
193
+ if (round < MAX_CHAIN_ROUNDS) continue;
194
+ throw lastError ?? new LlmClientError("All LLM providers failed (empty chain).");
195
+ }
196
+ throw lastError ?? new LlmClientError("All LLM providers failed after " + MAX_CHAIN_ROUNDS + " rounds.");
197
+ }
198
+ return { chat, model };
199
+ }
200
+ function parseJsonFromLlm(text) {
201
+ let cleaned = text.trim();
202
+ if (cleaned.startsWith("```json")) {
203
+ cleaned = cleaned.slice(7);
204
+ } else if (cleaned.startsWith("```")) {
205
+ cleaned = cleaned.slice(3);
206
+ }
207
+ if (cleaned.endsWith("```")) {
208
+ cleaned = cleaned.slice(0, -3);
209
+ }
210
+ cleaned = cleaned.trim();
211
+ try {
212
+ return JSON.parse(cleaned);
213
+ } catch {
214
+ const start = cleaned.indexOf("{");
215
+ if (start >= 0) {
216
+ let depth = 0;
217
+ let inString = false;
218
+ let escape = false;
219
+ for (let i = start; i < cleaned.length; i++) {
220
+ const ch = cleaned[i];
221
+ if (escape) {
222
+ escape = false;
223
+ continue;
224
+ }
225
+ if (ch === "\\") {
226
+ escape = true;
227
+ continue;
228
+ }
229
+ if (ch === '"') {
230
+ inString = !inString;
231
+ continue;
232
+ }
233
+ if (inString) continue;
234
+ if (ch === "{") depth++;
235
+ if (ch === "}") {
236
+ depth--;
237
+ if (depth === 0) {
238
+ try {
239
+ return JSON.parse(cleaned.slice(start, i + 1));
240
+ } catch {
241
+ }
242
+ }
243
+ }
244
+ }
245
+ }
246
+ throw new LlmClientError(`Failed to parse JSON from LLM response: ${cleaned.slice(0, 200)}`);
247
+ }
248
+ }
249
+ async function llmChatJson(client, systemPrompt, userPrompt, options) {
250
+ const result = await client.chat(
251
+ [
252
+ { role: "system", content: systemPrompt },
253
+ { role: "user", content: userPrompt }
254
+ ],
255
+ options
256
+ );
257
+ return parseJsonFromLlm(result.content);
258
+ }
259
+
260
+ // src/graph/scaffoldExtractor.ts
261
+ async function extractScaffold(options) {
262
+ const { goal, techStack, fileList, llmConfig } = options;
263
+ const client = createLlmClient(llmConfig);
264
+ const fileListStr = fileList.length > 0 ? fileList.join("\n") : "(empty)";
265
+ const systemPrompt = "You are a programming pedagogy expert. For ONE concrete project, extract the 'FOUNDATION & SETUP' feature (id F0) \u2014 the COMPLETE set of 'MUST-KNOW' steps the learner needs before studying the first feature. Break it into concrete ACTION steps (5-8 steps), each with completion_level='base'. Include:\n1. Tools required for this tech stack (IDE, simulator/emulator, terminal, git, package manager) + basic operations (open project, build, run, debug, commit).\n2. Create the initial project: from a template OR clone/open the base-project (the provided repo).\n3. MINIMAL programming knowledge of the language (variables, types, functions, if/for, view declaration) + build one small demo (e.g. a single-screen Hello World app) BEFORE touching the real project.\n4. Repo map of the actual project: folder structure, entry point, how to build/run, main architecture (MVVM/Flux...), important packages/modules.\n5. Development loop (build->run->see result->debug), how to read/fix basic compile errors, minimal git workflow (clone/branch/commit/push).\nkeywords[]: real tool/language terms (e.g. 'Xcode', 'Simulator', 'Git', 'Swift', '@main', 'MVVM'). files[]: leave [] or use real paths if the step touches specific files. description: ONE concise sentence, MAX 140 characters. intent: WHY this step matters. outcome: {user_visible: string, technical: string}. acceptance[]: 2 verifiable criteria. effort: {estimated_minutes: number, complexity: low|medium|high}. NEVER invent. ALL text must be in ENGLISH (technical terms stay as-is). Return JSON containing only feature F0.";
266
+ const userPrompt = `App goal: ${goal}
267
+ Tech stack: ${techStack}
268
+
269
+ PROJECT FILE LIST (base-project):
270
+ ${fileListStr}
271
+
272
+ Return JSON:
273
+ {
274
+ "feature": {
275
+ "id": "F0",
276
+ "name": "FOUNDATION & SETUP",
277
+ "description": "Get familiar with the tools, create/clone the project, learn minimal knowledge and the repo map",
278
+ "platform": "app",
279
+ "steps": [
280
+ {
281
+ "id": "F0-S1",
282
+ "sequence": 1,
283
+ "name": "Action step name",
284
+ "description": "Detailed description of the concrete actions",
285
+ "files": [],
286
+ "api_usage": [],
287
+ "keywords": ["Xcode", "Terminal"],
288
+ "completion_level": "base",
289
+ "intent": "Learn how to setup the IDE and run a minimal Swift app",
290
+ "outcome": {"user_visible": "App builds and runs", "technical": "Toolchain verified"},
291
+ "acceptance": ["Xcode builds without errors", "Simulator launches successfully"],
292
+ "effort": {"estimated_minutes": 20, "complexity": "low"}
293
+ }
294
+ ]
295
+ }
296
+ }
297
+ `;
298
+ try {
299
+ const result = await llmChatJson(client, systemPrompt, userPrompt, {
300
+ temperature: 0.1,
301
+ maxTokens: parseInt(process.env.PG_C0_MAX_TOKENS || "16384", 10)
302
+ });
303
+ const feat = result.feature;
304
+ if (!feat || !Array.isArray(feat.steps) || feat.steps.length === 0) {
305
+ console.warn("[WARN] Scaffold LLM returned no steps \u2014 skipping F0");
306
+ return null;
307
+ }
308
+ const steps = feat.steps.map((s, i) => ({
309
+ id: `F0-S${i + 1}`,
310
+ sequence: i + 1,
311
+ name: String(s.name || `Step ${i + 1}`),
312
+ description: String(s.description || ""),
313
+ files: Array.isArray(s.files) ? s.files : [],
314
+ api_usage: Array.isArray(s.api_usage) ? s.api_usage : [],
315
+ keywords: Array.isArray(s.keywords) ? s.keywords : [],
316
+ completion_level: "base",
317
+ platform: String(s.platform || "app"),
318
+ intent: String(s.intent || ""),
319
+ outcome: s.outcome && typeof s.outcome === "object" ? s.outcome : void 0,
320
+ acceptance: Array.isArray(s.acceptance) ? s.acceptance : [],
321
+ effort: s.effort && typeof s.effort === "object" ? s.effort : void 0,
322
+ requirement_ids: [],
323
+ concept_codes: []
324
+ }));
325
+ return {
326
+ id: "F0",
327
+ name: String(feat.name || "FOUNDATION & SETUP"),
328
+ description: String(feat.description || ""),
329
+ platform: String(feat.platform || "app"),
330
+ steps
331
+ };
332
+ } catch (err) {
333
+ console.error(`[ERROR] extractScaffold failed: ${err}`);
334
+ return null;
335
+ }
336
+ }
337
+
338
+ // src/graph/overviewExtractor.ts
339
+ function buildSourceText(fileContentsMap) {
340
+ const blocks = [];
341
+ for (const [relPath, content] of fileContentsMap) {
342
+ blocks.push(`### FILE: ${relPath}
343
+ ${content}`);
344
+ }
345
+ return blocks.join("\n\n");
346
+ }
347
+ async function extractProjectOverview(options) {
348
+ const { goal, techStack, sdkApiIndex, fileContentsMap, astKeywords, llmConfig } = options;
349
+ const client = createLlmClient(llmConfig);
350
+ const usedSdkApis = sdkApiIndex.sdk_apis.filter((api) => api.used_in_demo).map((api) => api.name).slice(0, 2e3);
351
+ const allFilesStr = buildSourceText(fileContentsMap);
352
+ let keywordsAnchor = "";
353
+ if (astKeywords && astKeywords.length > 0) {
354
+ const kwItems = astKeywords.slice(0, 30).map(
355
+ (kw) => `- ${kw.keyword} (from ${kw.source})`
356
+ );
357
+ if (kwItems.length > 0) {
358
+ keywordsAnchor = "\nAST Domain Keywords & Patterns (from static analysis \u2014 use as context anchor):\n" + kwItems.join("\n") + "\n";
359
+ }
360
+ }
361
+ const systemPrompt = "You are a software architect. The app the user will build IS EXACTLY the provided files (not an SDK/lib). Analyze them and return a PROJECT OVERVIEW \u2014 meta only, DO NOT list steps (steps are handled in a later step). NEVER invent files/APIs. NEVER reference internal SDK/lib unless it appears in the given files.\nEND-USER VIEW (M1/Design Thinking): product.purpose must describe the USER PROBLEM (what the user does with the app, which need it solves). NEVER describe repo/artifacts.\nDEVELOPMENT STAGES: Include 4-6 development stages in product.development_stages. Each stage must have: stage (name), need (list of feature needs), learn (concepts learned), product_state (what works), temporary_approach, and validation.\nMISSING GAPS: Identify 0-5 missing_gaps (features/functionality that should exist but don't).\nTECH DEBT: Identify 0-5 tech_debt issues (code quality problems).\nALL text must be in ENGLISH.";
362
+ const userPrompt = `App goal: ${goal}
363
+ Tech stack: ${techStack}
364
+ ${keywordsAnchor}
365
+ Filtered SDK API list (used_in_demo):
366
+ ${JSON.stringify(usedSdkApis, null, 0)}
367
+
368
+ Source code of the files:
369
+ ${allFilesStr}
370
+
371
+ Return JSON per the schema:
372
+ {
373
+ "schema_version": 2,
374
+ "project": {"name": "...", "project_type": "app", "platforms": ["ios"]},
375
+ "product": {
376
+ "purpose": "END-USER problem being solved",
377
+ "problem_statement": "Core user problem",
378
+ "primary_users": ["who the main users are"],
379
+ "development_stages": [
380
+ {
381
+ "stage": "Stage 1: Foundation & Setup",
382
+ "need": ["Core app shell"],
383
+ "learn": ["App lifecycle, basic UI"],
384
+ "product_state": "App launches with static mock data",
385
+ "temporary_approach": "Hardcoded array",
386
+ "validation": "Main screen loads"
387
+ }
388
+ ],
389
+ "features": [
390
+ {"id": "F1", "name": "Feature name", "description": "Feature description", "platform": "ios"}
391
+ ],
392
+ "user_journeys": [{"name": "...", "feature_ids": ["F1"]}]
393
+ },
394
+ "architecture": {"layers": [], "services": [], "state_management": "..."},
395
+ "decomposition": {"milestones": [{"id": "M1", "phase": "MVP", "name": "...", "goal": "...", "feature_ids": ["F1"]}]}
396
+ }`;
397
+ const result = await llmChatJson(client, systemPrompt, userPrompt, {
398
+ temperature: 0.1,
399
+ maxTokens: parseInt(process.env.PG_C1_MAX_TOKENS || "32768", 10)
400
+ });
401
+ const prod = result.product;
402
+ if (prod && !Array.isArray(prod.development_stages)) {
403
+ prod.development_stages = [];
404
+ }
405
+ return result;
406
+ }
407
+
408
+ // src/graph/stepExtractor.ts
409
+ function buildSourceText2(fileContentsMap) {
410
+ const blocks = [];
411
+ for (const [relPath, content] of fileContentsMap) {
412
+ blocks.push(`### FILE: ${relPath}
413
+ ${content}`);
414
+ }
415
+ return blocks.join("\n\n");
416
+ }
417
+ async function extractFeatureSteps(options) {
418
+ const { goal, techStack, sdkApiIndex, fileContentsMap, feature, llmConfig } = options;
419
+ const client = createLlmClient(llmConfig);
420
+ const usedSdkApis = sdkApiIndex.sdk_apis.filter((api) => api.used_in_demo).map((api) => api.name).slice(0, 2e3);
421
+ const allFilesStr = buildSourceText2(fileContentsMap);
422
+ const fid = feature.id || "F_UNK";
423
+ const fname = feature.name || fid;
424
+ const fdesc = feature.description || "";
425
+ const systemPrompt = "You are a software architect. Split ONE feature into ACTION steps (implementation steps) the learner must code sequentially. Each step must carry files[] (CORRECT paths in the source), api_usage[] (only from the provided SDK API index), keywords[] (real terms/language features in the files), and completion_level \u2208 {base, mvp, extend, polish}.\n - base = foundation/setup\n - mvp = make the app minimally WORKING for this feature\n - extend = make it real/richer\n - polish = robustness (error handling, tests, validation)\nInclude metadata: intent, outcome ({user_visible, technical}), acceptance[] (2 verifiable criteria), effort ({estimated_minutes, complexity}).\ndescription: ONE concise sentence, MAX 140 characters. NEVER invent files/APIs. Return ONLY the steps array. ALL text must be in ENGLISH.";
426
+ const userPrompt = `App goal: ${goal}
427
+ Tech stack: ${techStack}
428
+
429
+ FEATURE TO SPLIT: ${fid} \u2014 ${fname}
430
+ Feature description: ${fdesc}
431
+
432
+ SDK API list (used_in_demo):
433
+ ${JSON.stringify(usedSdkApis)}
434
+
435
+ Source code:
436
+ ${allFilesStr}
437
+
438
+ Split this feature into 2-6 action steps. Return JSON:
439
+ {
440
+ "steps": [
441
+ {
442
+ "id": "${fid}-S1",
443
+ "sequence": 1,
444
+ "name": "Action step name",
445
+ "description": "One concise sentence (max 140 chars)",
446
+ "files": ["path/to/file.swift"],
447
+ "api_usage": ["ChatClient"],
448
+ "keywords": ["@State", "NavigationStack"],
449
+ "completion_level": "mvp",
450
+ "intent": "Create reactive state container",
451
+ "outcome": {"user_visible": "Chat view updates", "technical": "ChatViewModel conforms to ObservableObject"},
452
+ "acceptance": ["ViewModel publishes messages", "UI re-renders on state mutation"],
453
+ "effort": {"estimated_minutes": 30, "complexity": "medium"}
454
+ }
455
+ ]
456
+ }`;
457
+ const result = await llmChatJson(client, systemPrompt, userPrompt, {
458
+ temperature: 0.1,
459
+ maxTokens: parseInt(process.env.PG_C2_MAX_TOKENS || "32768", 10)
460
+ });
461
+ const rawSteps = result.steps || [];
462
+ const clampedSteps = rawSteps.length > 6 ? rawSteps.slice(0, 6) : rawSteps.length < 2 && rawSteps.length > 0 ? rawSteps : rawSteps;
463
+ if (rawSteps.length > 6) {
464
+ console.warn(`[WARN] LLM returned ${rawSteps.length} steps for ${fid}, clamped to 6`);
465
+ } else if (rawSteps.length === 0) {
466
+ console.warn(`[WARN] LLM returned 0 steps for ${fid}`);
467
+ }
468
+ return clampedSteps.map((s, i) => ({
469
+ id: `${fid}-S${i + 1}`,
470
+ sequence: i + 1,
471
+ name: String(s.name || `Step ${i + 1}`),
472
+ description: String(s.description || ""),
473
+ files: Array.isArray(s.files) ? s.files : [],
474
+ api_usage: Array.isArray(s.api_usage) ? s.api_usage : [],
475
+ keywords: Array.isArray(s.keywords) ? s.keywords : [],
476
+ completion_level: String(s.completion_level || "mvp"),
477
+ platform: String(s.platform || feature.platform || "app"),
478
+ intent: String(s.intent || ""),
479
+ outcome: s.outcome,
480
+ acceptance: Array.isArray(s.acceptance) ? s.acceptance : [],
481
+ effort: s.effort,
482
+ requirement_ids: [],
483
+ concept_codes: []
484
+ }));
485
+ }
486
+ async function extractFeatureStepsBatched(goal, techStack, sdkApiIndex, fileContentsMap, featuresMeta, llmConfig) {
487
+ const client = createLlmClient(llmConfig);
488
+ const usedSdkApis = sdkApiIndex.sdk_apis.filter((api) => api.used_in_demo).map((api) => api.name).slice(0, 2e3);
489
+ const sourceText = buildSourceText2(fileContentsMap);
490
+ const featuresListing = featuresMeta.map(
491
+ (f) => `- ${f.id || "F?"}: ${f.name || ""} \u2014 ${f.description || ""}`
492
+ ).join("\n");
493
+ const systemPrompt = "You are a software architect. Split MULTIPLE features into ACTION steps. Each step must carry files[], api_usage[], keywords[], and completion_level \u2208 {base, mvp, extend, polish}. Include metadata: intent, outcome ({user_visible, technical}), acceptance[] (2 verifiable criteria), effort ({estimated_minutes, complexity}). description: ONE concise sentence, MAX 140 characters. NEVER invent files/APIs. Return ONLY the JSON. ALL text must be in ENGLISH.";
494
+ const userPrompt = `App goal: ${goal}
495
+ Tech stack: ${techStack}
496
+
497
+ SDK API list (used_in_demo):
498
+ ${JSON.stringify(usedSdkApis)}
499
+
500
+ Source code:
501
+ ${sourceText}
502
+
503
+ FEATURES to split into steps:
504
+ ${featuresListing}
505
+
506
+ For EACH feature above, produce 4-6 action steps. Each step must include:
507
+ id, sequence, name, description, files, api_usage, keywords, completion_level, platform,
508
+ intent, outcome ({user_visible, technical}), acceptance[] (2 criteria), effort ({estimated_minutes, complexity}).
509
+
510
+ Return JSON with a "steps" dict keyed by feature_id:
511
+ {
512
+ "steps": {
513
+ "<feature_id>": [
514
+ {
515
+ "id": "<feature_id>-S1",
516
+ "sequence": 1,
517
+ "name": "Step name",
518
+ "description": "Concise sentence (max 140 chars)",
519
+ "files": ["path/to/file"],
520
+ "api_usage": ["APIName"],
521
+ "keywords": ["keyword"],
522
+ "completion_level": "mvp",
523
+ "platform": "app",
524
+ "intent": "Step intent",
525
+ "outcome": {"user_visible": "User visible result", "technical": "Technical result"},
526
+ "acceptance": ["Criterion 1", "Criterion 2"],
527
+ "effort": {"estimated_minutes": 30, "complexity": "medium"}
528
+ }
529
+ ]
530
+ }
531
+ }`;
532
+ const result = await llmChatJson(client, systemPrompt, userPrompt, {
533
+ temperature: 0.1,
534
+ maxTokens: parseInt(process.env.PG_C2_MAX_TOKENS || "32768", 10)
535
+ });
536
+ const stepsDict = result.steps;
537
+ const output = /* @__PURE__ */ new Map();
538
+ if (stepsDict && typeof stepsDict === "object") {
539
+ for (const [fid, rawSteps] of Object.entries(stepsDict)) {
540
+ if (!Array.isArray(rawSteps)) continue;
541
+ const featMeta = featuresMeta.find((f) => f.id === fid);
542
+ const steps = rawSteps.map((s, i) => ({
543
+ id: `${fid}-S${i + 1}`,
544
+ sequence: i + 1,
545
+ name: String(s.name || `Step ${i + 1}`),
546
+ description: String(s.description || ""),
547
+ files: Array.isArray(s.files) ? s.files : [],
548
+ api_usage: Array.isArray(s.api_usage) ? s.api_usage : [],
549
+ keywords: Array.isArray(s.keywords) ? s.keywords : [],
550
+ completion_level: String(s.completion_level || "mvp"),
551
+ platform: String(s.platform || featMeta?.platform || "app"),
552
+ intent: String(s.intent || ""),
553
+ outcome: s.outcome,
554
+ acceptance: Array.isArray(s.acceptance) ? s.acceptance : [],
555
+ effort: s.effort,
556
+ requirement_ids: [],
557
+ concept_codes: []
558
+ }));
559
+ output.set(fid, steps);
560
+ }
561
+ }
562
+ return output;
563
+ }
564
+
565
+ // src/graph/graphVerifier.ts
566
+ function verifyProjectGraph(projectGraph, options) {
567
+ const { sdkApiIndex, fileContentsMap } = options;
568
+ const sdkApiNames = new Set(sdkApiIndex.sdk_apis.map((api) => api.name));
569
+ const hallucinations = [];
570
+ const features = projectGraph.features || [];
571
+ for (const feature of features) {
572
+ const fid = feature.id || "F_UNK";
573
+ const isFoundation = fid === "F0";
574
+ for (const step of feature.steps || []) {
575
+ const sid = step.id || `${fid}-SUNK`;
576
+ const validFiles = [];
577
+ for (const f of step.files || []) {
578
+ if (fileContentsMap.has(f)) {
579
+ validFiles.push(f);
580
+ } else {
581
+ hallucinations.push({
582
+ type: "file",
583
+ item: f,
584
+ feature_id: fid,
585
+ step_id: sid,
586
+ reason: `File '${f}' not found in repository`
587
+ });
588
+ }
589
+ }
590
+ step.files = validFiles;
591
+ const validApis = [];
592
+ for (const api of step.api_usage || []) {
593
+ if (sdkApiNames.size === 0 || sdkApiNames.has(api)) {
594
+ validApis.push(api);
595
+ } else {
596
+ hallucinations.push({
597
+ type: "api",
598
+ item: api,
599
+ feature_id: fid,
600
+ step_id: sid,
601
+ reason: `API '${api}' not found in SDK API index`
602
+ });
603
+ }
604
+ }
605
+ step.api_usage = validApis;
606
+ if (isFoundation) continue;
607
+ const validKws = [];
608
+ for (const kw of step.keywords || []) {
609
+ const kwLow = kw.toLowerCase();
610
+ const isSingleWord = !kwLow.includes(" ");
611
+ let found = false;
612
+ for (const f of validFiles) {
613
+ const content = (fileContentsMap.get(f) || "").toLowerCase();
614
+ if (isSingleWord) {
615
+ found = new RegExp(`\\b${kwLow.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`).test(content);
616
+ } else {
617
+ found = content.includes(kwLow);
618
+ }
619
+ if (found) break;
620
+ }
621
+ if (!found) {
622
+ for (const content of fileContentsMap.values()) {
623
+ const lc = content.toLowerCase();
624
+ if (isSingleWord) {
625
+ found = new RegExp(`\\b${kwLow.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`).test(lc);
626
+ } else {
627
+ found = lc.includes(kwLow);
628
+ }
629
+ if (found) break;
630
+ }
631
+ }
632
+ if (found) {
633
+ validKws.push(kw);
634
+ } else {
635
+ hallucinations.push({
636
+ type: "keyword",
637
+ item: kw,
638
+ feature_id: fid,
639
+ step_id: sid,
640
+ reason: `Keyword '${kw}' not found in target files`
641
+ });
642
+ }
643
+ }
644
+ step.keywords = validKws;
645
+ }
646
+ }
647
+ return { graph: projectGraph, hallucinations };
648
+ }
649
+
650
+ // src/graph/conceptEscalator.ts
651
+ function toUpperSnake(term) {
652
+ let s = term.replace(/^[^\w]+/, "");
653
+ s = s.replace(/([a-z0-9])([A-Z])/g, "$1_$2");
654
+ s = s.replace(/[^\w]+/g, "_");
655
+ const res = s.toUpperCase().replace(/^_+|_+$/g, "");
656
+ return res || "CONCEPT";
657
+ }
658
+ function extractTermSnippets(term, fileContentsMap, maxSnippets = 1) {
659
+ const snippets = [];
660
+ const termLow = term.toLowerCase();
661
+ for (const [relPath, content] of fileContentsMap) {
662
+ const lines = content.split("\n");
663
+ for (let idx = 0; idx < lines.length; idx++) {
664
+ if (lines[idx].toLowerCase().includes(termLow)) {
665
+ const start = Math.max(0, idx - 1);
666
+ const end = Math.min(lines.length, idx + 2);
667
+ let snippet = lines.slice(start, end).map((l) => l.trim()).filter(Boolean).join(" ");
668
+ if (snippet.length > 120) snippet = snippet.slice(0, 120) + "...";
669
+ if (snippet) snippets.push(`[${relPath}]: ${snippet}`);
670
+ if (snippets.length >= maxSnippets) break;
671
+ }
672
+ }
673
+ if (snippets.length >= maxSnippets) break;
674
+ }
675
+ return snippets;
676
+ }
677
+ function inferDepthFromContext(keyword, fileContentsMap) {
678
+ const kw = keyword.toLowerCase();
679
+ const sioPatterns = [
680
+ /^@/,
681
+ // SwiftUI decorators: @State, @Binding
682
+ /^import\s/,
683
+ // Import statements
684
+ /\(\)$/,
685
+ // Function calls
686
+ /\.prototype/,
687
+ // Prototype methods
688
+ /^new\s/,
689
+ // Constructor calls
690
+ /^async\s/,
691
+ // Async keywords
692
+ /^await\s/
693
+ ];
694
+ if (sioPatterns.some((p) => p.test(keyword))) {
695
+ return { depth: "sio", rationale: `Keyword '${keyword}' is a specific API/syntax pattern` };
696
+ }
697
+ const cioPatterns = [
698
+ /pattern/i,
699
+ /protocol/i,
700
+ /architecture/i,
701
+ /lifecycle/i,
702
+ /observer/i,
703
+ /singleton/i,
704
+ /factory/i,
705
+ /delegate/i,
706
+ /state\s*management/i,
707
+ /data\s*flow/i,
708
+ /binding/i,
709
+ /mvvm/i,
710
+ /mvc/i,
711
+ /flux/i,
712
+ /redux/i,
713
+ /authentication/i,
714
+ /authorization/i,
715
+ /persistence/i,
716
+ /caching/i,
717
+ /serialization/i
718
+ ];
719
+ if (cioPatterns.some((p) => p.test(keyword))) {
720
+ return { depth: "cio", rationale: `Keyword '${keyword}' represents a mechanism/pattern` };
721
+ }
722
+ const uloPatterns = [
723
+ /design\s*thinking/i,
724
+ /user\s*needs/i,
725
+ /problem\s*statement/i,
726
+ /foundation/i,
727
+ /setup/i,
728
+ /overview/i,
729
+ /introduction/i,
730
+ /scaffold/i,
731
+ /hello\s*world/i,
732
+ /getting\s*started/i
733
+ ];
734
+ if (uloPatterns.some((p) => p.test(keyword))) {
735
+ return { depth: "ulo", rationale: `Keyword '${keyword}' is a foundational/introductory concept` };
736
+ }
737
+ for (const content of fileContentsMap.values()) {
738
+ const lines = content.split("\n");
739
+ for (const line of lines) {
740
+ if (line.toLowerCase().includes(kw)) {
741
+ if (/^(import|from|require|use |#include)/.test(line.trim())) {
742
+ return { depth: "sio", rationale: `Keyword '${keyword}' found in import statement` };
743
+ }
744
+ if (/^\/\/|^\/\*|^#|^-->/.test(line.trim())) {
745
+ return { depth: "ulo", rationale: `Keyword '${keyword}' found in comment/doc` };
746
+ }
747
+ return { depth: "sio", rationale: `Keyword '${keyword}' used in implementation code` };
748
+ }
749
+ }
750
+ }
751
+ return { depth: "sio", rationale: `Default: treating '${keyword}' as SIO (implementation-level)` };
752
+ }
753
+ async function escalateAndMapConcepts(options) {
754
+ const { projectGraph, fileContentsMap, availableConcepts, conceptMapOverride, llmConfig } = options;
755
+ const features = projectGraph.features || [];
756
+ const allTerms = /* @__PURE__ */ new Set();
757
+ for (const feature of features) {
758
+ for (const step of feature.steps || []) {
759
+ for (const api of step.api_usage || []) allTerms.add(api);
760
+ for (const kw of step.keywords || []) allTerms.add(kw);
761
+ }
762
+ }
763
+ if (allTerms.size === 0) return /* @__PURE__ */ new Map();
764
+ const termList = Array.from(allTerms).sort();
765
+ let llmResults = {};
766
+ if (conceptMapOverride) {
767
+ llmResults = conceptMapOverride;
768
+ } else {
769
+ try {
770
+ const client = createLlmClient(llmConfig);
771
+ const conceptBank = (availableConcepts || []).sort().join(", ") || "(empty)";
772
+ const termEntries = termList.map((term) => {
773
+ const snippets = extractTermSnippets(term, fileContentsMap);
774
+ return snippets.length > 0 ? `- ${term} (Usage context: ${snippets[0]})` : `- ${term}`;
775
+ });
776
+ const systemPrompt = `You are a knowledge classification expert. For each concrete keyword/API, determine:
777
+ 1. The neutral concept it belongs to (UPPER_SNAKE_CASE)
778
+ 2. The depth level: ulo | cio | sio
779
+
780
+ DEPTH DEFINITIONS:
781
+ - ulo (WHAT + WHY): The keyword introduces a concept \u2014 "what is it, why does it exist"
782
+ Example: In a scaffold step, "@State is SwiftUI's way of managing local view state"
783
+ - cio (HOW): The keyword demonstrates a mechanism \u2014 "how it works"
784
+ Example: "@State triggers view re-render when value changes \u2014 mechanism is value-type observation"
785
+ - sio (IMPLEMENTATION): The keyword is a concrete API/syntax used in code
786
+ Example: "Using @State var isActive: Bool = false in ContentView"
787
+
788
+ RULES:
789
+ 1. PREFER an EXISTING concept from the CONCEPT_BANK below if the keyword is a manifestation of that concept.
790
+ 2. ONLY create a NEW concept (UPPER_SNAKE_CASE, NOT ending in _CONCEPT, NOT containing a specific technology name) when NO concept in the bank covers it.
791
+ 3. CONCEPT_BANK: ${conceptBank.slice(0, 12e3)}
792
+ 4. Depth is per-keyword-in-context, NOT per-concept. The same concept can have ULO at one step and SIO at another.
793
+ Return JSON: {"results": {"<keyword>": {"concept_code": "...", "concept_name": "...", "depth": "ulo|cio|sio"}}}`;
794
+ const userPrompt = "Classify the following keyword/API list into neutral concepts WITH depth levels.\nCode usage context is provided to disambiguate depth:\n" + termEntries.join("\n") + '\n\nReturn JSON: {"results": {"<keyword>": {"concept_code": "...", "concept_name": "...", "depth": "ulo|cio|sio"}}}';
795
+ const result = await llmChatJson(client, systemPrompt, userPrompt, {
796
+ temperature: 0.1,
797
+ maxTokens: 16384
798
+ });
799
+ llmResults = result.results || {};
800
+ } catch (err) {
801
+ console.warn(`[WARN] Concept escalation LLM failed (${err}), using fallback depth inference`);
802
+ }
803
+ }
804
+ const featureConcepts = /* @__PURE__ */ new Map();
805
+ for (const feature of features) {
806
+ const fid = feature.id || "F_UNK";
807
+ const featureFiles = /* @__PURE__ */ new Set();
808
+ for (const step of feature.steps || []) {
809
+ for (const f of step.files || []) featureFiles.add(f);
810
+ }
811
+ const fTerms = [
812
+ ...feature.api_usage || [],
813
+ ...(feature.steps || []).flatMap((s) => [...s.api_usage || [], ...s.keywords || []])
814
+ ];
815
+ const items = [];
816
+ const seen = /* @__PURE__ */ new Set();
817
+ for (const kw of fTerms) {
818
+ const info = llmResults[kw] || {};
819
+ const cCode = info.concept_code || toUpperSnake(kw);
820
+ const cName = info.concept_name || kw;
821
+ let depth = "sio";
822
+ let depthRationale = "Default: SIO";
823
+ if (info.depth && ["ulo", "cio", "sio"].includes(info.depth)) {
824
+ depth = info.depth;
825
+ depthRationale = `LLM classified as ${depth}`;
826
+ } else {
827
+ const inferred = inferDepthFromContext(kw, fileContentsMap);
828
+ depth = inferred.depth;
829
+ depthRationale = inferred.rationale;
830
+ }
831
+ const kwKey = `${cCode}::${kw}`;
832
+ if (seen.has(kwKey)) continue;
833
+ seen.add(kwKey);
834
+ const evidenceFiles = [];
835
+ for (const f of featureFiles) {
836
+ const content = fileContentsMap.get(f) || "";
837
+ if (content.toLowerCase().includes(kw.toLowerCase())) {
838
+ evidenceFiles.push(f);
839
+ }
840
+ }
841
+ items.push({
842
+ concept_code: cCode,
843
+ concept_name: cName,
844
+ keyword: kw,
845
+ depth,
846
+ depth_rationale: depthRationale,
847
+ evidence_files: evidenceFiles
848
+ });
849
+ }
850
+ featureConcepts.set(fid, items);
851
+ }
852
+ return featureConcepts;
853
+ }
854
+
855
+ // src/graph/loCodeStandard.ts
856
+ var TECH_TAG_MAP = {
857
+ python: "PY",
858
+ swift: "SW",
859
+ typescript: "TS",
860
+ javascript: "JV",
861
+ java: "JAVA",
862
+ kotlin: "KT",
863
+ go: "GO",
864
+ rust: "RUST",
865
+ csharp: "CS",
866
+ cpp: "CPP",
867
+ dart: "DT",
868
+ php: "PHP",
869
+ ruby: "RB",
870
+ sql: "SQL",
871
+ html: "HTML",
872
+ css: "CSS"
873
+ };
874
+ function techTagFor(techStack) {
875
+ const primary = (techStack || "").trim().toLowerCase();
876
+ for (const [key, tag] of Object.entries(TECH_TAG_MAP)) {
877
+ if (primary.includes(key)) return tag;
878
+ }
879
+ const first = primary.split(/[\s,+/]+/)[0] ?? "";
880
+ if (!/^[a-z]/.test(first)) return "GEN";
881
+ return first.length <= 4 ? first.toUpperCase() : first.slice(0, 3).toUpperCase();
882
+ }
883
+ var SMALL_WORDS = /* @__PURE__ */ new Set(["and", "or", "the", "of", "for", "in", "on", "a", "an", "vs"]);
884
+ function conceptCodeFromName(name) {
885
+ const words = name.replace(/[^A-Za-z0-9]+/g, " ").trim().split(/\s+/).filter((w) => w.length > 0 && !SMALL_WORDS.has(w.toLowerCase()));
886
+ const base = words.join("_").toUpperCase().replace(/^_+|_+$/g, "").replace(/_{2,}/g, "_");
887
+ const trimmed = (base || "CONCEPT").slice(0, 60).replace(/_+$/g, "");
888
+ return trimmed;
889
+ }
890
+ function assignConceptCodes(concepts) {
891
+ const used = /* @__PURE__ */ new Map();
892
+ const out = {};
893
+ for (const c of concepts) {
894
+ const base = conceptCodeFromName(c.name);
895
+ const n = (used.get(base) ?? 0) + 1;
896
+ used.set(base, n);
897
+ out[c.id] = n === 1 ? base : base + "_" + n;
898
+ }
899
+ return out;
900
+ }
901
+ var pad2 = (n) => String(n).padStart(2, "0");
902
+ function uloCode(conceptCode, seq = 1) {
903
+ return "ULO-" + conceptCode + "-" + pad2(seq);
904
+ }
905
+ var CIO_STOPWORDS = /* @__PURE__ */ new Set([
906
+ // clause boilerplate
907
+ "learner",
908
+ "will",
909
+ "be",
910
+ "able",
911
+ // generic fillers
912
+ "a",
913
+ "an",
914
+ "the",
915
+ "of",
916
+ "to",
917
+ "and",
918
+ "or",
919
+ "in",
920
+ "on",
921
+ "for",
922
+ "by",
923
+ "with",
924
+ "is",
925
+ "are",
926
+ "that",
927
+ "it",
928
+ "its",
929
+ "their",
930
+ "when",
931
+ "how",
932
+ "as",
933
+ "into",
934
+ "from"
935
+ ]);
936
+ function cioActionSlug(cioText) {
937
+ const body = cioText.startsWith(LEARNER_CLAUSE) ? cioText.slice(LEARNER_CLAUSE.length) : cioText;
938
+ 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));
939
+ const seen = /* @__PURE__ */ new Set();
940
+ const picked = [];
941
+ for (const w of words) {
942
+ if (!seen.has(w)) {
943
+ seen.add(w);
944
+ picked.push(w);
945
+ }
946
+ if (picked.length === 3) break;
947
+ }
948
+ return (picked.length > 0 ? picked : ["apply"]).join("_").toUpperCase();
949
+ }
950
+ function cioCode(conceptCode, uloSeq, actionSlug) {
951
+ return "CIO-" + conceptCode + "-" + pad2(uloSeq) + "-" + actionSlug;
952
+ }
953
+ function sioCode(techTag, conceptCode, seq) {
954
+ return "SIO-" + techTag + "-" + conceptCode + "-" + pad2(seq);
955
+ }
956
+ var LEARNER_CLAUSE = "The learner will be able to ";
957
+ function standardStatement(text) {
958
+ let body = (text || "").trim().replace(/^the learner (will be able to|can)\s*/i, "").replace(/\s+/g, " ");
959
+ if (body.length === 0) return "";
960
+ const firstWord = body.split(" ")[0] ?? "";
961
+ const looksAcronym = /^[A-Z0-9_.`]+$/.test(firstWord) && firstWord.length > 1;
962
+ if (!looksAcronym) body = body.charAt(0).toLowerCase() + body.slice(1);
963
+ body = body.replace(/[.\s]+$/, "");
964
+ return LEARNER_CLAUSE + body + ".";
965
+ }
966
+ var CONCEPT_CODE_RE = /^[A-Z][A-Z0-9_]*$/;
967
+ var ULO_CODE_RE = /^ULO-[A-Z][A-Z0-9_]*-\d{2}$/;
968
+ var CIO_CODE_RE = /^CIO-[A-Z][A-Z0-9_]*-\d{2}-[A-Z][A-Z0-9_]*$/;
969
+ var SIO_CODE_RE = /^SIO-[A-Z0-9]+-[A-Z][A-Z0-9_]*-\d{2}$/;
970
+
971
+ // src/graph/loExemplars.ts
972
+ var ULO_EXEMPLARS = [
973
+ // Calibrated against production learning_objectives (UNIVERSAL rows, neutral)
974
+ "The learner will be able to recall the key concepts, terminology, and characteristics of layers of abstraction.",
975
+ "The learner will be able to explain how layers of abstraction hide implementation details while exposing essential behavior.",
976
+ "The learner will be able to explain how a program changes state through statements and control flow.",
977
+ "The learner will be able to differentiate local from global scope and describe how return values affect data flow.",
978
+ "The learner will be able to describe the mechanism of a loop, including its condition, step and stopping rule.",
979
+ "The learner will be able to explain why a representation format must balance readability against processing efficiency."
980
+ ];
981
+ var CIO_EXEMPLARS = [
982
+ // Production CONCEPTUAL_IMPL rows: mechanism behind the clause, Marr 2-Language neutral
983
+ "The learner will be able to develop a conceptual model that explains the internal mechanism by which the representation produces its effect.",
984
+ "The learner will be able to compare alternative approaches for the same operation and describe the trade-offs between them.",
985
+ "The learner will be able to decompose the choice of representation into decisive criteria such as cost, fidelity and tolerance to change.",
986
+ "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."
987
+ ];
988
+ var SIO_EXEMPLARS = [
989
+ // Production SPECIFIC_IMPL style: keyword-bound completable tasks, tech-tagged tier
990
+ "The learner will be able to use argparse.ArgumentParser with add_subparsers to register add, done and list commands in a Python CLI.",
991
+ "The learner will be able to define a @dataclass with type hints and a __post_init__ method that raises ValueError on invariant violation.",
992
+ "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.",
993
+ "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."
994
+ ];
995
+
996
+ // src/graph/depthAudit.ts
997
+ var TECH_SIGNAL_RES = [
998
+ /`[^`]+`/,
999
+ /\b[a-zA-Z_][A-Za-z0-9_]*\(\)/,
1000
+ // call-with-arguments: Status(enum.Enum), field(default_factory=list)
1001
+ /\b[A-Za-z_][A-Za-z0-9_]*\([^)]+\)/,
1002
+ // attribute access glued to a value: enum.Enum, os.path, tasks.json
1003
+ /[A-Za-z0-9_)\]]\.[A-Za-z_][A-Za-z0-9_]+/,
1004
+ /[a-z]+_[a-z]+/,
1005
+ /[a-z]+[A-Z][A-Za-z]*/,
1006
+ /\.[a-z]{2,4}\b/,
1007
+ /\b(?:API|SDK|JSON|XML|YAML|HTTP|SQL|UUID|URL|DOM|CLI|TUI|CSV|UTF|CRUD|DSL)\b/,
1008
+ // Exception/error class names: Exception, ValueError, CustomError
1009
+ /\b[A-Z][a-zA-Z0-9_]*(?:Error|Exception|Warning|Fault)\b/,
1010
+ // class declarations or references: class Status, static methods on types
1011
+ /\bclass\s+[A-Za-z_][A-Za-z0-9_]*/,
1012
+ // inheritance/derivation mentions: inheriting from Exception, subclass of Base
1013
+ /\b(?:inherit(?:ing|s)?|subclass(?:ing)?|deriv(?:ing|ed|es)?)\s+(?:from|of)\s+[A-Z][A-Za-z0-9_]*/
1014
+ ];
1015
+ var GENERIC_STOP = /* @__PURE__ */ new Set(["e", "g", "i"]);
1016
+ function techSignalHits(text) {
1017
+ const hits = [];
1018
+ for (const re of TECH_SIGNAL_RES) {
1019
+ const found = text.match(new RegExp(re.source, "g")) ?? [];
1020
+ for (const m of found) if (!GENERIC_STOP.has(m.toLowerCase())) hits.push(m);
1021
+ }
1022
+ return hits;
1023
+ }
1024
+ function auditDepthLayers(concepts) {
1025
+ return concepts.map((c) => {
1026
+ const ulo = (c.ulo ?? "").trim();
1027
+ const cio = (c.cio ?? "").trim();
1028
+ const sioItems = (c.sio ?? []).map((s) => (s ?? "").trim()).filter(Boolean);
1029
+ const uloTechSignals = techSignalHits(ulo);
1030
+ const uloHasTechSignals = uloTechSignals.length > 0;
1031
+ const IMPL_VERBS = /\b(implement|refactor|debug|serialize)\b/i;
1032
+ const uloHasImplementationVerbs = IMPL_VERBS.test(ulo);
1033
+ const registryKeywords = (c.keywords ?? []).map((k) => String(k).toLowerCase()).filter((k) => k.length >= 3);
1034
+ const nameTokens = String(c.name ?? "").toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length >= 4);
1035
+ const boundToConcept = (s) => {
1036
+ const lower = s.toLowerCase();
1037
+ return registryKeywords.some((k) => lower.includes(k)) || nameTokens.some((w) => lower.includes(w));
1038
+ };
1039
+ const sioUnboundItems = sioItems.filter((s) => {
1040
+ if (techSignalHits(s).length > 0) return false;
1041
+ return !boundToConcept(s);
1042
+ });
1043
+ const conceptKeywords = (c.keywords ?? []).map((k) => k.toLowerCase()).filter(Boolean);
1044
+ const sioOffConceptItems = conceptKeywords.length > 0 ? sioItems.filter((s) => !boundToConcept(s)) : [];
1045
+ 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;
1046
+ const sioNotCompletable = sioItems.filter((s) => !COMPLETABLE.test(s) && !/`[^`]+`/.test(s));
1047
+ const density = (text) => {
1048
+ if (!text) return 0;
1049
+ return techSignalHits(text).length / Math.max(1, text.split(/\s+/).length) * 100;
1050
+ };
1051
+ const dUlo = density(ulo);
1052
+ density(cio);
1053
+ const dSio = sioItems.length > 0 ? Math.max(...sioItems.map(density)) : 0;
1054
+ const concretenessIncreases = dSio > dUlo;
1055
+ const clauseOk = ulo.startsWith(LEARNER_CLAUSE) && cio.startsWith(LEARNER_CLAUSE) && sioItems.every((t) => t.startsWith(LEARNER_CLAUSE));
1056
+ const codeIssues = [];
1057
+ const conceptCode = c.code;
1058
+ if (conceptCode !== void 0 && !CONCEPT_CODE_RE.test(conceptCode)) codeIssues.push("concept code not UPPER_SNAKE: " + conceptCode);
1059
+ const uloCodeVal = c.ulo_code;
1060
+ if (uloCodeVal !== void 0 && uloCodeVal !== "" && !ULO_CODE_RE.test(uloCodeVal)) codeIssues.push("ULO code malformed: " + uloCodeVal);
1061
+ const cioCodeVal = c.cio_code;
1062
+ if (cioCodeVal !== void 0 && cioCodeVal !== "" && !CIO_CODE_RE.test(cioCodeVal)) codeIssues.push("CIO code malformed: " + cioCodeVal);
1063
+ const sioCodeVals = c.sio_codes;
1064
+ if (sioCodeVals !== void 0) {
1065
+ if (sioCodeVals.length !== sioItems.length) codeIssues.push("SIO codes count mismatch");
1066
+ for (const sc of sioCodeVals) if (!SIO_CODE_RE.test(sc)) codeIssues.push("SIO code malformed: " + sc);
1067
+ }
1068
+ const codesOk = codeIssues.length === 0;
1069
+ const passed = !uloHasTechSignals && !uloHasImplementationVerbs && sioUnboundItems.length === 0 && sioOffConceptItems.length === 0 && sioNotCompletable.length === 0 && concretenessIncreases && clauseOk && codesOk;
1070
+ return {
1071
+ conceptId: c.id,
1072
+ uloHasTechSignals,
1073
+ uloTechSignals,
1074
+ uloHasImplementationVerbs,
1075
+ sioAllKeywordBound: sioUnboundItems.length === 0,
1076
+ sioUnboundItems,
1077
+ sioConceptKeywordBound: sioOffConceptItems.length === 0,
1078
+ sioOffConceptItems,
1079
+ sioAllCompletable: sioNotCompletable.length === 0,
1080
+ sioNotCompletable,
1081
+ concretenessIncreases,
1082
+ clauseOk,
1083
+ codesOk,
1084
+ codeIssues,
1085
+ passed
1086
+ };
1087
+ });
1088
+ }
1089
+
1090
+ // src/graph/hierarchicalLoAuthoring.ts
1091
+ function excerpt(text, max) {
1092
+ const t = (text || "").trim();
1093
+ return t.length > max ? t.slice(0, max) + "..." : t;
1094
+ }
1095
+ async function chatJson(client, system, user) {
1096
+ const r = await client.chat(
1097
+ [{ role: "system", content: system }, { role: "user", content: user }],
1098
+ { temperature: 0.1, maxTokens: parseInt(process.env.KG_MAX_TOKENS || "65536", 10) }
1099
+ );
1100
+ return parseJsonFromLlm(r.content);
1101
+ }
1102
+ var LO_BATCH_SIZE = 6;
1103
+ function chunkConcepts(items, size) {
1104
+ const out = [];
1105
+ for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
1106
+ return out;
1107
+ }
1108
+ var JSON_ONLY = "Return EXACTLY JSON. No markdown, no explanations.";
1109
+ async function authorDepthLayersHierarchically(client, concepts, techStack, warnings) {
1110
+ const uloByConcept = {};
1111
+ const cioByConcept = {};
1112
+ const sioByConcept = {};
1113
+ concepts.map((c) => "- " + c.id + ": " + c.name + (c.description ? " \u2014 " + excerpt(c.description, 160) : "")).join("\n");
1114
+ const uloSystem = [
1115
+ "You are a Curriculum Design Expert writing Universal Learning Objectives (ULO).",
1116
+ "",
1117
+ "ULO = Computational Tier: the CORE COMPETENCY \u2014 WHAT the concept is and WHY it exists \u2014",
1118
+ "completely independent of any technology, language, framework, library, file format or tool.",
1119
+ "",
1120
+ "Rules:",
1121
+ "1. NEVER mention a concrete technology, API, library, file name or syntax in a ULO.",
1122
+ "2. Bind the ULO to the concept intrinsic nature: the problem it solves in principle.",
1123
+ "3. Typical assessment level: Remember or Understand. Use pragmatic, measurable verbs",
1124
+ " (Explain, Differentiate, Identify, Describe) instead of Know/Understand/Summarize.",
1125
+ "4. Cognitive Ceiling: do NOT force Analyze/Evaluate/Create ULOs \u2014 if the concept is",
1126
+ " foundational, its core competency is low-level. Higher levels are exercised later",
1127
+ " INDIRECTLY through implementation work, not in the ULO itself.",
1128
+ "5. One ULO per concept; 1-2 sentences covering WHAT + WHY.",
1129
+ "6. Statement form (mandatory): every ULO MUST read 'The learner will be able to ...' \u2014",
1130
+ " a lowercase actionable verb follows the clause (explain ..., differentiate ...).",
1131
+ " Do not prefix any other phrasing.",
1132
+ "",
1133
+ "Approved style exemplars (production bank):",
1134
+ ULO_EXEMPLARS.map((e) => "- " + e).join("\n"),
1135
+ "",
1136
+ JSON_ONLY
1137
+ ].join("\n");
1138
+ for (const batch of chunkConcepts(concepts, LO_BATCH_SIZE)) {
1139
+ const batchList = batch.map((c) => "- " + c.id + " (" + c.name + ")" + (c.description ? ": " + excerpt(c.description, 160) : "")).join("\n");
1140
+ const batchUser = "Concepts:\n" + batchList + '\n\nReturn JSON:\n{"ulos":[{"concept_id":"C1","ulo":"..."}]}';
1141
+ const uloRes = await chatJson(client, uloSystem, batchUser);
1142
+ for (const u of uloRes.ulos ?? []) {
1143
+ if (u.concept_id && u.ulo) uloByConcept[u.concept_id] = standardStatement(u.ulo);
1144
+ }
1145
+ }
1146
+ for (const c of concepts) {
1147
+ if (!uloByConcept[c.id]) {
1148
+ warnings.push("Phase A: no ULO generated for " + c.id + " \u2014 kept empty (audit will fail)");
1149
+ uloByConcept[c.id] = "";
1150
+ }
1151
+ }
1152
+ concepts.map((c) => "- " + c.id + " (" + c.name + "): " + uloByConcept[c.id]).join("\n");
1153
+ const cioSystem = [
1154
+ "You are a Curriculum Design Expert writing Concept-level Instructional Objectives (CIO).",
1155
+ "",
1156
+ "CIO = Algorithmic Tier: the MECHANISM \u2014 HOW the concept works, step by step, at a",
1157
+ "procedural level. CIOs are derived from approved ULOs.",
1158
+ "",
1159
+ "Rules:",
1160
+ "1. Still technology-agnostic: describe the neutral pattern/approach WITHOUT concrete",
1161
+ " API names, libraries, file formats or syntax.",
1162
+ "2. Marr 2-Language Test: the CIO must read as true and implementable regardless of",
1163
+ " whether the learner uses Python, Swift, JavaScript or any other language. If it",
1164
+ " only makes sense in one language, rewrite it more neutrally.",
1165
+ "3. More concrete than the ULO: reference stages, conditions, ordering or trade-offs",
1166
+ " of the underlying process.",
1167
+ "4. One CIO per concept; 1-3 sentences describing the mechanism.",
1168
+ "5. Statement form (mandatory): every CIO MUST read 'The learner will be able to ...' \u2014",
1169
+ " the mechanism is described after the clause.",
1170
+ "",
1171
+ "Approved style exemplars (production bank):",
1172
+ CIO_EXEMPLARS.map((e) => "- " + e).join("\n"),
1173
+ "",
1174
+ JSON_ONLY
1175
+ ].join("\n");
1176
+ for (const batch of chunkConcepts(concepts, LO_BATCH_SIZE)) {
1177
+ new Set(batch.map((c) => c.id));
1178
+ const batchUloContext = batch.map((c) => "- " + c.id + " (" + c.name + "): " + (uloByConcept[c.id] || "(missing)")).join("\n");
1179
+ const batchCioUser = "Approved ULOs:\n" + batchUloContext + '\n\nReturn JSON:\n{"cios":[{"concept_id":"C1","cio":"..."}]}';
1180
+ const cioRes = await chatJson(client, cioSystem, batchCioUser);
1181
+ for (const x of cioRes.cios ?? []) {
1182
+ if (x.concept_id && x.cio) cioByConcept[x.concept_id] = standardStatement(x.cio);
1183
+ }
1184
+ }
1185
+ for (const c of concepts) {
1186
+ if (!cioByConcept[c.id]) {
1187
+ warnings.push("Phase B: no CIO generated for " + c.id + " \u2014 kept empty (audit will fail)");
1188
+ cioByConcept[c.id] = "";
1189
+ }
1190
+ }
1191
+ concepts.map((c) => "- " + c.id + " (" + c.name + "): CIO=" + cioByConcept[c.id] + " | ULO=" + uloByConcept[c.id]).join("\n");
1192
+ const sioSystem = [
1193
+ "You are a Curriculum Design Expert writing Specific Instructional Objectives (SIO).",
1194
+ "",
1195
+ "SIO = Implementation Tier: completable, context-specific implementation tasks derived",
1196
+ "from approved CIOs, bound to the TARGET technology of the course.",
1197
+ "",
1198
+ "Rules:",
1199
+ "1. EVERY SIO item MUST name concrete keywords/technologies: a real API, function,",
1200
+ " decorator, module, class, file or command of the target technology.",
1201
+ "2. Each item is a completable task: an actionable verb + the concrete construct + the",
1202
+ " context where it is used. Application/Analysis/Creation skills are assessed",
1203
+ " INDIRECTLY through completing these tasks \u2014 there is no fixed Bloom ceiling.",
1204
+ " MACHINE CHECK: every item MUST contain at least one ACTION VERB from this whitelist",
1205
+ " (build, create, implement, write, configure, add, use, apply, display, store, load,",
1206
+ " save, handle, parse, validate, test, register, compute, generate, print, format,",
1207
+ " convert, extend, define, execute, run, read, fetch, wrap, log, call, raise, install,",
1208
+ " import, export, declare, embed, model, represent, override, customize, enforce, mock,",
1209
+ " assert, query, index, cache, stream, split, join, strip, encode, decode, traverse,",
1210
+ " measure, evaluate, benchmark, diagnose, demonstrate, verify, organize, structure,",
1211
+ " choose, select, compare, distinguish, attach, annotate, expose, accept, manage, group,",
1212
+ " sort, filter, map, reduce, catch, throw, migrate, inspect, trace, parameterize,",
1213
+ " construct, design, capture) \u2014 OR wrap the concrete construct in backticks.",
1214
+ " Items with abstract verbs (understand, learn, know, grasp, appreciate, explore) and",
1215
+ " no backtick construct FAIL the audit. Prefer starting the task phrase with the verb.",
1216
+ "3. 2-3 items per concept, each referencing a DIFFERENT concrete construct.",
1217
+ "4. Statement form (mandatory): every SIO MUST read 'The learner will be able to ...' \u2014",
1218
+ " the concrete task follows the clause.",
1219
+ "",
1220
+ "Approved style exemplars (production bank):",
1221
+ SIO_EXEMPLARS.map((e) => "- " + e).join("\n"),
1222
+ "",
1223
+ JSON_ONLY
1224
+ ].join("\n");
1225
+ concepts.map((c) => "- " + c.id + " (" + c.name + "): " + ((c.keywords ?? []).slice(0, 10).join(", ") || "(none listed \u2014 use concrete constructs of " + techStack + ")")).join("\n");
1226
+ for (const batch of chunkConcepts(concepts, LO_BATCH_SIZE)) {
1227
+ 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");
1228
+ const batchCioCtx = batch.map((c) => "- " + c.id + " (" + c.name + "): CIO=" + (cioByConcept[c.id] || "(missing)") + " | ULO=" + (uloByConcept[c.id] || "(missing)")).join("\n");
1229
+ const batchSioUser = [
1230
+ "Target technology: " + techStack,
1231
+ "",
1232
+ "Concept keywords (each SIO item MUST contain at least one of its concept's keywords):",
1233
+ batchKw,
1234
+ "",
1235
+ "Approved CIOs and ULOs:",
1236
+ batchCioCtx,
1237
+ "",
1238
+ "Return JSON:",
1239
+ '{"sios":[{"concept_id":"C1","sio":["...","..."]}]}'
1240
+ ].join("\n");
1241
+ const sioRes = await chatJson(client, sioSystem, batchSioUser);
1242
+ for (const x of sioRes.sios ?? []) {
1243
+ if (x.concept_id && Array.isArray(x.sio)) sioByConcept[x.concept_id] = x.sio.map((item) => standardStatement(String(item)));
1244
+ }
1245
+ }
1246
+ for (const c of concepts) {
1247
+ if (!sioByConcept[c.id] || sioByConcept[c.id].length === 0) {
1248
+ warnings.push("Phase C: no SIO generated for " + c.id + " \u2014 kept empty (audit will fail)");
1249
+ sioByConcept[c.id] = [];
1250
+ }
1251
+ }
1252
+ concepts.map((c) => c.id);
1253
+ const auditOnce = () => auditDepthLayers(concepts.map((c) => ({
1254
+ id: c.id,
1255
+ name: c.name,
1256
+ keywords: c.keywords ?? [],
1257
+ ulo: uloByConcept[c.id],
1258
+ cio: cioByConcept[c.id],
1259
+ sio: sioByConcept[c.id]
1260
+ })));
1261
+ let audits = auditOnce();
1262
+ const repairRound = async (round) => {
1263
+ const failingNow = audits.filter((a) => !a.passed);
1264
+ if (failingNow.length === 0) return false;
1265
+ if (round > 1) warnings.push("Depth audit repair round " + round + ": " + failingNow.length + " concept(s) still failing");
1266
+ const failing = failingNow;
1267
+ {
1268
+ warnings.push("Depth audit: " + failing.length + "/" + concepts.length + " concepts failed first audit \u2014 targeted repair");
1269
+ const repairTargets = failing.map((a) => {
1270
+ const c = concepts.find((x) => x.id === a.conceptId);
1271
+ const issues = [];
1272
+ if (a.uloHasTechSignals) issues.push("ULO names concrete technology (remove: " + a.uloTechSignals.join(", ") + ")");
1273
+ if (a.uloHasImplementationVerbs) issues.push("ULO reads as an implementation task (rewrite as WHAT+WHY competency)");
1274
+ for (const item of a.sioUnboundItems) issues.push("SIO not keyword-bound: " + excerpt(item, 120));
1275
+ for (const item of a.sioOffConceptItems) issues.push("SIO does not reference any of this concept's keywords (" + (c?.keywords ?? []).join(", ") + "): " + excerpt(item, 120));
1276
+ for (const item of a.sioNotCompletable) issues.push("SIO not a completable task: " + excerpt(item, 120));
1277
+ if (!a.concretenessIncreases) issues.push("SIO is not more concrete than the ULO \u2014 bind it to concrete constructs");
1278
+ return {
1279
+ concept_id: a.conceptId,
1280
+ name: c?.name ?? a.conceptId,
1281
+ keywords: c?.keywords ?? [],
1282
+ current: { ulo: uloByConcept[a.conceptId], cio: cioByConcept[a.conceptId], sio: sioByConcept[a.conceptId] },
1283
+ issues
1284
+ };
1285
+ });
1286
+ const repairSystem = [
1287
+ "You repair depth-layer learning objectives that failed a deterministic contract audit.",
1288
+ "For each concept, rewrite ONLY the layers mentioned in issues, keeping the others as-is.",
1289
+ "Contract:",
1290
+ "- ULO: WHAT+WHY, concept-bound, technology-agnostic, Remember/Understand verbs.",
1291
+ "- CIO: HOW mechanism, technology-agnostic, more concrete than ULO, Marr 2-Language neutral.",
1292
+ "- SIO: keyword-bound completable implementation tasks naming real constructs of " + techStack + ".",
1293
+ "- 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).",
1294
+ "- 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.",
1295
+ "",
1296
+ JSON_ONLY
1297
+ ].join("\n");
1298
+ const repairUser = [
1299
+ "Failing concepts:",
1300
+ JSON.stringify(repairTargets, null, 2),
1301
+ "",
1302
+ "Return the FULL repaired set for these concepts in the same 3-layer JSON shape:",
1303
+ '{"repairs":[{"concept_id":"C1","ulo":"...","cio":"...","sio":["..."]}]}'
1304
+ ].join("\n");
1305
+ try {
1306
+ const repairRes = await chatJson(client, repairSystem, repairUser);
1307
+ for (const r of repairRes.repairs ?? []) {
1308
+ if (!r.concept_id) continue;
1309
+ if (r.ulo) uloByConcept[r.concept_id] = standardStatement(r.ulo);
1310
+ if (r.cio) cioByConcept[r.concept_id] = standardStatement(r.cio);
1311
+ if (Array.isArray(r.sio) && r.sio.length > 0) sioByConcept[r.concept_id] = r.sio.map((t) => standardStatement(String(t)));
1312
+ }
1313
+ audits = auditOnce();
1314
+ } catch (err) {
1315
+ warnings.push("Depth repair round failed: " + (err instanceof Error ? err.message : String(err)));
1316
+ }
1317
+ }
1318
+ return audits.every((a) => a.passed);
1319
+ };
1320
+ for (let round = 1; round <= 2; round++) {
1321
+ const allPass = await repairRound(round);
1322
+ if (allPass) break;
1323
+ }
1324
+ const stillFailing = audits.filter((a) => !a.passed);
1325
+ if (stillFailing.length > 0) {
1326
+ try {
1327
+ const { mkdirSync: mkdirSync2, writeFileSync: writeFileSync2 } = await import('fs');
1328
+ const dumpDir = (await import('os')).tmpdir() + "/domain-kit-debug/";
1329
+ mkdirSync2(dumpDir, { recursive: true });
1330
+ writeFileSync2(dumpDir + "depth-audit-debug.json", JSON.stringify(
1331
+ stillFailing.map((a) => ({ audit: a, ulo: uloByConcept[a.conceptId], cio: cioByConcept[a.conceptId], sio: sioByConcept[a.conceptId] })),
1332
+ null,
1333
+ 2
1334
+ ));
1335
+ } catch {
1336
+ }
1337
+ 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(", ");
1338
+ throw new Error(
1339
+ "Depth-layer contract audit failed after repair for: " + detail + " \u2014 regenerate or fix the prompt contract (fail-closed, no silent fallback)"
1340
+ );
1341
+ }
1342
+ return { uloByConcept, cioByConcept, sioByConcept, audits, warnings };
1343
+ }
1344
+ function cell(v) {
1345
+ return (v || "").split(",").map((s) => s.trim()).filter(Boolean);
1346
+ }
1347
+ function loadKnowledgeTreeCatalog(tsvPath) {
1348
+ const text = fs.readFileSync(tsvPath, "utf8");
1349
+ const lines = text.split("\n").filter((l) => l.trim().length > 0);
1350
+ if (lines.length === 0) throw new Error("Knowledge tree TSV is empty: " + tsvPath);
1351
+ const header = lines[0].split(" ").map((h) => h.trim());
1352
+ const col = (name) => header.indexOf(name);
1353
+ const iT = col("item_type");
1354
+ const iC = col("code");
1355
+ const iN = col("name");
1356
+ const iD = col("description");
1357
+ const iCat = col("category_codes");
1358
+ const iTpc = col("topic_codes");
1359
+ const iPre = col("prerequisite_concept_codes");
1360
+ const iKw = col("keywords");
1361
+ for (const [name, idx] of [["item_type", iT], ["code", iC], ["name", iN]]) {
1362
+ if (idx < 0) throw new Error("Knowledge tree TSV missing column: " + name);
1363
+ }
1364
+ const categories = /* @__PURE__ */ new Map();
1365
+ const topics = /* @__PURE__ */ new Map();
1366
+ const concepts = [];
1367
+ for (const line of lines.slice(1)) {
1368
+ const c = line.split(" ");
1369
+ const type = (c[iT] || "").trim();
1370
+ const code = (c[iC] || "").trim();
1371
+ const name = (c[iN] || "").trim();
1372
+ if (!code || !name) continue;
1373
+ if (type === "CATEGORY") categories.set(code, name);
1374
+ if (type === "TOPIC") topics.set(code, { name, categoryCodes: cell(c[iCat]) });
1375
+ if (type !== "CONCEPT") continue;
1376
+ const topicCodes = cell(c[iTpc]);
1377
+ const categoryCodes = /* @__PURE__ */ new Set();
1378
+ for (const t of topicCodes) for (const cc of topics.get(t)?.categoryCodes || []) categoryCodes.add(cc);
1379
+ concepts.push({
1380
+ code,
1381
+ name,
1382
+ description: (c[iD] || "").trim(),
1383
+ keywords: cell(c[iKw]),
1384
+ topicCodes,
1385
+ categoryCodes: [...categoryCodes],
1386
+ prerequisiteCodes: cell(c[iPre])
1387
+ });
1388
+ }
1389
+ if (concepts.length === 0) throw new Error("Knowledge tree TSV has no CONCEPT rows: " + tsvPath);
1390
+ return { path: tsvPath, concepts, categories, topics };
1391
+ }
1392
+ function tokens(s) {
1393
+ return new Set(
1394
+ s.toLowerCase().replace(/[^a-z0-9\s-]/g, " ").split(/\s+/).filter((w) => w.length >= 4)
1395
+ );
1396
+ }
1397
+ function filterBySelection(catalog, selectedCategories, selectedTopics, analysisConcepts, maxConcepts = 120) {
1398
+ const tps = new Set(selectedTopics.map((c) => c.trim().toUpperCase()).filter(Boolean));
1399
+ const cats = new Set(selectedCategories.map((c) => c.trim().toUpperCase()).filter(Boolean));
1400
+ const probe = analysisConcepts.map((c) => tokens(c.name + " " + c.keywords.join(" ")));
1401
+ const probeAll = /* @__PURE__ */ new Set();
1402
+ for (const p of probe) for (const w of p) probeAll.add(w);
1403
+ const inSelection = (tc) => tc.topicCodes.some((t) => tps.has(t)) || tc.categoryCodes.some((c) => cats.has(c));
1404
+ const overlapScore = (tc) => {
1405
+ const tcTok = tokens(tc.name + " " + tc.description.slice(0, 300) + " " + tc.keywords.join(" "));
1406
+ let overlap = 0;
1407
+ for (const w of tcTok) if (probeAll.has(w)) overlap++;
1408
+ const kwDirect = tc.keywords.filter((k) => {
1409
+ const kl = k.toLowerCase();
1410
+ return [...probeAll].some((w) => w === kl || w.length >= 5 && kl.includes(w));
1411
+ }).length;
1412
+ return overlap * 2 + kwDirect * 3;
1413
+ };
1414
+ const kept = catalog.concepts.filter((tc) => inSelection(tc) || overlapScore(tc) >= 6);
1415
+ return kept.map((tc) => ({ tc, s: overlapScore(tc) })).sort((a, b) => b.s - a.s).slice(0, maxConcepts).map((x) => x.tc);
1416
+ }
1417
+ function renderShortlist(shortlist) {
1418
+ return shortlist.map((tc) => "- " + tc.code + " | " + tc.name + " | kw: " + tc.keywords.slice(0, 8).join(", ") + (tc.prerequisiteCodes.length ? " | prereqs: " + tc.prerequisiteCodes.join(",") : "")).join("\n");
1419
+ }
1420
+ function renderCategoryTopicIndex(catalog) {
1421
+ const topicToConcepts = /* @__PURE__ */ new Map();
1422
+ for (const tc of catalog.concepts) for (const t of tc.topicCodes) topicToConcepts.set(t, (topicToConcepts.get(t) || 0) + 1);
1423
+ const byCat = /* @__PURE__ */ new Map();
1424
+ for (const [code, info] of catalog.topics) {
1425
+ for (const cat of info.categoryCodes) {
1426
+ const arr = byCat.get(cat) || [];
1427
+ arr.push(code + " " + info.name + " (" + (topicToConcepts.get(code) || 0) + " concepts)");
1428
+ byCat.set(cat, arr);
1429
+ }
1430
+ }
1431
+ const out = [];
1432
+ for (const [code, name] of catalog.categories) {
1433
+ out.push("CATEGORY " + code + " \u2014 " + name);
1434
+ for (const t of byCat.get(code) || []) out.push(" TOPIC: " + t);
1435
+ }
1436
+ return out.join("\n");
1437
+ }
1438
+ var JSON_ONLY2 = "Return ONLY a JSON object, no markdown fences, no commentary.";
1439
+ function parseJsonBlock(text) {
1440
+ const start = text.indexOf("{");
1441
+ const end = text.lastIndexOf("}");
1442
+ if (start < 0 || end <= start) throw new Error("LLM standardization response has no JSON object");
1443
+ return JSON.parse(text.slice(start, end + 1));
1444
+ }
1445
+ async function standardizeConcepts(opts) {
1446
+ const { client, catalog, techStack = "python", proposalsPath } = opts;
1447
+ const log = opts.onProgress ?? (() => {
1448
+ });
1449
+ const warnings = [];
1450
+ const hasTopics = catalog.topics.size > 0;
1451
+ const selSystem = [
1452
+ "You pre-select relevant areas of an institutional knowledge tree before a detailed concept alignment pass.",
1453
+ 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.",
1454
+ "- Be generous: missing a relevant topic corrupts the alignment; an extra topic only costs attention.",
1455
+ "- Only codes that appear in the index are valid.",
1456
+ JSON_ONLY2
1457
+ ].join("\n");
1458
+ const selUser = [
1459
+ "ANALYSIS CONCEPTS:",
1460
+ opts.concepts.map((c) => "- " + c.name + ": " + c.description.slice(0, 160)).join("\n"),
1461
+ "",
1462
+ "KNOWLEDGE TREE INDEX:",
1463
+ renderCategoryTopicIndex(catalog),
1464
+ "",
1465
+ hasTopics ? 'Return JSON: {"relevant_topics":["TOPIC_CODE"]}' : 'Return JSON: {"relevant_categories":["CATEGORY_CODE"]}'
1466
+ ].join("\n");
1467
+ const selRes = await client.chat(
1468
+ [{ role: "system", content: selSystem }, { role: "user", content: selUser }],
1469
+ { temperature: 0, maxTokens: 4096 }
1470
+ );
1471
+ const sel = parseJsonBlock(selRes.content);
1472
+ const selTps = hasTopics ? (sel.relevant_topics || []).map(String).filter(Boolean) : [];
1473
+ const selCats = hasTopics ? [] : (sel.relevant_categories || []).map(String).filter(Boolean);
1474
+ log("STEP_2_5", "LLM relevance pre-selection (" + (hasTopics ? "topics" : "categories") + "): " + (hasTopics ? selTps.join(",") : selCats.join(",")));
1475
+ const shortlist = filterBySelection(catalog, selCats, selTps, opts.concepts);
1476
+ log("STEP_2_5", "Filtered tree concepts: " + shortlist.length + "/" + catalog.concepts.length + " shortlisted for alignment");
1477
+ if (shortlist.length === 0) throw new Error("Topic/category pre-selection eliminated every tree concept \u2014 fail-closed");
1478
+ const system = [
1479
+ "You align auto-derived learning concepts with an institutional knowledge tree.",
1480
+ "For EACH input concept decide exactly one of:",
1481
+ ` 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.`,
1482
+ " Adopt the tree's terminology. Only propose new when the tree genuinely has NO concept teaching that knowledge (broader AND narrower both fail).",
1483
+ ' 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.',
1484
+ " If between 1 and 3 tree concepts are CLOSE but not exact, list their codes in possible_tree_matches for human review.",
1485
+ `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.`,
1486
+ "Rules:",
1487
+ "- Judge by MEANING (definition + keywords), not by string similarity.",
1488
+ '- 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.',
1489
+ "- Context-specific wording does NOT make a new concept: new concept = knowledge absent from the tree, not knowledge applied elsewhere.",
1490
+ "- Every input concept MUST receive exactly one decision. Never merge two input concepts into one tree code.",
1491
+ "- Prefer proposed_new over a wrong standardized match: a false match corrupts the curriculum.",
1492
+ JSON_ONLY2
1493
+ ].join("\n");
1494
+ const user = [
1495
+ "TECH STACK: " + techStack,
1496
+ "",
1497
+ "ANALYSIS CONCEPTS (to standardize):",
1498
+ 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),
1499
+ "",
1500
+ "KNOWLEDGE TREE SHORTLIST (pre-filtered, " + shortlist.length + " candidate concepts):",
1501
+ renderShortlist(shortlist),
1502
+ "",
1503
+ 'Return JSON: {"decisions":[{"id":"<input id>","decision":"standardized","tree_code":"TREE_CODE","adopted_keywords":["kw1","kw2"],"note":"one sentence"},',
1504
+ ' {"id":"<input id>","decision":"proposed_new","proposed_code":"PROPOSED_CODE","proposed_definition":"...","possible_tree_matches":["CODE"]}]}'
1505
+ ].join("\n");
1506
+ const res = await client.chat(
1507
+ [{ role: "system", content: system }, { role: "user", content: user }],
1508
+ { temperature: 0, maxTokens: 8192 }
1509
+ );
1510
+ log("STEP_2_5", "Standardization response received (provider " + res.provider + ")");
1511
+ const parsed = parseJsonBlock(res.content);
1512
+ const decisions = parsed.decisions ?? [];
1513
+ const byId = new Map(decisions.map((d) => [String(d.id), d]));
1514
+ const finalDecisions = [];
1515
+ const proposals = [];
1516
+ for (const c of opts.concepts) {
1517
+ const d = byId.get(c.id);
1518
+ if (!d || d.decision !== "standardized" && d.decision !== "proposed_new") {
1519
+ throw new Error("Concept " + c.id + " (" + c.name + ") has no standardization decision \u2014 fail-closed");
1520
+ }
1521
+ if (d.decision === "standardized") {
1522
+ const tc = catalog.concepts.find((x) => x.code === d.tree_code);
1523
+ if (!tc) throw new Error("Concept " + c.id + " standardized to unknown tree code " + d.tree_code + " \u2014 fail-closed");
1524
+ const treeKw = new Set(tc.keywords.map((k) => k.toLowerCase()));
1525
+ const adopted = (d.adopted_keywords || []).map((k) => String(k)).filter((k) => {
1526
+ if (treeKw.has(k.toLowerCase())) return true;
1527
+ throw new Error("Concept " + c.id + ' adopted keyword "' + k + '" not in tree concept ' + tc.code + " \u2014 fail-closed");
1528
+ });
1529
+ if (tc.keywords.length > 0 && adopted.length === 0) {
1530
+ throw new Error("Concept " + c.id + " standardized to " + tc.code + " without adopted_keywords \u2014 fail-closed");
1531
+ }
1532
+ finalDecisions.push({ ...d, id: c.id, tree_code: tc.code, adopted_keywords: adopted });
1533
+ warnings.push("Concept " + c.id + " standardized as " + tc.code + " (" + tc.name + "), adopted keywords: " + adopted.join(", ") + (d.note ? " \u2014 " + d.note : ""));
1534
+ } else {
1535
+ const code = (d.proposed_code || "").toUpperCase().replace(/[^A-Z0-9_]/g, "_");
1536
+ if (!/^[A-Z][A-Z0-9_]*$/.test(code)) {
1537
+ throw new Error("Concept " + c.id + ' proposed invalid code "' + d.proposed_code + '" \u2014 fail-closed');
1538
+ }
1539
+ finalDecisions.push({ ...d, id: c.id, proposed_code: code });
1540
+ proposals.push({
1541
+ code,
1542
+ name: c.name,
1543
+ description: d.proposed_definition || c.description.slice(0, 300),
1544
+ keywords: c.keywords,
1545
+ subject_codes: "PY",
1546
+ category_codes: "",
1547
+ topic_codes: "",
1548
+ prerequisite_concept_codes: [],
1549
+ status: "proposed",
1550
+ source_concept_id: c.id,
1551
+ possible_tree_matches: (d.possible_tree_matches || []).filter(Boolean)
1552
+ });
1553
+ warnings.push("Concept " + c.id + " proposed as NEW: " + code + (d.possible_tree_matches?.length ? " (near matches: " + d.possible_tree_matches.join(", ") + ")" : ""));
1554
+ }
1555
+ }
1556
+ const outPath = proposalsPath || path.join(os.tmpdir(), "domain-kit-debug", "concept-proposals.json");
1557
+ try {
1558
+ fs.mkdirSync(outPath.slice(0, outPath.lastIndexOf("/")), { recursive: true });
1559
+ fs.writeFileSync(outPath, JSON.stringify({ generated_at: (/* @__PURE__ */ new Date()).toISOString(), proposals }, null, 2));
1560
+ log("STEP_2_5", "Proposals written: " + proposals.length + " -> " + outPath);
1561
+ } catch (e) {
1562
+ warnings.push("Could not write proposals artifact: " + (e instanceof Error ? e.message : String(e)));
1563
+ }
1564
+ return { decisions: finalDecisions, proposals, warnings, shortlistSize: shortlist.length, catalogSize: catalog.concepts.length };
1565
+ }
1566
+
1567
+ // src/graph/knowledgeGraphPipeline.ts
1568
+ function detectCycles(concepts) {
1569
+ const cycles = [];
1570
+ const visited = /* @__PURE__ */ new Set();
1571
+ const inStack = /* @__PURE__ */ new Set();
1572
+ const path = [];
1573
+ function dfs(conceptId, prereqMap2) {
1574
+ if (inStack.has(conceptId)) {
1575
+ const cycleStart = path.indexOf(conceptId);
1576
+ if (cycleStart >= 0) {
1577
+ cycles.push([...path.slice(cycleStart), conceptId]);
1578
+ }
1579
+ return;
1580
+ }
1581
+ if (visited.has(conceptId)) return;
1582
+ visited.add(conceptId);
1583
+ inStack.add(conceptId);
1584
+ path.push(conceptId);
1585
+ const prereqs = prereqMap2.get(conceptId) || [];
1586
+ for (const prereq of prereqs) {
1587
+ dfs(prereq, prereqMap2);
1588
+ }
1589
+ path.pop();
1590
+ inStack.delete(conceptId);
1591
+ }
1592
+ const prereqMap = /* @__PURE__ */ new Map();
1593
+ for (const concept of concepts) {
1594
+ prereqMap.set(concept.id, concept.prerequisites || []);
1595
+ }
1596
+ for (const concept of concepts) {
1597
+ if (!visited.has(concept.id)) {
1598
+ dfs(concept.id, prereqMap);
1599
+ }
1600
+ }
1601
+ return cycles;
1602
+ }
1603
+ function breakCycles(concepts, cycles) {
1604
+ const removed = [];
1605
+ const fixed = concepts.map((c) => ({ ...c, prerequisites: [...c.prerequisites || []] }));
1606
+ for (const cycle of cycles) {
1607
+ if (cycle.length >= 2) {
1608
+ const breaker = cycle[cycle.length - 2];
1609
+ const target = cycle[cycle.length - 1];
1610
+ for (const concept of fixed) {
1611
+ if (concept.id === breaker) {
1612
+ concept.prerequisites = concept.prerequisites.filter((p) => p !== target);
1613
+ removed.push({ from: breaker, to: target });
1614
+ }
1615
+ }
1616
+ }
1617
+ }
1618
+ return { fixed, removed };
1619
+ }
1620
+ function topologicalSort(concepts) {
1621
+ const inDegree = /* @__PURE__ */ new Map();
1622
+ const adjacency = /* @__PURE__ */ new Map();
1623
+ for (const concept of concepts) {
1624
+ inDegree.set(concept.id, 0);
1625
+ adjacency.set(concept.id, []);
1626
+ }
1627
+ for (const concept of concepts) {
1628
+ for (const prereq of concept.prerequisites || []) {
1629
+ adjacency.get(prereq)?.push(concept.id);
1630
+ inDegree.set(concept.id, (inDegree.get(concept.id) || 0) + 1);
1631
+ }
1632
+ }
1633
+ const queue = [];
1634
+ for (const [id, degree] of inDegree) {
1635
+ if (degree === 0) queue.push(id);
1636
+ }
1637
+ const sorted = [];
1638
+ while (queue.length > 0) {
1639
+ const current = queue.shift();
1640
+ sorted.push(current);
1641
+ for (const neighbor of adjacency.get(current) || []) {
1642
+ const newDegree = (inDegree.get(neighbor) || 1) - 1;
1643
+ inDegree.set(neighbor, newDegree);
1644
+ if (newDegree === 0) queue.push(neighbor);
1645
+ }
1646
+ }
1647
+ if (sorted.length !== concepts.length) {
1648
+ console.warn(`[WARN] Topological sort incomplete: ${sorted.length}/${concepts.length} concepts sorted`);
1649
+ }
1650
+ return sorted;
1651
+ }
1652
+ async function generateKnowledgeGraph(options) {
1653
+ const { subject, description, syllabusText, gradeBand, domain, techStack, llmConfig, onProgress } = options;
1654
+ const warnings = [];
1655
+ const log = (step, msg) => {
1656
+ console.log(`[KG-${step}] ${msg}`);
1657
+ onProgress?.(step, msg);
1658
+ };
1659
+ log("STEP_1", "Decomposing subject into concepts...");
1660
+ const client = createLlmClient(llmConfig);
1661
+ const maxSyllabusChars = parseInt(process.env.KG_MAX_SYLLABUS_CHARS || "16000", 10);
1662
+ let truncatedSyllabus = "";
1663
+ if (syllabusText) {
1664
+ if (syllabusText.length > maxSyllabusChars) {
1665
+ truncatedSyllabus = syllabusText.slice(0, maxSyllabusChars);
1666
+ warnings.push(`Syllabus truncated from ${syllabusText.length} to ${maxSyllabusChars} chars \u2014 may miss some concepts`);
1667
+ } else {
1668
+ truncatedSyllabus = syllabusText;
1669
+ }
1670
+ }
1671
+ 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";
1672
+ const userPrompt = `Subject: ${subject}
1673
+ ${description ? `Description: ${description}` : ""}
1674
+ ${truncatedSyllabus ? `Syllabus:
1675
+ ${truncatedSyllabus}` : ""}
1676
+ ${gradeBand ? `Grade band: ${gradeBand[0]}-${gradeBand[1]}` : ""}
1677
+ ${domain ? `Domain: ${domain}` : ""}
1678
+
1679
+ Return JSON:
1680
+ {
1681
+ "subject": {
1682
+ "id": "${subject.toLowerCase().replace(/\s+/g, "-").slice(0, 30)}",
1683
+ "name": "${subject}",
1684
+ "description": "...",
1685
+ "domain": "${domain || "other"}",
1686
+ "grade_band": ${gradeBand ? `[${gradeBand[0]}, ${gradeBand[1]}]` : "[6, 12]"}
1687
+ },
1688
+ "concepts": [
1689
+ {
1690
+ "id": "C1",
1691
+ "name": "Concept name",
1692
+ "description": "Brief description",
1693
+ "category": "category_id",
1694
+ "ulo": "WHAT + WHY in technology-agnostic language: what the concept is and the problem it exists to solve. No library/API/tool names.",
1695
+ "cio": "HOW the mechanism works, still technology-agnostic but more concrete than the ULO.",
1696
+ "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"],
1697
+ "prerequisites": [],
1698
+ "estimated_minutes": 30,
1699
+ "problem_types": [
1700
+ {
1701
+ "id": "PT-C1-01",
1702
+ "name": "Problem type name",
1703
+ "description": "What this problem type tests",
1704
+ "bloom_level": "Remember",
1705
+ "difficulty": "easy",
1706
+ "estimated_minutes": 10
1707
+ }
1708
+ ],
1709
+ "techniques": ["technique 1", "technique 2"],
1710
+ "common_mistakes": ["mistake 1"]
1711
+ }
1712
+ ],
1713
+ "categories": [
1714
+ {
1715
+ "id": "cat1",
1716
+ "name": "Category name",
1717
+ "description": "Category description",
1718
+ "concept_ids": ["C1", "C2"],
1719
+ "order": 1
1720
+ }
1721
+ ],
1722
+ "learning_path": [
1723
+ {"concept_id": "C1", "order": 1, "depends_on": []},
1724
+ {"concept_id": "C2", "order": 2, "depends_on": ["C1"]}
1725
+ ]
1726
+ }`;
1727
+ const result = await llmChatJson(client, systemPrompt, userPrompt, {
1728
+ temperature: 0.1,
1729
+ maxTokens: parseInt(process.env.KG_MAX_TOKENS || "65536", 10)
1730
+ });
1731
+ log("STEP_2", "Validating and cleaning knowledge graph...");
1732
+ const concepts = result.concepts || [];
1733
+ const categories = result.categories || [];
1734
+ {
1735
+ 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"]);
1736
+ const tokensFrom = (text) => text.toLowerCase().replace(/[^a-z0-9\s-]/g, " ").split(/\s+/).filter((w) => w.length >= 4 && !STOP.has(w));
1737
+ for (const c of concepts) {
1738
+ const existing = (c.keywords || []).map((k) => String(k).trim()).filter(Boolean);
1739
+ if (existing.length === 0) {
1740
+ const derived = [.../* @__PURE__ */ new Set([...tokensFrom(c.name), ...tokensFrom(c.description || "")])].slice(0, 5);
1741
+ if (derived.length === 0) {
1742
+ throw new Error("Concept " + c.id + " (" + c.name + ") has no keywords and none could be derived from name/description \u2014 fail-closed");
1743
+ }
1744
+ c.keywords = derived;
1745
+ warnings.push("Concept " + c.id + ": empty keyword set - derived " + derived.join(", ") + " from name/description");
1746
+ } else {
1747
+ c.keywords = existing;
1748
+ }
1749
+ }
1750
+ }
1751
+ const rawPath = result.learning_path;
1752
+ let learningPath = (rawPath || []).map((s) => ({
1753
+ concept_id: String(s.concept_id || ""),
1754
+ order: Number(s.order || 0),
1755
+ depends_on: Array.isArray(s.depends_on) ? s.depends_on.map(String) : [],
1756
+ milestone_name: String(s.milestone_name || "")
1757
+ }));
1758
+ const conceptIds = new Set(concepts.map((c) => c.id));
1759
+ for (const concept of concepts) {
1760
+ for (const prereq of concept.prerequisites || []) {
1761
+ if (!conceptIds.has(prereq)) {
1762
+ warnings.push(`Concept ${concept.id} references non-existent prerequisite ${prereq} \u2014 removed`);
1763
+ concept.prerequisites = (concept.prerequisites || []).filter((p) => p !== prereq);
1764
+ }
1765
+ }
1766
+ }
1767
+ if (options.knowledgeTreePath) {
1768
+ const catalog = loadKnowledgeTreeCatalog(options.knowledgeTreePath);
1769
+ log("STEP_2_5", "Knowledge tree loaded: " + catalog.concepts.length + " concepts from " + catalog.path.split("/").pop());
1770
+ const std = await standardizeConcepts({
1771
+ client,
1772
+ concepts: concepts.map((c) => ({
1773
+ id: c.id,
1774
+ name: c.name,
1775
+ description: c.description || "",
1776
+ keywords: c.keywords || []
1777
+ })),
1778
+ catalog,
1779
+ techStack,
1780
+ proposalsPath: options.proposalsPath,
1781
+ onProgress: log
1782
+ });
1783
+ warnings.push(...std.warnings);
1784
+ const codeByStd = new Map(std.decisions.map((d) => [d.id, d]));
1785
+ for (const c of concepts) {
1786
+ const d = codeByStd.get(c.id);
1787
+ if (!d) throw new Error("Concept " + c.id + " missing standardization decision \u2014 fail-closed");
1788
+ if (d.decision === "standardized") {
1789
+ c.standardization = "standardized";
1790
+ c.tree_code = d.tree_code;
1791
+ c.code = d.tree_code;
1792
+ const tc = catalog.concepts.find((x) => x.code === d.tree_code);
1793
+ if (tc) {
1794
+ for (const k of d.adopted_keywords || []) {
1795
+ if (!(c.keywords || []).some((x) => x.toLowerCase() === k.toLowerCase())) {
1796
+ c.keywords = [...c.keywords || [], k];
1797
+ }
1798
+ }
1799
+ c.tree_prerequisites = tc.prerequisiteCodes;
1800
+ }
1801
+ } else {
1802
+ c.standardization = "proposed_new";
1803
+ c.code = d.proposed_code;
1804
+ }
1805
+ }
1806
+ const idByTreeCode = new Map(concepts.filter((c) => c.tree_code).map((c) => [c.tree_code, c.id]));
1807
+ for (const c of concepts) {
1808
+ for (const tp of c.tree_prerequisites || []) {
1809
+ const target = idByTreeCode.get(tp);
1810
+ if (target && target !== c.id && !(c.prerequisites || []).includes(target)) {
1811
+ c.prerequisites = [...c.prerequisites || [], target];
1812
+ warnings.push("Prereq seeded from tree: " + c.id + " <- " + tp + " (" + target + ")");
1813
+ }
1814
+ }
1815
+ }
1816
+ log("STEP_2_5", "Standardized: " + std.decisions.filter((d) => d.decision === "standardized").length + ", proposed new: " + std.decisions.filter((d) => d.decision === "proposed_new").length);
1817
+ }
1818
+ log("STEP_3", "Checking for prerequisite cycles...");
1819
+ const cycles = detectCycles(concepts);
1820
+ if (cycles.length > 0) {
1821
+ log("STEP_3", `Found ${cycles.length} cycle(s) in prerequisite chain \u2014 breaking cycles`);
1822
+ for (const cycle of cycles) {
1823
+ warnings.push(`Cycle detected: ${cycle.join(" \u2192 ")} \u2014 breaking at weakest edge`);
1824
+ }
1825
+ const { fixed, removed } = breakCycles(concepts, cycles);
1826
+ for (let i = 0; i < concepts.length; i++) {
1827
+ const fixedConcept = fixed.find((f) => f.id === concepts[i].id);
1828
+ if (fixedConcept) {
1829
+ concepts[i] = { ...concepts[i], prerequisites: fixedConcept.prerequisites };
1830
+ }
1831
+ }
1832
+ for (const { from, to } of removed) {
1833
+ warnings.push(`Removed prerequisite edge: ${from} \u2192 ${to} (cycle breaker)`);
1834
+ }
1835
+ }
1836
+ log("STEP_4", "Topological sort of concepts...");
1837
+ const sortedIds = topologicalSort(concepts);
1838
+ learningPath = sortedIds.map((id, idx) => {
1839
+ const concept = concepts.find((c) => c.id === id);
1840
+ return {
1841
+ concept_id: id,
1842
+ order: idx + 1,
1843
+ depends_on: concept?.prerequisites || [],
1844
+ milestone_name: ""
1845
+ };
1846
+ });
1847
+ log("STEP_5", "Authoring ULO/CIO/SIO depth layers hierarchically...");
1848
+ {
1849
+ const lo = await authorDepthLayersHierarchically(
1850
+ client,
1851
+ concepts.map((c) => ({ id: c.id, name: c.name, description: c.description, keywords: c.keywords })),
1852
+ techStack || (domain === "software" || domain === "technology" ? "python" : domain || "general"),
1853
+ warnings
1854
+ );
1855
+ const codeByConceptId = assignConceptCodes(concepts.map((c) => ({ id: c.id, name: c.name })));
1856
+ const techTag = techTagFor(techStack || (domain === "software" || domain === "technology" ? "python" : domain || "general"));
1857
+ for (const concept of concepts) {
1858
+ concept.ulo = lo.uloByConcept[concept.id] || concept.ulo || "";
1859
+ concept.cio = lo.cioByConcept[concept.id] || concept.cio || "";
1860
+ if (lo.sioByConcept[concept.id] && lo.sioByConcept[concept.id].length > 0) {
1861
+ concept.sio = lo.sioByConcept[concept.id];
1862
+ }
1863
+ concept.code = concept.code || codeByConceptId[concept.id];
1864
+ concept.ulo_code = concept.ulo ? uloCode(concept.code) : concept.ulo_code;
1865
+ concept.cio_code = concept.cio ? cioCode(concept.code, 1, cioActionSlug(concept.cio)) : concept.cio_code;
1866
+ concept.sio_codes = concept.sio.length > 0 ? concept.sio.map((_, i) => sioCode(techTag, concept.code, i + 1)) : concept.sio_codes;
1867
+ }
1868
+ log("STEP_5", "Depth layers authored: " + concepts.length + " concepts, audit " + lo.audits.filter((a) => a.passed).length + "/" + concepts.length + " passed");
1869
+ }
1870
+ for (const step of learningPath) {
1871
+ if (!conceptIds.has(step.concept_id)) {
1872
+ warnings.push(`Learning path references non-existent concept ${step.concept_id}`);
1873
+ }
1874
+ }
1875
+ log("STEP_2", `Validated ${concepts.length} concepts, ${categories.length} categories, ${learningPath.length} learning path steps`);
1876
+ return {
1877
+ knowledgeGraph: {
1878
+ schema_version: 1,
1879
+ type: "knowledge_graph",
1880
+ subject: result.subject,
1881
+ concepts,
1882
+ categories,
1883
+ learning_path: learningPath
1884
+ },
1885
+ warnings
1886
+ };
1887
+ }
1888
+
1889
+ // src/graph/hybridGraphPipeline.ts
1890
+ async function generateHybridGraph(options) {
1891
+ const { projectGraph, knowledgeGraph, llmConfig, onProgress } = options;
1892
+ const warnings = [];
1893
+ const log = (step, msg) => {
1894
+ console.log("[HG-" + step + "] " + msg);
1895
+ onProgress?.(step, msg);
1896
+ };
1897
+ const features = projectGraph.features || [];
1898
+ const concepts = knowledgeGraph.concepts || [];
1899
+ if (features.length === 0 || concepts.length === 0) {
1900
+ warnings.push("No features or concepts to link");
1901
+ return {
1902
+ hybridGraph: {
1903
+ schema_version: 1,
1904
+ type: "hybrid_graph",
1905
+ project_graph: projectGraph,
1906
+ knowledge_graph: knowledgeGraph,
1907
+ links: [],
1908
+ phases: [],
1909
+ description: "",
1910
+ total_project_minutes: 0,
1911
+ total_concept_minutes: 0,
1912
+ estimated_total_minutes: 0
1913
+ },
1914
+ warnings
1915
+ };
1916
+ }
1917
+ const client = createLlmClient(llmConfig);
1918
+ const featuresList = features.map(
1919
+ (f) => "- " + f.id + ": " + f.name + " - " + (f.description || "") + " (keywords: " + (f.steps || []).flatMap((s) => s.keywords || []).slice(0, 5).join(", ") + ")"
1920
+ ).join("\n");
1921
+ const conceptsList = concepts.map(
1922
+ (c) => "- " + c.id + ": " + c.name + " - ULO: " + (c.ulo || "").slice(0, 100) + " (prerequisites: " + (c.prerequisites || []).join(", ") + ")"
1923
+ ).join("\n");
1924
+ 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";
1925
+ const userPrompt = "FEATURES:\n" + featuresList + "\n\nCONCEPTS:\n" + conceptsList + "\n\nCreate links between features and concepts. Return JSON.\n";
1926
+ const result = await llmChatJson(client, systemPrompt, userPrompt, {
1927
+ temperature: 0.1,
1928
+ maxTokens: 16384
1929
+ });
1930
+ const rawLinks = result.links || [];
1931
+ const featureIds = new Set(features.map((f) => f.id));
1932
+ const conceptIds = new Set(concepts.map((c) => c.id));
1933
+ const validLinks = [];
1934
+ for (const link of rawLinks) {
1935
+ const fid = String(link.feature_id || "");
1936
+ const cid = String(link.concept_id || "");
1937
+ if (!featureIds.has(fid)) {
1938
+ warnings.push("Link references non-existent feature " + fid);
1939
+ continue;
1940
+ }
1941
+ if (!conceptIds.has(cid)) {
1942
+ warnings.push("Link references non-existent concept " + cid);
1943
+ continue;
1944
+ }
1945
+ validLinks.push({
1946
+ feature_id: fid,
1947
+ concept_id: cid,
1948
+ relationship: link.relationship || "requires",
1949
+ depth: link.depth || "cio",
1950
+ description: String(link.description || ""),
1951
+ estimated_prereq_minutes: Number(link.estimated_prereq_minutes) || 0,
1952
+ phase_id: ""
1953
+ });
1954
+ }
1955
+ log("STEP_1", "Generated " + validLinks.length + " feature-concept links");
1956
+ const phases = await decomposePhases({
1957
+ features,
1958
+ concepts,
1959
+ links: validLinks,
1960
+ client,
1961
+ log,
1962
+ warnings
1963
+ });
1964
+ const phaseByFeature = /* @__PURE__ */ new Map();
1965
+ for (const ph of phases) {
1966
+ for (const fid of ph.feature_ids) phaseByFeature.set(fid, ph.id);
1967
+ }
1968
+ for (const link of validLinks) link.phase_id = phaseByFeature.get(link.feature_id) || "";
1969
+ log("STEP_3", "Calculating totals...");
1970
+ const totalProjectMinutes = features.reduce((sum, f) => {
1971
+ const featureMinutes = (f.steps || []).reduce((s, step) => s + (step.effort?.estimated_minutes || 15), 0);
1972
+ return sum + featureMinutes;
1973
+ }, 0);
1974
+ const totalConceptMinutes = concepts.reduce((sum, c) => sum + (c.estimated_minutes || 30), 0);
1975
+ const prereqMinutesByConcept = /* @__PURE__ */ new Map();
1976
+ for (const link of validLinks) {
1977
+ const mins = link.estimated_prereq_minutes || 0;
1978
+ if (mins > 0) {
1979
+ const existing = prereqMinutesByConcept.get(link.concept_id) || 0;
1980
+ prereqMinutesByConcept.set(link.concept_id, Math.max(existing, mins));
1981
+ }
1982
+ }
1983
+ const totalPrereqMinutes = Array.from(prereqMinutesByConcept.values()).reduce((a, b) => a + b, 0);
1984
+ return {
1985
+ hybridGraph: {
1986
+ schema_version: 1,
1987
+ type: "hybrid_graph",
1988
+ project_graph: projectGraph,
1989
+ knowledge_graph: knowledgeGraph,
1990
+ links: validLinks,
1991
+ phases,
1992
+ description: "Progressive completion path: " + phases.length + " phases, " + features.length + " features, " + concepts.length + " concepts",
1993
+ total_project_minutes: totalProjectMinutes,
1994
+ total_concept_minutes: totalConceptMinutes,
1995
+ estimated_total_minutes: totalProjectMinutes + totalPrereqMinutes
1996
+ },
1997
+ warnings
1998
+ };
1999
+ }
2000
+ function auditPhasePlan(plan, features, concepts, links, warnings, log) {
2001
+ const knownFeatureIds = new Set(features.map((f) => f.id));
2002
+ const knownConceptIds = new Set(concepts.map((c) => c.id));
2003
+ const prereqOf = /* @__PURE__ */ new Map();
2004
+ for (const c of concepts) prereqOf.set(c.id, (c.prerequisites || []).filter((p) => knownConceptIds.has(p)));
2005
+ const phases = [];
2006
+ const featurePhase = /* @__PURE__ */ new Map();
2007
+ const newIntroPhase = /* @__PURE__ */ new Map();
2008
+ const errors = [];
2009
+ plan.forEach((rp, idx) => {
2010
+ const id = String(rp.id || "PH" + (idx + 1));
2011
+ const order = idx + 1;
2012
+ const name = String(rp.name || "Phase " + order).slice(0, 80);
2013
+ const productCompletion = String(rp.product_completion || "").trim();
2014
+ const rawFeatureIds = Array.isArray(rp.feature_ids) ? rp.feature_ids.map(String) : [];
2015
+ const rawIntros = Array.isArray(rp.introduces) ? rp.introduces : [];
2016
+ if (!productCompletion) {
2017
+ errors.push("Phase " + id + ": product_completion is empty - every phase must describe the product completion level");
2018
+ }
2019
+ const featureIdsForPhase = [];
2020
+ for (const fid of rawFeatureIds) {
2021
+ if (!knownFeatureIds.has(fid)) {
2022
+ errors.push("Phase " + id + ": unknown feature " + fid);
2023
+ continue;
2024
+ }
2025
+ if (featurePhase.has(fid)) {
2026
+ errors.push("Feature " + fid + " assigned to both " + featurePhase.get(fid) + " and " + id + " - each feature must belong to exactly one phase");
2027
+ continue;
2028
+ }
2029
+ featurePhase.set(fid, id);
2030
+ featureIdsForPhase.push(fid);
2031
+ }
2032
+ const introductions = [];
2033
+ for (const ri of rawIntros) {
2034
+ const cid = String(ri.concept_id || "");
2035
+ if (!knownConceptIds.has(cid)) {
2036
+ errors.push("Phase " + id + ": introduces unknown concept " + cid);
2037
+ continue;
2038
+ }
2039
+ const aspect = String(ri.aspect || "new") === "advanced" ? "advanced" : "new";
2040
+ if (aspect === "advanced") {
2041
+ const first = newIntroPhase.get(cid);
2042
+ if (first === void 0) {
2043
+ errors.push("Phase " + id + ": advanced introduction of " + cid + " before any new introduction - revisit requires prior introduction");
2044
+ continue;
2045
+ }
2046
+ if (first >= order) {
2047
+ errors.push("Phase " + id + ": advanced introduction of " + cid + " must come after its new introduction in phase " + first);
2048
+ continue;
2049
+ }
2050
+ } else if (newIntroPhase.has(cid)) {
2051
+ errors.push("Phase " + id + ": duplicate new introduction of " + cid + " (already introduced in phase " + newIntroPhase.get(cid) + ")");
2052
+ continue;
2053
+ } else {
2054
+ newIntroPhase.set(cid, order);
2055
+ }
2056
+ for (const pre of prereqOf.get(cid) || []) {
2057
+ if (!newIntroPhase.has(pre)) {
2058
+ errors.push("Phase " + id + ": concept " + cid + " introduced before its prerequisite " + pre + " is introduced - violates the prerequisite chain");
2059
+ }
2060
+ }
2061
+ introductions.push({ concept_id: cid, aspect, note: String(ri.note || "") });
2062
+ }
2063
+ phases.push({
2064
+ id,
2065
+ order,
2066
+ name,
2067
+ product_completion: productCompletion,
2068
+ feature_ids: featureIdsForPhase,
2069
+ introduces: introductions
2070
+ });
2071
+ });
2072
+ const missing = features.map((f) => f.id).filter((fid) => !featurePhase.has(fid));
2073
+ if (missing.length > 0) {
2074
+ errors.push("Features not assigned to any phase: " + missing.join(", "));
2075
+ }
2076
+ const firstConsumerPhase = /* @__PURE__ */ new Map();
2077
+ const phaseOrderByFeature = /* @__PURE__ */ new Map();
2078
+ for (const ph of phases) for (const fid of ph.feature_ids) phaseOrderByFeature.set(fid, ph.order);
2079
+ for (const l of links) {
2080
+ const po = phaseOrderByFeature.get(l.feature_id);
2081
+ if (po === void 0) continue;
2082
+ const cur = firstConsumerPhase.get(l.concept_id);
2083
+ if (cur === void 0 || po < cur) firstConsumerPhase.set(l.concept_id, po);
2084
+ }
2085
+ for (const [cid, consumerOrder] of firstConsumerPhase) {
2086
+ const intro = newIntroPhase.get(cid);
2087
+ if (intro === void 0) {
2088
+ errors.push("Concept " + cid + " is consumed from phase " + consumerOrder + " but never introduced in any phase");
2089
+ } else if (intro > consumerOrder) {
2090
+ errors.push("Concept " + cid + " introduced in phase " + intro + " but first consumed in phase " + consumerOrder + " - introduction must come no later than first consumption");
2091
+ }
2092
+ }
2093
+ return { phases, errors };
2094
+ }
2095
+ async function decomposePhases(args) {
2096
+ const { features, concepts, links, client, log, warnings } = args;
2097
+ const featureList = features.map(
2098
+ (f) => "- " + f.id + ": " + f.name + " - " + (f.description || "").slice(0, 120)
2099
+ ).join("\n");
2100
+ const conceptList = concepts.map(
2101
+ (c) => "- " + c.id + ": " + c.name + " (prerequisites: " + ((c.prerequisites || []).join(", ") || "none") + ")"
2102
+ ).join("\n");
2103
+ const linkList = links.map(
2104
+ (l) => "- " + l.feature_id + " -> " + l.concept_id + " (" + l.depth + ")"
2105
+ ).join("\n") || "(none)";
2106
+ 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.";
2107
+ 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";
2108
+ const MAX_DECOMPOSE_ATTEMPTS = 3;
2109
+ let auditErrors = [];
2110
+ let phases = [];
2111
+ let rawPhases = [];
2112
+ for (let attempt = 1; attempt <= MAX_DECOMPOSE_ATTEMPTS; attempt++) {
2113
+ 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";
2114
+ const result = await llmChatJson(client, systemPrompt, userPrompt, {
2115
+ temperature: 0.1,
2116
+ maxTokens: 16384
2117
+ });
2118
+ rawPhases = result.phases || [];
2119
+ if (rawPhases.length === 0) {
2120
+ if (attempt === MAX_DECOMPOSE_ATTEMPTS) {
2121
+ throw new Error("Phase decomposition returned zero phases - fail-closed abort");
2122
+ }
2123
+ auditErrors = ["Returned zero phases"];
2124
+ continue;
2125
+ }
2126
+ ({ phases, errors: auditErrors } = auditPhasePlan(rawPhases, features, concepts, links));
2127
+ if (auditErrors.length === 0) break;
2128
+ if (attempt < MAX_DECOMPOSE_ATTEMPTS) {
2129
+ log("STEP_2", "Contract violations (" + auditErrors.length + ") - repairing (attempt " + (attempt + 1) + "/" + MAX_DECOMPOSE_ATTEMPTS + ")");
2130
+ }
2131
+ }
2132
+ if (auditErrors.length > 0) {
2133
+ throw new Error(
2134
+ "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."
2135
+ );
2136
+ }
2137
+ if (phases.length === 1 && features.length > 2) {
2138
+ warnings.push("Only one phase for " + features.length + " features - progressive decomposition likely too coarse");
2139
+ }
2140
+ log("STEP_2", "Decomposed into " + phases.length + " phases: " + phases.map((p) => p.id + "(" + p.feature_ids.length + "F/" + p.introduces.length + "K)").join(", "));
2141
+ return phases;
2142
+ }
2143
+
2144
+ exports.CIO_CODE_RE = CIO_CODE_RE;
2145
+ exports.CONCEPT_CODE_RE = CONCEPT_CODE_RE;
2146
+ exports.LEARNER_CLAUSE = LEARNER_CLAUSE;
2147
+ exports.SIO_CODE_RE = SIO_CODE_RE;
2148
+ exports.ULO_CODE_RE = ULO_CODE_RE;
2149
+ exports.assignConceptCodes = assignConceptCodes;
2150
+ exports.auditDepthLayers = auditDepthLayers;
2151
+ exports.cioActionSlug = cioActionSlug;
2152
+ exports.cioCode = cioCode;
2153
+ exports.conceptCodeFromName = conceptCodeFromName;
2154
+ exports.escalateAndMapConcepts = escalateAndMapConcepts;
2155
+ exports.extractFeatureSteps = extractFeatureSteps;
2156
+ exports.extractFeatureStepsBatched = extractFeatureStepsBatched;
2157
+ exports.extractProjectOverview = extractProjectOverview;
2158
+ exports.extractScaffold = extractScaffold;
2159
+ exports.generateHybridGraph = generateHybridGraph;
2160
+ exports.generateKnowledgeGraph = generateKnowledgeGraph;
2161
+ exports.sioCode = sioCode;
2162
+ exports.standardStatement = standardStatement;
2163
+ exports.techTagFor = techTagFor;
2164
+ exports.uloCode = uloCode;
2165
+ exports.verifyProjectGraph = verifyProjectGraph;
2166
+ //# sourceMappingURL=index.cjs.map
2167
+ //# sourceMappingURL=index.cjs.map