@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 @@
1
+ {"version":3,"sources":["../src/utils/llmClient.ts","../src/graph/scaffoldExtractor.ts","../src/graph/overviewExtractor.ts","../src/graph/stepExtractor.ts","../src/graph/graphVerifier.ts","../src/graph/conceptEscalator.ts"],"names":["buildSourceText"],"mappings":";AAmDO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA,EACxC,WAAA,CACE,OAAA,EACgB,MAAA,EACA,KAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAHG,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,gBAAA;AAAA,EACd;AACF,CAAA;AAeO,SAAS,qBAAqB,MAAA,EAA0C;AAC7E,EAAA,MAAM,QAAwB,EAAC;AAC/B,EAAA,MAAM,IAAA,GAAO,CAAC,KAAA,EAAe,OAAA,EAAiB,QAAgB,KAAA,KAAwB;AACpF,IAAA,IAAI,MAAA,IAAU,OAAA,IAAW,KAAA,IAAS,CAAC,MAAM,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,OAAA,KAAY,OAAA,IAAW,CAAA,CAAE,KAAA,KAAU,KAAK,CAAA,EAAG;AAChG,MAAA,KAAA,CAAM,KAAK,EAAE,KAAA,EAAO,OAAA,EAAS,MAAA,EAAQ,OAAO,CAAA;AAAA,IAC9C;AAAA,EACF,CAAA;AAEA,EAAA,IAAI,QAAQ,MAAA,EAAQ;AAClB,IAAA,IAAA,CAAK,QAAA,EAAU,OAAO,OAAA,IAAW,2BAAA,EAA6B,OAAO,MAAA,EAAQ,MAAA,CAAO,SAAS,aAAa,CAAA;AAAA,EAC5G;AAEA,EAAA,IAAA,CAAK,QAAA,EAAU,QAAQ,GAAA,CAAI,YAAA,IAAgB,QAAQ,GAAA,CAAI,eAAA,IAAmB,IAAI,OAAA,CAAQ,GAAA,CAAI,eAAe,OAAA,CAAQ,GAAA,CAAI,kBAAkB,EAAA,EAAI,OAAA,CAAQ,IAAI,SAAA,IA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B,cAAA,EAAgB;AAAA,OACjB,CAAA;AAAA,IACH;AAEA,IAAA,eAAA,CAAgB,GAAA,CAAI,KAAK,KAAK,CAAA;AAAA,EAChC;AAEA,EAAA,OAAO,eAAA;AACT","file":"chunk-MOKNFLUD.mjs","sourcesContent":["/**\n * LLM client wrapper — provides a unified interface for LLM calls\n * used by the graph generation pipeline.\n *\n * Supports OpenAI-compatible APIs via environment variables:\n * LLM_API_KEY, LLM_BASE_URL, LLM_MODEL (or LLM_TIER_FAST / LLM_TIER_STRONG)\n */\n\nexport interface LlmClientConfig {\n apiKey?: string;\n baseUrl?: string;\n model?: string;\n temperature?: number;\n maxTokens?: number;\n}\n\n/** One callable provider endpoint in the fallback chain. */\nexport interface ProviderSpec {\n label: string;\n baseUrl: string;\n apiKey: string;\n model: string;\n}\n\nexport interface LlmClient {\n chat(messages: LlmChatMessage[], options?: { temperature?: number; maxTokens?: number }): Promise<LlmChatResult>;\n model: string;\n}\n\nexport interface LlmChatMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n}\n\nexport interface LlmChatResult {\n content: string;\n model: string;\n /** Provider label that ultimately served the request. */\n provider?: string;\n /** What happened per provider when fallback occurred (empty when first try succeeded). */\n attempts?: string[];\n /** 'stop' when complete; 'length' means the response was TRUNCATED by max_tokens. */\n finishReason?: string;\n usage?: {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n finishReason?: string;\n};\n}\n\nexport class LlmClientError extends Error {\n constructor(\n message: string,\n public readonly status?: number,\n public readonly cause?: Error,\n ) {\n super(message);\n this.name = 'LlmClientError';\n }\n}\n\n/**\n * Create an LLM client from environment variables.\n */\n/**\n * Resolve the provider fallback chain from explicit config and environment.\n * Base order: explicit config > legacy LLM_API_KEY/OPENAI_API_KEY > NVIDIA NIM >\n * OpenRouter > DashScope/Alibaba MaaS. First entry is PRIMARY; the rest are\n * fallbacks tried in order.\n *\n * QUALITY-EVAL MODE: when OPENROUTER_MODEL is set (a paid preset), OpenRouter\n * is promoted to PRIMARY so generation quality is evaluated without free-tier\n * 429/403 noise. NVIDIA/dashscope then act only as safety-net fallbacks.\n */\nexport function resolveProviderChain(config?: LlmClientConfig): ProviderSpec[] {\n const chain: ProviderSpec[] = [];\n const push = (label: string, baseUrl: string, apiKey: string, model: string): void => {\n if (apiKey && baseUrl && model && !chain.some((c) => c.baseUrl === baseUrl && c.model === model)) {\n chain.push({ label, baseUrl, apiKey, model });\n }\n };\n // Explicit single-provider config keeps its historical meaning.\n if (config?.apiKey) {\n push('config', config.baseUrl || 'https://api.openai.com/v1', config.apiKey, config.model || 'gpt-4o-mini');\n }\n // Legacy generic env (knowledge-tree compatible: OPENAI_BASE_URL + LLM_MODEL).\n 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 || '');\n // DashScope / Alibaba MaaS (OpenAI-compatible endpoints).\n 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 || '');\n // NVIDIA NIM — hosted provider for generation workloads.\n push('nvidia', 'https://integrate.api.nvidia.com/v1', process.env.NVIDIA_API_KEY || '', process.env.NVIDIA_MODEL || 'nvidia/nemotron-3-ultra-550b-a55b');\n // OpenRouter — paid preset primary when OPENROUTER_MODEL pins a model/preset.\n push('openrouter', 'https://openrouter.ai/api/v1', process.env.OPENROUTER_API_KEY || '', process.env.OPENROUTER_MODEL || 'nvidia/nemotron-3-ultra-550b-a55b');\n // QUALITY-EVAL MODE: paid OpenRouter preset goes FIRST (no 429 noise).\n if (process.env.OPENROUTER_MODEL) {\n const or = chain.find((c) => c.label === 'openrouter');\n if (or) {\n const rest = chain.filter((c) => c !== or);\n return [or, ...rest];\n }\n }\n return chain;\n}\n\n// Free-tier rate limits (NVIDIA NIM, OpenRouter) trip when a pipeline fires\n// many requests in a burst. Global pacing keeps us under the limit; a single\n// isolated call still goes through immediately.\nconst MIN_REQUEST_INTERVAL_MS = 2_500;\nlet lastRequestAt = 0;\n\nasync function pacedDelay(): Promise<void> {\n const wait = lastRequestAt + MIN_REQUEST_INTERVAL_MS - Date.now();\n if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));\n lastRequestAt = Date.now();\n}\n\nexport function createLlmClient(config?: LlmClientConfig): LlmClient {\n const chain = resolveProviderChain(config);\n const primary = chain[0];\n if (!primary) {\n throw new LlmClientError(\n 'No LLM provider configured. Set NVIDIA_API_KEY (primary) and/or OPENROUTER_API_KEY (fallback), or pass llmConfig.',\n );\n }\n const apiKey = primary.apiKey;\n const baseUrl = primary.baseUrl;\n const model = primary.model;\n\n async function chat(\n messages: LlmChatMessage[],\n options?: { temperature?: number; maxTokens?: number },\n ): Promise<LlmChatResult> {\n const temperature = options?.temperature ?? config?.temperature ?? 0.1;\n const maxTokens = options?.maxTokens ?? config?.maxTokens ?? parseInt(process.env.LLM_MAX_TOKENS || '65536', 10);\n\n const attempts: string[] = [];\n let lastError: LlmClientError | null = null;\n const TRANSIENT = new Set([408, 429, 500, 502, 503, 504]);\n // Hard per-request cap so a hanging provider degrades to a transient error\n // and the chain falls through instead of blocking the pipeline forever.\n // Reasoning presets (e.g. deepseek-v4-flash) can legitimately think for\n // minutes on large structured outputs — 5 minutes default, env-overridable.\n const REQUEST_TIMEOUT_MS = Number(process.env.LLM_REQUEST_TIMEOUT_MS || 300_000);\n const MAX_CHAIN_ROUNDS = 3;\n for (let round = 1; round <= MAX_CHAIN_ROUNDS; round++) {\n if (round > 1) {\n // Whole chain failed transiently (rate limits / upstream 5xx) — back\n // off and rewalk the chain from the primary instead of dying.\n attempts.push('round ' + (round - 1) + ' failed — backing off 20s before rewalking the chain');\n await new Promise((resolve) => setTimeout(resolve, 20_000));\n }\n for (const provider of chain) {\n try {\n const headers = {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${provider.apiKey}`,\n };\n const payload = {\n model: provider.model,\n messages,\n temperature,\n max_tokens: maxTokens,\n };\n await pacedDelay();\n const doFetch = (): Promise<Response> => fetch(`${provider.baseUrl}/chat/completions`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${provider.apiKey}`,\n },\n body: JSON.stringify({\n model: provider.model,\n messages,\n temperature,\n max_tokens: maxTokens,\n }),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n // Transient network failures (DNS blip, TLS reset, \"fetch failed\") get\n // one same-provider retry before falling through the chain.\n let response: Response;\n try {\n response = await doFetch();\n } catch (netErr) {\n attempts.push(`${provider.label}: network error (${netErr instanceof Error ? netErr.message : String(netErr)}) — retrying once`);\n await new Promise((r) => setTimeout(r, 5_000));\n lastRequestAt = Date.now();\n response = await doFetch();\n }\n if (!response.ok) {\n const body = await response.text().catch(() => '');\n const err = new LlmClientError(\n `[${provider.label}] LLM API error: ${response.status} ${response.statusText} — ${body.slice(0, 200)}`,\n response.status,\n );\n if (response.status === 429) {\n // Rate-limited: honor Retry-After (bounded) and retry once on the\n // same provider before falling through to the next one.\n const retryAfterRaw = response.headers.get('retry-after');\n const retryAfterMs = Math.min(\n 60_000,\n Math.max(15_000, (Number.isFinite(Number(retryAfterRaw)) ? Number(retryAfterRaw) : 20) * 1_000),\n );\n attempts.push(`${provider.label}: 429 rate-limited — backing off ${Math.round(retryAfterMs / 1000)}s`);\n await new Promise((resolve) => setTimeout(resolve, retryAfterMs));\n lastRequestAt = Date.now();\n const retry = await fetch(`${provider.baseUrl}/chat/completions`, {\n method: 'POST',\n headers,\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n if (!retry.ok) throw err;\n const retryData = await retry.json() as {\n choices?: Array<{ message?: { content?: string }; finish_reason?: string }>;\n model?: string;\n usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number };\n };\n const retryContent2 = retryData.choices?.[0]?.message?.content || '';\n if (!retryContent2.trim()) throw err;\n return {\n content: retryContent2,\n model: retryData.model || provider.model,\n provider: provider.label,\n attempts: attempts.slice(),\n usage: retryData.usage,\n finishReason: retryData.choices?.[0]?.finish_reason,\n };\n }\n if (TRANSIENT.has(response.status)) {\n await new Promise((r) => setTimeout(r, 3000));\n const retry = await fetch(`${provider.baseUrl}/chat/completions`, {\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${provider.apiKey}`,\n },\n body: JSON.stringify({\n model: provider.model,\n messages,\n temperature,\n max_tokens: maxTokens,\n }),\n });\n if (!retry.ok) throw err; // still transient-failing — fall through to next provider\n const retryData = await retry.json() as {\n choices?: Array<{ message?: { content?: string }; finish_reason?: string }>;\n model?: string;\n usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number };\n };\n const retryContent = retryData.choices?.[0]?.message?.content || '';\n return {\n content: retryContent,\n model: retryData.model || provider.model,\n provider: provider.label,\n attempts: attempts.slice(),\n usage: retryData.usage,\n finishReason: retryData.choices?.[0]?.finish_reason,\n };\n }\n throw err;\n }\n const data = await response.json() as {\n choices?: Array<{ message?: { content?: string }; finish_reason?: string }>;\n model?: string;\n usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number };\n };\n const wrappedError = (data as { error?: { message?: string; code?: number } }).error;\n if (wrappedError) {\n // OpenRouter proxies some upstream failures as HTTP 200 with an\n // {\"error\": {...}} body — treat as transient and fall through.\n throw new LlmClientError('[' + provider.label + '] upstream error ' + (wrappedError.code ?? '') + ': ' + (wrappedError.message ?? 'unknown'));\n }\n const content = data.choices?.[0]?.message?.content || '';\n if (!content.trim()) {\n // Empty completion (provider outage / content filter) is transient —\n // fall through to the next provider instead of returning unusable ''.\n throw new LlmClientError('[' + provider.label + '] empty completion returned');\n }\n return {\n content,\n model: data.model || provider.model,\n provider: provider.label,\n attempts: attempts.slice(),\n usage: data.usage,\n finishReason: data.choices?.[0]?.finish_reason,\n };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n attempts.push(`${provider.label}: ${msg}`);\n lastError = err instanceof LlmClientError ? err : new LlmClientError(`[${provider.label}] ${msg}`);\n // try next provider\n }\n }\n if (round < MAX_CHAIN_ROUNDS) continue; // rewalk the chain\n throw lastError ?? new LlmClientError('All LLM providers failed (empty chain).');\n }\n throw lastError ?? new LlmClientError('All LLM providers failed after ' + MAX_CHAIN_ROUNDS + ' rounds.');\n }\n\n return { chat, model };\n}\n\n/**\n * Parse JSON from LLM response, handling markdown code fences.\n */\nexport function parseJsonFromLlm(text: string): Record<string, unknown> {\n // Strip markdown code fences if present\n let cleaned = text.trim();\n if (cleaned.startsWith('```json')) {\n cleaned = cleaned.slice(7);\n } else if (cleaned.startsWith('```')) {\n cleaned = cleaned.slice(3);\n }\n if (cleaned.endsWith('```')) {\n cleaned = cleaned.slice(0, -3);\n }\n cleaned = cleaned.trim();\n\n try {\n return JSON.parse(cleaned) as Record<string, unknown>;\n } catch {\n // Try to find first complete JSON object using brace-depth tracking\n const start = cleaned.indexOf('{');\n if (start >= 0) {\n let depth = 0;\n let inString = false;\n let escape = false;\n for (let i = start; i < cleaned.length; i++) {\n const ch = cleaned[i];\n if (escape) { escape = false; continue; }\n if (ch === '\\\\') { escape = true; continue; }\n if (ch === '\"') { inString = !inString; continue; }\n if (inString) continue;\n if (ch === '{') depth++;\n if (ch === '}') {\n depth--;\n if (depth === 0) {\n try {\n return JSON.parse(cleaned.slice(start, i + 1)) as Record<string, unknown>;\n } catch {\n // keep looking\n }\n }\n }\n }\n }\n throw new LlmClientError(`Failed to parse JSON from LLM response: ${cleaned.slice(0, 200)}`);\n }\n}\n\n/**\n * Call LLM and parse JSON response.\n */\nexport async function llmChatJson(\n client: ReturnType<typeof createLlmClient>,\n systemPrompt: string,\n userPrompt: string,\n options?: { temperature?: number; maxTokens?: number },\n): Promise<Record<string, unknown>> {\n const result = await client.chat(\n [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: userPrompt },\n ],\n options,\n );\n\n return parseJsonFromLlm(result.content);\n}\n","/**\n * STEP C0: Extract FOUNDATION & SETUP feature (F0) via LLM.\n *\n * Ported from knowledge-tree/llm_project_graph.py extract_scaffold_llm()\n * The F0 feature covers MUST-KNOW steps before the first feature:\n * tools, project creation, minimal programming knowledge, repo map, dev loop.\n */\n\nimport { createLlmClient, llmChatJson, type LlmClientConfig } from '../utils/llmClient';\nimport type { Feature } from '../schemas/projectGraphSchema';\n\nexport interface ExtractScaffoldOptions {\n goal: string;\n techStack: string;\n fileList: string[];\n llmConfig?: LlmClientConfig;\n}\n\n/**\n * Extract the FOUNDATION & SETUP feature (F0) via LLM.\n * Returns a Feature with steps covering tool setup, project creation,\n * minimal programming knowledge, repo map, and dev loop.\n */\nexport async function extractScaffold(options: ExtractScaffoldOptions): Promise<Feature | null> {\n const { goal, techStack, fileList, llmConfig } = options;\n const client = createLlmClient(llmConfig);\n const fileListStr = fileList.length > 0 ? fileList.join('\\n') : '(empty)';\n\n const systemPrompt = (\n 'You are a programming pedagogy expert. For ONE concrete project, extract the '\n + \"'FOUNDATION & SETUP' feature (id F0) — the COMPLETE set of 'MUST-KNOW' steps \"\n + 'the learner needs before studying the first feature. Break it into concrete ACTION '\n + 'steps (5-8 steps), each with completion_level=\\'base\\'. Include:\\n'\n + '1. Tools required for this tech stack (IDE, simulator/emulator, terminal, git, '\n + 'package manager) + basic operations (open project, build, run, debug, commit).\\n'\n + '2. Create the initial project: from a template OR clone/open the base-project (the provided repo).\\n'\n + '3. MINIMAL programming knowledge of the language (variables, types, functions, if/for, view declaration) '\n + '+ build one small demo (e.g. a single-screen Hello World app) BEFORE touching the real project.\\n'\n + '4. Repo map of the actual project: folder structure, entry point, how to build/run, main architecture '\n + '(MVVM/Flux...), important packages/modules.\\n'\n + '5. Development loop (build->run->see result->debug), how to read/fix basic compile errors, '\n + 'minimal git workflow (clone/branch/commit/push).\\n'\n + 'keywords[]: real tool/language terms (e.g. \\'Xcode\\', \\'Simulator\\', \\'Git\\', \\'Swift\\', '\n + '\\'@main\\', \\'MVVM\\'). files[]: leave [] or use real paths if the step touches specific files. '\n + 'description: ONE concise sentence, MAX 140 characters. '\n + 'intent: WHY this step matters. outcome: {user_visible: string, technical: string}. '\n + 'acceptance[]: 2 verifiable criteria. effort: {estimated_minutes: number, complexity: low|medium|high}. '\n + 'NEVER invent. ALL text must be in ENGLISH (technical terms stay as-is). '\n + 'Return JSON containing only feature F0.'\n );\n\n const userPrompt = (\n `App goal: ${goal}\\n`\n + `Tech stack: ${techStack}\\n\\n`\n + 'PROJECT FILE LIST (base-project):\\n'\n + `${fileListStr}\\n\\n`\n + 'Return JSON:\\n'\n + '{\\n'\n + ' \"feature\": {\\n'\n + ' \"id\": \"F0\",\\n'\n + ' \"name\": \"FOUNDATION & SETUP\",\\n'\n + ' \"description\": \"Get familiar with the tools, create/clone the project, learn minimal knowledge and the repo map\",\\n'\n + ' \"platform\": \"app\",\\n'\n + ' \"steps\": [\\n'\n + ' {\\n'\n + ' \"id\": \"F0-S1\",\\n'\n + ' \"sequence\": 1,\\n'\n + ' \"name\": \"Action step name\",\\n'\n + ' \"description\": \"Detailed description of the concrete actions\",\\n'\n + ' \"files\": [],\\n'\n + ' \"api_usage\": [],\\n'\n + ' \"keywords\": [\"Xcode\", \"Terminal\"],\\n'\n + ' \"completion_level\": \"base\",\\n'\n + ' \"intent\": \"Learn how to setup the IDE and run a minimal Swift app\",\\n'\n + ' \"outcome\": {\"user_visible\": \"App builds and runs\", \"technical\": \"Toolchain verified\"},\\n'\n + ' \"acceptance\": [\"Xcode builds without errors\", \"Simulator launches successfully\"],\\n'\n + ' \"effort\": {\"estimated_minutes\": 20, \"complexity\": \"low\"}\\n'\n + ' }\\n'\n + ' ]\\n'\n + ' }\\n'\n + '}\\n'\n );\n\n try {\n const result = await llmChatJson(client, systemPrompt, userPrompt, {\n temperature: 0.1,\n maxTokens: parseInt(process.env.PG_C0_MAX_TOKENS || '16384', 10),\n });\n\n const feat = result.feature as Record<string, unknown> | undefined;\n if (!feat || !Array.isArray(feat.steps) || feat.steps.length === 0) {\n console.warn('[WARN] Scaffold LLM returned no steps — skipping F0');\n return null;\n }\n\n // Normalize step IDs and ensure required fields\n const steps = (feat.steps as Record<string, unknown>[]).map((s, i) => ({\n id: `F0-S${i + 1}`,\n sequence: i + 1,\n name: String(s.name || `Step ${i + 1}`),\n description: String(s.description || ''),\n files: Array.isArray(s.files) ? s.files : [],\n api_usage: Array.isArray(s.api_usage) ? s.api_usage : [],\n keywords: Array.isArray(s.keywords) ? s.keywords : [],\n completion_level: 'base' as const,\n platform: String(s.platform || 'app'),\n intent: String(s.intent || ''),\n outcome: s.outcome && typeof s.outcome === 'object' ? s.outcome as { user_visible?: string; technical?: string } : undefined,\n acceptance: Array.isArray(s.acceptance) ? s.acceptance : [],\n effort: s.effort && typeof s.effort === 'object' ? s.effort as { estimated_minutes?: number; complexity?: 'low' | 'medium' | 'high' } : undefined,\n requirement_ids: [] as string[],\n concept_codes: [] as string[],\n }));\n\n return {\n id: 'F0',\n name: String(feat.name || 'FOUNDATION & SETUP'),\n description: String(feat.description || ''),\n platform: String(feat.platform || 'app'),\n steps,\n } as Feature;\n } catch (err) {\n console.error(`[ERROR] extractScaffold failed: ${err}`);\n return null;\n }\n}\n","/**\n * STEP C1: Extract PROJECT OVERVIEW via LLM (features meta — NO steps).\n *\n * Ported from knowledge-tree/llm_project_graph.py extract_project_overview_llm()\n * Output: project, product, features[], user_journeys, architecture, decomposition.\n */\n\nimport { createLlmClient, llmChatJson, type LlmClientConfig } from '../utils/llmClient';\nimport type { Keyword } from '../extractors/keywordExtractor';\n\nexport interface ExtractOverviewOptions {\n goal: string;\n techStack: string;\n sdkApiIndex: { sdk_apis: Array<{ name: string; kind: string; used_in_demo: boolean }> };\n fileContentsMap: Map<string, string>;\n astKeywords?: Keyword[];\n llmConfig?: LlmClientConfig;\n}\n\nfunction buildSourceText(fileContentsMap: Map<string, string>): string {\n const blocks: string[] = [];\n for (const [relPath, content] of fileContentsMap) {\n blocks.push(`### FILE: ${relPath}\\n${content}`);\n }\n return blocks.join('\\n\\n');\n}\n\n/**\n * Extract project overview (features meta) via LLM.\n * Does NOT include steps — those are extracted per-feature in STEP C2.\n */\nexport async function extractProjectOverview(options: ExtractOverviewOptions): Promise<Record<string, unknown>> {\n const { goal, techStack, sdkApiIndex, fileContentsMap, astKeywords, llmConfig } = options;\n const client = createLlmClient(llmConfig);\n\n const usedSdkApis = sdkApiIndex.sdk_apis\n .filter(api => api.used_in_demo)\n .map(api => api.name)\n .slice(0, 2000);\n\n const allFilesStr = buildSourceText(fileContentsMap);\n\n // Build AST keywords anchor\n let keywordsAnchor = '';\n if (astKeywords && astKeywords.length > 0) {\n const kwItems = astKeywords.slice(0, 30).map(kw =>\n `- ${kw.keyword} (from ${kw.source})`,\n );\n if (kwItems.length > 0) {\n keywordsAnchor = (\n '\\nAST Domain Keywords & Patterns (from static analysis — use as context anchor):\\n'\n + kwItems.join('\\n')\n + '\\n'\n );\n }\n }\n\n const systemPrompt = (\n 'You are a software architect. The app the user will build IS EXACTLY the provided files '\n + '(not an SDK/lib). Analyze them and return a PROJECT OVERVIEW — meta only, '\n + 'DO NOT list steps (steps are handled in a later step). '\n + 'NEVER invent files/APIs. NEVER reference internal SDK/lib unless it appears in the given files.\\n'\n + 'END-USER VIEW (M1/Design Thinking): product.purpose must describe the USER PROBLEM '\n + '(what the user does with the app, which need it solves). NEVER describe repo/artifacts.\\n'\n + 'DEVELOPMENT STAGES: Include 4-6 development stages in product.development_stages. '\n + 'Each stage must have: stage (name), need (list of feature needs), learn (concepts learned), '\n + 'product_state (what works), temporary_approach, and validation.\\n'\n + 'MISSING GAPS: Identify 0-5 missing_gaps (features/functionality that should exist but don\\'t).\\n'\n + 'TECH DEBT: Identify 0-5 tech_debt issues (code quality problems).\\n'\n + 'ALL text must be in ENGLISH.'\n );\n\n const userPrompt = `App goal: ${goal}\nTech stack: ${techStack}\n${keywordsAnchor}\nFiltered SDK API list (used_in_demo):\n${JSON.stringify(usedSdkApis, null, 0)}\n\nSource code of the files:\n${allFilesStr}\n\nReturn JSON per the schema:\n{\n \"schema_version\": 2,\n \"project\": {\"name\": \"...\", \"project_type\": \"app\", \"platforms\": [\"ios\"]},\n \"product\": {\n \"purpose\": \"END-USER problem being solved\",\n \"problem_statement\": \"Core user problem\",\n \"primary_users\": [\"who the main users are\"],\n \"development_stages\": [\n {\n \"stage\": \"Stage 1: Foundation & Setup\",\n \"need\": [\"Core app shell\"],\n \"learn\": [\"App lifecycle, basic UI\"],\n \"product_state\": \"App launches with static mock data\",\n \"temporary_approach\": \"Hardcoded array\",\n \"validation\": \"Main screen loads\"\n }\n ],\n \"features\": [\n {\"id\": \"F1\", \"name\": \"Feature name\", \"description\": \"Feature description\", \"platform\": \"ios\"}\n ],\n \"user_journeys\": [{\"name\": \"...\", \"feature_ids\": [\"F1\"]}]\n },\n \"architecture\": {\"layers\": [], \"services\": [], \"state_management\": \"...\"},\n \"decomposition\": {\"milestones\": [{\"id\": \"M1\", \"phase\": \"MVP\", \"name\": \"...\", \"goal\": \"...\", \"feature_ids\": [\"F1\"]}]}\n}`;\n\n const result = await llmChatJson(client, systemPrompt, userPrompt, {\n temperature: 0.1,\n maxTokens: parseInt(process.env.PG_C1_MAX_TOKENS || '32768', 10),\n });\n\n // Ensure development_stages exists\n const prod = result.product as Record<string, unknown> | undefined;\n if (prod && !Array.isArray(prod.development_stages)) {\n prod.development_stages = [];\n }\n\n return result;\n}\n","/**\n * STEP C2: Extract feature STEPS via LLM.\n *\n * Ported from knowledge-tree/llm_project_graph.py\n * - extract_feature_steps_llm() — single feature\n * - extract_feature_steps_batched() — batch of features\n */\n\nimport { createLlmClient, llmChatJson, type LlmClientConfig } from '../utils/llmClient';\nimport type { Feature, Step } from '../schemas/projectGraphSchema';\n\nexport interface ExtractStepsOptions {\n goal: string;\n techStack: string;\n sdkApiIndex: { sdk_apis: Array<{ name: string; kind: string; used_in_demo: boolean }> };\n fileContentsMap: Map<string, string>;\n feature: Feature;\n llmConfig?: LlmClientConfig;\n}\n\nfunction buildSourceText(fileContentsMap: Map<string, string>): string {\n const blocks: string[] = [];\n for (const [relPath, content] of fileContentsMap) {\n blocks.push(`### FILE: ${relPath}\\n${content}`);\n }\n return blocks.join('\\n\\n');\n}\n\n/**\n * Extract steps for a SINGLE feature via LLM.\n */\nexport async function extractFeatureSteps(options: ExtractStepsOptions): Promise<Step[]> {\n const { goal, techStack, sdkApiIndex, fileContentsMap, feature, llmConfig } = options;\n const client = createLlmClient(llmConfig);\n\n const usedSdkApis = sdkApiIndex.sdk_apis\n .filter(api => api.used_in_demo)\n .map(api => api.name)\n .slice(0, 2000);\n\n const allFilesStr = buildSourceText(fileContentsMap);\n const fid = feature.id || 'F_UNK';\n const fname = feature.name || fid;\n const fdesc = feature.description || '';\n\n const systemPrompt = (\n 'You are a software architect. Split ONE feature into ACTION steps '\n + '(implementation steps) the learner must code sequentially. Each step must carry '\n + 'files[] (CORRECT paths in the source), api_usage[] (only from the provided SDK API index), '\n + 'keywords[] (real terms/language features in the files), '\n + 'and completion_level ∈ {base, mvp, extend, polish}.\\n'\n + ' - base = foundation/setup\\n'\n + ' - mvp = make the app minimally WORKING for this feature\\n'\n + ' - extend = make it real/richer\\n'\n + ' - polish = robustness (error handling, tests, validation)\\n'\n + 'Include metadata: intent, outcome ({user_visible, technical}), '\n + 'acceptance[] (2 verifiable criteria), effort ({estimated_minutes, complexity}).\\n'\n + 'description: ONE concise sentence, MAX 140 characters. '\n + 'NEVER invent files/APIs. Return ONLY the steps array. '\n + 'ALL text must be in ENGLISH.'\n );\n\n const userPrompt = `App goal: ${goal}\nTech stack: ${techStack}\n\nFEATURE TO SPLIT: ${fid} — ${fname}\nFeature description: ${fdesc}\n\nSDK API list (used_in_demo):\n${JSON.stringify(usedSdkApis)}\n\nSource code:\n${allFilesStr}\n\nSplit this feature into 2-6 action steps. Return JSON:\n{\n \"steps\": [\n {\n \"id\": \"${fid}-S1\",\n \"sequence\": 1,\n \"name\": \"Action step name\",\n \"description\": \"One concise sentence (max 140 chars)\",\n \"files\": [\"path/to/file.swift\"],\n \"api_usage\": [\"ChatClient\"],\n \"keywords\": [\"@State\", \"NavigationStack\"],\n \"completion_level\": \"mvp\",\n \"intent\": \"Create reactive state container\",\n \"outcome\": {\"user_visible\": \"Chat view updates\", \"technical\": \"ChatViewModel conforms to ObservableObject\"},\n \"acceptance\": [\"ViewModel publishes messages\", \"UI re-renders on state mutation\"],\n \"effort\": {\"estimated_minutes\": 30, \"complexity\": \"medium\"}\n }\n ]\n}`;\n\n const result = await llmChatJson(client, systemPrompt, userPrompt, {\n temperature: 0.1,\n maxTokens: parseInt(process.env.PG_C2_MAX_TOKENS || '32768', 10),\n });\n\n const rawSteps = (result.steps || []) as Record<string, unknown>[];\n // Clamp to 2-6 steps per prompt contract\n const clampedSteps = rawSteps.length > 6 ? rawSteps.slice(0, 6) : rawSteps.length < 2 && rawSteps.length > 0 ? rawSteps : rawSteps;\n if (rawSteps.length > 6) {\n console.warn(`[WARN] LLM returned ${rawSteps.length} steps for ${fid}, clamped to 6`);\n } else if (rawSteps.length === 0) {\n console.warn(`[WARN] LLM returned 0 steps for ${fid}`);\n }\n return clampedSteps.map((s, i) => ({\n id: `${fid}-S${i + 1}`,\n sequence: i + 1,\n name: String(s.name || `Step ${i + 1}`),\n description: String(s.description || ''),\n files: Array.isArray(s.files) ? s.files as string[] : [],\n api_usage: Array.isArray(s.api_usage) ? s.api_usage as string[] : [],\n keywords: Array.isArray(s.keywords) ? s.keywords as string[] : [],\n completion_level: (String(s.completion_level || 'mvp') as 'base' | 'mvp' | 'extend' | 'polish'),\n platform: String(s.platform || feature.platform || 'app'),\n intent: String(s.intent || ''),\n outcome: s.outcome as Step['outcome'],\n acceptance: Array.isArray(s.acceptance) ? s.acceptance as string[] : [],\n effort: s.effort as Step['effort'],\n requirement_ids: [],\n concept_codes: [],\n }));\n}\n\n/**\n * Extract steps for MULTIPLE features in a single LLM call.\n */\nexport async function extractFeatureStepsBatched(\n goal: string,\n techStack: string,\n sdkApiIndex: { sdk_apis: Array<{ name: string; kind: string; used_in_demo: boolean }> },\n fileContentsMap: Map<string, string>,\n featuresMeta: Feature[],\n llmConfig?: LlmClientConfig,\n): Promise<Map<string, Step[]>> {\n const client = createLlmClient(llmConfig);\n\n const usedSdkApis = sdkApiIndex.sdk_apis\n .filter(api => api.used_in_demo)\n .map(api => api.name)\n .slice(0, 2000);\n\n const sourceText = buildSourceText(fileContentsMap);\n\n const featuresListing = featuresMeta.map(f =>\n `- ${f.id || 'F?'}: ${f.name || ''} — ${f.description || ''}`,\n ).join('\\n');\n\n const systemPrompt = (\n 'You are a software architect. Split MULTIPLE features into ACTION steps. '\n + 'Each step must carry files[], api_usage[], keywords[], and '\n + 'completion_level ∈ {base, mvp, extend, polish}. '\n + 'Include metadata: intent, outcome ({user_visible, technical}), '\n + 'acceptance[] (2 verifiable criteria), effort ({estimated_minutes, complexity}). '\n + 'description: ONE concise sentence, MAX 140 characters. '\n + 'NEVER invent files/APIs. Return ONLY the JSON. '\n + 'ALL text must be in ENGLISH.'\n );\n\n const userPrompt = `App goal: ${goal}\nTech stack: ${techStack}\n\nSDK API list (used_in_demo):\n${JSON.stringify(usedSdkApis)}\n\nSource code:\n${sourceText}\n\nFEATURES to split into steps:\n${featuresListing}\n\nFor EACH feature above, produce 4-6 action steps. Each step must include:\nid, sequence, name, description, files, api_usage, keywords, completion_level, platform,\nintent, outcome ({user_visible, technical}), acceptance[] (2 criteria), effort ({estimated_minutes, complexity}).\n\nReturn JSON with a \"steps\" dict keyed by feature_id:\n{\n \"steps\": {\n \"<feature_id>\": [\n {\n \"id\": \"<feature_id>-S1\",\n \"sequence\": 1,\n \"name\": \"Step name\",\n \"description\": \"Concise sentence (max 140 chars)\",\n \"files\": [\"path/to/file\"],\n \"api_usage\": [\"APIName\"],\n \"keywords\": [\"keyword\"],\n \"completion_level\": \"mvp\",\n \"platform\": \"app\",\n \"intent\": \"Step intent\",\n \"outcome\": {\"user_visible\": \"User visible result\", \"technical\": \"Technical result\"},\n \"acceptance\": [\"Criterion 1\", \"Criterion 2\"],\n \"effort\": {\"estimated_minutes\": 30, \"complexity\": \"medium\"}\n }\n ]\n }\n}`;\n\n const result = await llmChatJson(client, systemPrompt, userPrompt, {\n temperature: 0.1,\n maxTokens: parseInt(process.env.PG_C2_MAX_TOKENS || '32768', 10),\n });\n\n const stepsDict = result.steps as Record<string, Record<string, unknown>[]> | undefined;\n const output = new Map<string, Step[]>();\n\n if (stepsDict && typeof stepsDict === 'object') {\n for (const [fid, rawSteps] of Object.entries(stepsDict)) {\n if (!Array.isArray(rawSteps)) continue;\n const featMeta = featuresMeta.find(f => f.id === fid);\n const steps = rawSteps.map((s, i) => ({\n id: `${fid}-S${i + 1}`,\n sequence: i + 1,\n name: String(s.name || `Step ${i + 1}`),\n description: String(s.description || ''),\n files: Array.isArray(s.files) ? s.files as string[] : [],\n api_usage: Array.isArray(s.api_usage) ? s.api_usage as string[] : [],\n keywords: Array.isArray(s.keywords) ? s.keywords as string[] : [],\n completion_level: (String(s.completion_level || 'mvp') as 'base' | 'mvp' | 'extend' | 'polish'),\n platform: String(s.platform || featMeta?.platform || 'app'),\n intent: String(s.intent || ''),\n outcome: s.outcome as Step['outcome'],\n acceptance: Array.isArray(s.acceptance) ? s.acceptance as string[] : [],\n effort: s.effort as Step['effort'],\n requirement_ids: [],\n concept_codes: [],\n }));\n output.set(fid, steps);\n }\n }\n\n return output;\n}\n","/**\n * STEP D: Ground-truth verification of project graph against code and SDK API index.\n *\n * Ported from knowledge-tree/llm_project_graph.py verify_project_graph()\n * Removes invalid files, APIs, keywords and logs hallucinations.\n */\n\nimport type { ProjectGraph, Feature, Step } from '../schemas/projectGraphSchema';\n\nexport interface Hallucination {\n type: string;\n item: string;\n feature_id: string;\n step_id: string;\n reason: string;\n}\n\nexport interface VerifyOptions {\n repoDir: string;\n sdkApiIndex: { sdk_apis: Array<{ name: string; kind: string; used_in_demo: boolean }> };\n fileContentsMap: Map<string, string>;\n}\n\n/**\n * Verify project graph against actual code. Remove hallucinated files, APIs, keywords.\n * F0 (foundation) keywords are kept as-is since they are pedagogical terms.\n */\nexport function verifyProjectGraph(\n projectGraph: ProjectGraph,\n options: VerifyOptions,\n): { graph: ProjectGraph; hallucinations: Hallucination[] } {\n const { sdkApiIndex, fileContentsMap } = options;\n const sdkApiNames = new Set(sdkApiIndex.sdk_apis.map(api => api.name));\n const hallucinations: Hallucination[] = [];\n\n const features = projectGraph.features || [];\n\n for (const feature of features) {\n const fid = feature.id || 'F_UNK';\n const isFoundation = fid === 'F0';\n\n for (const step of feature.steps || []) {\n const sid = step.id || `${fid}-SUNK`;\n\n // Verify files[]\n const validFiles: string[] = [];\n for (const f of step.files || []) {\n if (fileContentsMap.has(f)) {\n validFiles.push(f);\n } else {\n hallucinations.push({\n type: 'file',\n item: f,\n feature_id: fid,\n step_id: sid,\n reason: `File '${f}' not found in repository`,\n });\n }\n }\n step.files = validFiles;\n\n // Verify api_usage[]\n const validApis: string[] = [];\n for (const api of step.api_usage || []) {\n if (sdkApiNames.size === 0 || sdkApiNames.has(api)) {\n validApis.push(api);\n } else {\n hallucinations.push({\n type: 'api',\n item: api,\n feature_id: fid,\n step_id: sid,\n reason: `API '${api}' not found in SDK API index`,\n });\n }\n }\n step.api_usage = validApis;\n\n // Verify keywords[] — skip for F0 (foundation keywords are pedagogical)\n if (isFoundation) continue;\n\n const validKws: string[] = [];\n for (const kw of step.keywords || []) {\n const kwLow = kw.toLowerCase();\n // Single-word keywords: use word boundary match to avoid\n // false positives (\"app\" should NOT match \"mapping\" or \"happen\")\n const isSingleWord = !kwLow.includes(' ');\n let found = false;\n // Check in step's files\n for (const f of validFiles) {\n const content = (fileContentsMap.get(f) || '').toLowerCase();\n if (isSingleWord) {\n found = new RegExp(`\\\\b${kwLow.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\\\b`).test(content);\n } else {\n found = content.includes(kwLow);\n }\n if (found) break;\n }\n // Check in any file\n if (!found) {\n for (const content of fileContentsMap.values()) {\n const lc = content.toLowerCase();\n if (isSingleWord) {\n found = new RegExp(`\\\\b${kwLow.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\\\b`).test(lc);\n } else {\n found = lc.includes(kwLow);\n }\n if (found) break;\n }\n }\n\n if (found) {\n validKws.push(kw);\n } else {\n hallucinations.push({\n type: 'keyword',\n item: kw,\n feature_id: fid,\n step_id: sid,\n reason: `Keyword '${kw}' not found in target files`,\n });\n }\n }\n step.keywords = validKws;\n }\n }\n\n return { graph: projectGraph, hallucinations };\n}\n","/**\n * STEP E: Escalate keywords/api_usage to neutral concepts + ULO/CIO/SIO depth + evidence files join.\n *\n * Ported from knowledge-tree/llm_project_graph.py escalate_and_map_concepts()\n * Maps concrete keywords to technology-neutral concept codes WITH depth levels.\n *\n * ULO/CIO/SIO model:\n * - ULO: WHAT + WHY — concept is introduced (what it is, why it exists)\n * - CIO: HOW — mechanism is explained (how it works)\n * - SIO: IMPLEMENTATION — concrete tech-specific usage (syntax, API)\n */\n\nimport { createLlmClient, llmChatJson, type LlmClientConfig } from '../utils/llmClient';\nimport type { ProjectGraph, Feature } from '../schemas/projectGraphSchema';\n\nexport interface ConceptMapping {\n concept_code: string;\n concept_name: string;\n keyword: string;\n depth: 'ulo' | 'cio' | 'sio';\n depth_rationale: string;\n evidence_files: string[];\n}\n\nexport interface EscalateOptions {\n projectGraph: ProjectGraph;\n fileContentsMap: Map<string, string>;\n availableConcepts?: string[];\n conceptMapOverride?: Record<string, { concept_code: string; concept_name: string; depth?: string }>;\n llmConfig?: LlmClientConfig;\n}\n\nfunction toUpperSnake(term: string): string {\n let s = term.replace(/^[^\\w]+/, '');\n s = s.replace(/([a-z0-9])([A-Z])/g, '$1_$2');\n s = s.replace(/[^\\w]+/g, '_');\n const res = s.toUpperCase().replace(/^_+|_+$/g, '');\n return res || 'CONCEPT';\n}\n\nfunction extractTermSnippets(term: string, fileContentsMap: Map<string, string>, maxSnippets = 1): string[] {\n const snippets: string[] = [];\n const termLow = term.toLowerCase();\n for (const [relPath, content] of fileContentsMap) {\n const lines = content.split('\\n');\n for (let idx = 0; idx < lines.length; idx++) {\n if (lines[idx].toLowerCase().includes(termLow)) {\n const start = Math.max(0, idx - 1);\n const end = Math.min(lines.length, idx + 2);\n let snippet = lines.slice(start, end).map(l => l.trim()).filter(Boolean).join(' ');\n if (snippet.length > 120) snippet = snippet.slice(0, 120) + '...';\n if (snippet) snippets.push(`[${relPath}]: ${snippet}`);\n if (snippets.length >= maxSnippets) break;\n }\n }\n if (snippets.length >= maxSnippets) break;\n }\n return snippets;\n}\n\n/**\n * Determine ULO/CIO/SIO depth based on keyword usage context.\n */\nfunction inferDepthFromContext(\n keyword: string,\n fileContentsMap: Map<string, string>,\n): { depth: 'ulo' | 'cio' | 'sio'; rationale: string } {\n const kw = keyword.toLowerCase();\n\n // SIO: specific implementation keywords (API names, decorators, syntax)\n const sioPatterns = [\n /^@/, // SwiftUI decorators: @State, @Binding\n /^import\\s/, // Import statements\n /\\(\\)$/, // Function calls\n /\\.prototype/, // Prototype methods\n /^new\\s/, // Constructor calls\n /^async\\s/, // Async keywords\n /^await\\s/,\n ];\n\n if (sioPatterns.some(p => p.test(keyword))) {\n return { depth: 'sio', rationale: `Keyword '${keyword}' is a specific API/syntax pattern` };\n }\n\n // CIO: mechanism-level keywords (patterns, protocols, design patterns)\n const cioPatterns = [\n /pattern/i, /protocol/i, /architecture/i, /lifecycle/i,\n /observer/i, /singleton/i, /factory/i, /delegate/i,\n /state\\s*management/i, /data\\s*flow/i, /binding/i,\n /mvvm/i, /mvc/i, /flux/i, /redux/i,\n /authentication/i, /authorization/i,\n /persistence/i, /caching/i, /serialization/i,\n ];\n\n if (cioPatterns.some(p => p.test(keyword))) {\n return { depth: 'cio', rationale: `Keyword '${keyword}' represents a mechanism/pattern` };\n }\n\n // ULO: general concept keywords (what/why level)\n const uloPatterns = [\n /design\\s*thinking/i, /user\\s*needs/i, /problem\\s*statement/i,\n /foundation/i, /setup/i, /overview/i, /introduction/i,\n /scaffold/i, /hello\\s*world/i, /getting\\s*started/i,\n ];\n\n if (uloPatterns.some(p => p.test(keyword))) {\n return { depth: 'ulo', rationale: `Keyword '${keyword}' is a foundational/introductory concept` };\n }\n\n // Default: check evidence in code — if it appears in import/declaration → SIO, in comment → ULO\n for (const content of fileContentsMap.values()) {\n const lines = content.split('\\n');\n for (const line of lines) {\n if (line.toLowerCase().includes(kw)) {\n if (/^(import|from|require|use |#include)/.test(line.trim())) {\n return { depth: 'sio', rationale: `Keyword '${keyword}' found in import statement` };\n }\n if (/^\\/\\/|^\\/\\*|^#|^-->/.test(line.trim())) {\n return { depth: 'ulo', rationale: `Keyword '${keyword}' found in comment/doc` };\n }\n // Found in code body → likely SIO\n return { depth: 'sio', rationale: `Keyword '${keyword}' used in implementation code` };\n }\n }\n }\n\n return { depth: 'sio', rationale: `Default: treating '${keyword}' as SIO (implementation-level)` };\n}\n\n/**\n * Escalate keywords/api_usage to neutral concepts with ULO/CIO/SIO depth and join evidence files.\n */\nexport async function escalateAndMapConcepts(\n options: EscalateOptions,\n): Promise<Map<string, ConceptMapping[]>> {\n const { projectGraph, fileContentsMap, availableConcepts, conceptMapOverride, llmConfig } = options;\n\n const features = projectGraph.features || [];\n\n // Collect all terms from all features\n const allTerms = new Set<string>();\n for (const feature of features) {\n for (const step of feature.steps || []) {\n for (const api of step.api_usage || []) allTerms.add(api);\n for (const kw of step.keywords || []) allTerms.add(kw);\n }\n }\n\n if (allTerms.size === 0) return new Map();\n\n const termList = Array.from(allTerms).sort();\n let llmResults: Record<string, { concept_code?: string; concept_name?: string; depth?: string }> = {};\n\n if (conceptMapOverride) {\n llmResults = conceptMapOverride;\n } else {\n try {\n const client = createLlmClient(llmConfig);\n const conceptBank = (availableConcepts || []).sort().join(', ') || '(empty)';\n\n const termEntries = termList.map(term => {\n const snippets = extractTermSnippets(term, fileContentsMap);\n return snippets.length > 0\n ? `- ${term} (Usage context: ${snippets[0]})`\n : `- ${term}`;\n });\n\n const systemPrompt = (\n 'You are a knowledge classification expert. For each concrete keyword/API, determine:\\n'\n + '1. The neutral concept it belongs to (UPPER_SNAKE_CASE)\\n'\n + '2. The depth level: ulo | cio | sio\\n\\n'\n + 'DEPTH DEFINITIONS:\\n'\n + '- ulo (WHAT + WHY): The keyword introduces a concept — \"what is it, why does it exist\"\\n'\n + ' Example: In a scaffold step, \"@State is SwiftUI\\'s way of managing local view state\"\\n'\n + '- cio (HOW): The keyword demonstrates a mechanism — \"how it works\"\\n'\n + ' Example: \"@State triggers view re-render when value changes — mechanism is value-type observation\"\\n'\n + '- sio (IMPLEMENTATION): The keyword is a concrete API/syntax used in code\\n'\n + ' Example: \"Using @State var isActive: Bool = false in ContentView\"\\n\\n'\n + 'RULES:\\n'\n + '1. PREFER an EXISTING concept from the CONCEPT_BANK below if the keyword is a manifestation of that concept.\\n'\n + '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.\\n'\n + `3. CONCEPT_BANK: ${conceptBank.slice(0, 12000)}\\n`\n + '4. Depth is per-keyword-in-context, NOT per-concept. The same concept can have ULO at one step and SIO at another.\\n'\n + 'Return JSON: {\"results\": {\"<keyword>\": {\"concept_code\": \"...\", \"concept_name\": \"...\", \"depth\": \"ulo|cio|sio\"}}}'\n );\n\n const userPrompt = (\n 'Classify the following keyword/API list into neutral concepts WITH depth levels.\\n'\n + 'Code usage context is provided to disambiguate depth:\\n'\n + termEntries.join('\\n')\n + '\\n\\nReturn JSON: {\"results\": {\"<keyword>\": {\"concept_code\": \"...\", \"concept_name\": \"...\", \"depth\": \"ulo|cio|sio\"}}}'\n );\n\n const result = await llmChatJson(client, systemPrompt, userPrompt, {\n temperature: 0.1,\n maxTokens: 16384,\n });\n\n llmResults = (result.results || {}) as Record<string, { concept_code?: string; concept_name?: string; depth?: string }>;\n } catch (err) {\n console.warn(`[WARN] Concept escalation LLM failed (${err}), using fallback depth inference`);\n }\n }\n\n // Join results into feature_concepts\n const featureConcepts = new Map<string, ConceptMapping[]>();\n\n for (const feature of features) {\n const fid = feature.id || 'F_UNK';\n const featureFiles = new Set<string>();\n for (const step of feature.steps || []) {\n for (const f of step.files || []) featureFiles.add(f);\n }\n\n const fTerms = [\n ...(feature.api_usage || []),\n ...(feature.steps || []).flatMap(s => [...(s.api_usage || []), ...(s.keywords || [])]),\n ];\n\n const items: ConceptMapping[] = [];\n const seen = new Set<string>();\n\n for (const kw of fTerms) {\n const info = llmResults[kw] || {};\n const cCode = info.concept_code || toUpperSnake(kw);\n const cName = info.concept_name || kw;\n\n // Determine depth: LLM result > fallback inference\n let depth: 'ulo' | 'cio' | 'sio' = 'sio';\n let depthRationale = 'Default: SIO';\n\n if (info.depth && ['ulo', 'cio', 'sio'].includes(info.depth)) {\n depth = info.depth as 'ulo' | 'cio' | 'sio';\n depthRationale = `LLM classified as ${depth}`;\n } else {\n const inferred = inferDepthFromContext(kw, fileContentsMap);\n depth = inferred.depth;\n depthRationale = inferred.rationale;\n }\n\n // Allow multiple keywords per concept — don't dedup by concept_code\n const kwKey = `${cCode}::${kw}`;\n if (seen.has(kwKey)) continue;\n seen.add(kwKey);\n\n // Evidence: files that actually contain this term\n const evidenceFiles: string[] = [];\n for (const f of featureFiles) {\n const content = fileContentsMap.get(f) || '';\n if (content.toLowerCase().includes(kw.toLowerCase())) {\n evidenceFiles.push(f);\n }\n }\n\n items.push({\n concept_code: cCode,\n concept_name: cName,\n keyword: kw,\n depth,\n depth_rationale: depthRationale,\n evidence_files: evidenceFiles,\n });\n }\n\n featureConcepts.set(fid, items);\n }\n\n return featureConcepts;\n}\n"]}
@@ -0,0 +1,211 @@
1
+ // src/assembly/roadmapAssembler.ts
2
+ function calculateOverhead(rawMinutes, overheadFactor) {
3
+ return Math.ceil(rawMinutes * overheadFactor);
4
+ }
5
+ function splitFeatureIntoMilestones(feature, featureConcepts, maxMinutes, overheadFactor) {
6
+ const steps = feature.steps || [];
7
+ if (steps.length === 0) return [];
8
+ const featureId = feature.id || "F_UNK";
9
+ const stepMinutes = steps.map((s) => s.effort?.estimated_minutes || 15);
10
+ const totalRawMinutes = stepMinutes.reduce((a, b) => a + b, 0);
11
+ if (calculateOverhead(totalRawMinutes, overheadFactor) <= maxMinutes) {
12
+ return [buildMilestone(feature, featureConcepts, steps, stepMinutes, featureId, 1)];
13
+ }
14
+ const milestones = [];
15
+ let currentSteps = [];
16
+ let currentMinutes = [];
17
+ let milestoneIndex = 1;
18
+ for (let i = 0; i < steps.length; i++) {
19
+ const step = steps[i];
20
+ const mins = stepMinutes[i];
21
+ const currentTotal = currentMinutes.reduce((a, b) => a + b, 0);
22
+ if (calculateOverhead(currentTotal + mins, overheadFactor) > maxMinutes && currentSteps.length > 0) {
23
+ milestones.push(buildMilestone(
24
+ feature,
25
+ featureConcepts,
26
+ currentSteps,
27
+ currentMinutes,
28
+ featureId,
29
+ milestoneIndex
30
+ ));
31
+ milestoneIndex++;
32
+ currentSteps = [];
33
+ currentMinutes = [];
34
+ }
35
+ currentSteps.push(step);
36
+ currentMinutes.push(mins);
37
+ }
38
+ if (currentSteps.length > 0) {
39
+ milestones.push(buildMilestone(
40
+ feature,
41
+ featureConcepts,
42
+ currentSteps,
43
+ currentMinutes,
44
+ featureId,
45
+ milestoneIndex
46
+ ));
47
+ }
48
+ return milestones;
49
+ }
50
+ function buildMilestone(feature, featureConcepts, steps, stepMinutes, featureId, milestoneIndex) {
51
+ const rawMinutes = stepMinutes.reduce((a, b) => a + b, 0);
52
+ const levels = steps.map((s) => s.completion_level || "mvp");
53
+ const completionLevel = levels.includes("extend") ? "extend" : levels.includes("mvp") ? "mvp" : "base";
54
+ const milestoneConcepts = /* @__PURE__ */ new Set();
55
+ const milestoneKeywords = /* @__PURE__ */ new Set();
56
+ for (const step of steps) {
57
+ const stepConceptCodes = step.concept_codes || [];
58
+ for (const code of stepConceptCodes) {
59
+ milestoneConcepts.add(code);
60
+ }
61
+ const stepKws = [...step.keywords || [], ...step.api_usage || []];
62
+ for (const cm of featureConcepts) {
63
+ if (stepKws.includes(cm.keyword)) {
64
+ milestoneConcepts.add(cm.concept_code);
65
+ milestoneKeywords.add(cm.keyword);
66
+ }
67
+ }
68
+ }
69
+ const depthCounts = { ulo: 0, cio: 0, sio: 0 };
70
+ for (const cm of featureConcepts) {
71
+ if (milestoneKeywords.has(cm.keyword)) {
72
+ depthCounts[cm.depth]++;
73
+ }
74
+ }
75
+ const dominantDepth = depthCounts.sio >= depthCounts.cio && depthCounts.sio >= depthCounts.ulo ? "sio" : depthCounts.cio >= depthCounts.ulo ? "cio" : "ulo";
76
+ return {
77
+ id: milestoneIndex === 1 ? featureId : `${featureId}-M${milestoneIndex}`,
78
+ name: milestoneIndex === 1 ? feature.name || featureId : `${feature.name || featureId} (Part ${milestoneIndex})`,
79
+ description: feature.description || "",
80
+ feature_id: featureId,
81
+ feature_name: feature.name || "",
82
+ concept_code: [...milestoneConcepts].join(", "),
83
+ depth: dominantDepth,
84
+ all_keywords: [],
85
+ new_keywords: [],
86
+ prerequisite_keywords: [],
87
+ steps,
88
+ estimated_minutes: rawMinutes,
89
+ adjusted_minutes: rawMinutes,
90
+ // placeholder — assembleRoadmap() applies actual overheadFactor
91
+ completion_level: completionLevel
92
+ };
93
+ }
94
+ function buildKeywordMap(featureConcepts) {
95
+ const map = /* @__PURE__ */ new Map();
96
+ for (const mappings of featureConcepts.values()) {
97
+ for (const m of mappings) {
98
+ const existing = map.get(m.concept_code) || [];
99
+ if (!existing.includes(m.keyword)) {
100
+ existing.push(m.keyword);
101
+ map.set(m.concept_code, existing);
102
+ }
103
+ }
104
+ }
105
+ return map;
106
+ }
107
+ function attachKeywordsToMilestones(milestones, keywordMap) {
108
+ const cumulativeKeywords = /* @__PURE__ */ new Set();
109
+ for (const milestone of milestones) {
110
+ const allKw = /* @__PURE__ */ new Set();
111
+ const conceptCodes = milestone.concept_code.split(",").map((c) => c.trim()).filter(Boolean);
112
+ for (const code of conceptCodes) {
113
+ const kws = keywordMap.get(code) || [];
114
+ for (const kw of kws) allKw.add(kw);
115
+ }
116
+ milestone.all_keywords = Array.from(allKw).sort();
117
+ const newKw = [];
118
+ const prereqKw = [];
119
+ for (const kw of milestone.all_keywords) {
120
+ if (cumulativeKeywords.has(kw)) {
121
+ prereqKw.push(kw);
122
+ } else {
123
+ newKw.push(kw);
124
+ cumulativeKeywords.add(kw);
125
+ }
126
+ }
127
+ milestone.new_keywords = newKw;
128
+ milestone.prerequisite_keywords = prereqKw;
129
+ }
130
+ return milestones;
131
+ }
132
+ function groupIntoPhases(milestones, sessionMinutes) {
133
+ const phases = [];
134
+ let currentMilestones = [];
135
+ let currentMinutes = 0;
136
+ let phaseNum = 1;
137
+ for (const milestone of milestones) {
138
+ const milestoneMinutes = milestone.adjusted_minutes;
139
+ if (currentMinutes + milestoneMinutes > sessionMinutes && currentMilestones.length > 0) {
140
+ phases.push(buildPhase(currentMilestones, phaseNum));
141
+ phaseNum++;
142
+ currentMilestones = [];
143
+ currentMinutes = 0;
144
+ }
145
+ currentMilestones.push(milestone);
146
+ currentMinutes += milestoneMinutes;
147
+ }
148
+ if (currentMilestones.length > 0) {
149
+ phases.push(buildPhase(currentMilestones, phaseNum));
150
+ }
151
+ return phases;
152
+ }
153
+ function buildPhase(milestones, phaseNum) {
154
+ const totalMinutes = milestones.reduce((sum, m) => sum + m.adjusted_minutes, 0);
155
+ const depths = milestones.map((m) => m.depth);
156
+ const uniqueDepths = [...new Set(depths)];
157
+ const progression = uniqueDepths.map((d) => d.toUpperCase()).join(" \u2192 ");
158
+ return {
159
+ phase_id: phaseNum,
160
+ phase_name: `Phase ${phaseNum}`,
161
+ milestones,
162
+ total_minutes: totalMinutes,
163
+ concept_progression: progression
164
+ };
165
+ }
166
+ function assembleRoadmap(options) {
167
+ const {
168
+ projectGraph,
169
+ featureConcepts = /* @__PURE__ */ new Map(),
170
+ sessionMinutes = 90,
171
+ overheadFactor = 1.15,
172
+ maxMilestoneMinutes = 120
173
+ } = options;
174
+ const features = projectGraph.features || [];
175
+ const keywordMap = buildKeywordMap(featureConcepts);
176
+ const allMilestones = [];
177
+ for (const feature of features) {
178
+ const fid = feature.id || "F_UNK";
179
+ const fConcepts = featureConcepts.get(fid) || [];
180
+ const milestones = splitFeatureIntoMilestones(
181
+ feature,
182
+ fConcepts,
183
+ maxMilestoneMinutes,
184
+ overheadFactor
185
+ );
186
+ allMilestones.push(...milestones);
187
+ }
188
+ for (const milestone of allMilestones) {
189
+ milestone.adjusted_minutes = calculateOverhead(milestone.estimated_minutes, overheadFactor);
190
+ }
191
+ attachKeywordsToMilestones(allMilestones, keywordMap);
192
+ const phases = groupIntoPhases(allMilestones, sessionMinutes);
193
+ const totalEstimatedMinutes = allMilestones.reduce((sum, m) => sum + m.estimated_minutes, 0);
194
+ const totalAdjustedMinutes = allMilestones.reduce((sum, m) => sum + m.adjusted_minutes, 0);
195
+ return {
196
+ project: projectGraph.project,
197
+ product: projectGraph.product,
198
+ phases,
199
+ feature_concepts: featureConcepts,
200
+ time_budget: {
201
+ session_minutes: sessionMinutes,
202
+ overhead_factor: overheadFactor,
203
+ total_estimated_minutes: totalEstimatedMinutes,
204
+ total_adjusted_minutes: totalAdjustedMinutes
205
+ }
206
+ };
207
+ }
208
+
209
+ export { assembleRoadmap };
210
+ //# sourceMappingURL=chunk-ONQHJ4OH.mjs.map
211
+ //# sourceMappingURL=chunk-ONQHJ4OH.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/assembly/roadmapAssembler.ts"],"names":[],"mappings":";AAoEA,SAAS,iBAAA,CACP,YACA,cAAA,EACQ;AACR,EAAA,OAAO,IAAA,CAAK,IAAA,CAAK,UAAA,GAAa,cAAc,CAAA;AAC9C;AAQA,SAAS,0BAAA,CACP,OAAA,EACA,eAAA,EACA,UAAA,EACA,cAAA,EACsB;AACtB,EA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,EAAwB;AAAA;AAC1B,GACF;AACF","file":"chunk-ONQHJ4OH.mjs","sourcesContent":["/**\n * Roadmap assembly — assembles final roadmap with keyword tracking and time awareness.\n *\n * Ported from knowledge-tree/assemble_roadmap.py\n * Handles: topo sort, phases, keyword-per-milestone tracking.\n *\n * Improvements:\n * - Time budget per session/lesson\n * - Overhead factor (setup, transitions, review)\n * - Smart feature → milestone splitting (respect time constraints)\n * - Phase grouping based on concept progression\n */\n\nimport type { ProjectGraph, Feature, Step } from '../schemas/projectGraphSchema';\nimport type { ConceptMapping } from '../graph/conceptEscalator';\n\nexport interface AssembledMilestone {\n id: string;\n name: string;\n description: string;\n feature_id: string;\n feature_name: string;\n concept_code: string;\n depth: 'ulo' | 'cio' | 'sio';\n all_keywords: string[];\n new_keywords: string[];\n prerequisite_keywords: string[];\n steps: Step[];\n estimated_minutes: number;\n adjusted_minutes: number; // with overhead\n completion_level: string;\n}\n\nexport interface AssembledPhase {\n phase_id: number;\n phase_name: string;\n milestones: AssembledMilestone[];\n total_minutes: number;\n concept_progression: string; // e.g., \"ULO → CIO → SIO\"\n}\n\nexport interface AssembledRoadmap {\n project: ProjectGraph['project'];\n product: ProjectGraph['product'];\n phases: AssembledPhase[];\n feature_concepts: Map<string, ConceptMapping[]>;\n time_budget: {\n session_minutes: number;\n overhead_factor: number;\n total_estimated_minutes: number;\n total_adjusted_minutes: number;\n };\n}\n\nexport interface AssembleOptions {\n projectGraph: ProjectGraph;\n featureConcepts?: Map<string, ConceptMapping[]>;\n sessionMinutes?: number; // Target minutes per session/lesson (default: 90)\n overheadFactor?: number; // Overhead multiplier (default: 1.15 = 15% overhead)\n maxMilestoneMinutes?: number; // Max minutes before splitting a milestone (default: 120)\n}\n\n// ─── Overhead Calculation ────────────────────────────────────────────────────\n\n/**\n * Calculate overhead-adjusted minutes for a milestone.\n * Overhead includes: setup time, transitions, review, Q&A.\n */\nfunction calculateOverhead(\n rawMinutes: number,\n overheadFactor: number,\n): number {\n return Math.ceil(rawMinutes * overheadFactor);\n}\n\n// ─── Milestone Splitting ─────────────────────────────────────────────────────\n\n/**\n * Split a feature's steps into multiple milestones if they exceed maxMilestoneMinutes.\n * Splits at natural break points (between steps of different complexity).\n */\nfunction splitFeatureIntoMilestones(\n feature: Feature,\n featureConcepts: ConceptMapping[],\n maxMinutes: number,\n overheadFactor: number,\n): AssembledMilestone[] {\n const steps = feature.steps || [];\n if (steps.length === 0) return [];\n\n const featureId = feature.id || 'F_UNK';\n\n // Calculate raw minutes per step\n const stepMinutes = steps.map(s => s.effort?.estimated_minutes || 15);\n const totalRawMinutes = stepMinutes.reduce((a, b) => a + b, 0);\n\n // If within budget, return as single milestone\n if (calculateOverhead(totalRawMinutes, overheadFactor) <= maxMinutes) {\n return [buildMilestone(feature, featureConcepts, steps, stepMinutes, featureId, 1)];\n }\n\n // Split into multiple milestones\n const milestones: AssembledMilestone[] = [];\n let currentSteps: Step[] = [];\n let currentMinutes: number[] = [];\n let milestoneIndex = 1;\n\n for (let i = 0; i < steps.length; i++) {\n const step = steps[i];\n const mins = stepMinutes[i];\n\n // Check if adding this step would exceed budget\n const currentTotal = currentMinutes.reduce((a, b) => a + b, 0);\n if (calculateOverhead(currentTotal + mins, overheadFactor) > maxMinutes && currentSteps.length > 0) {\n // Split here\n milestones.push(buildMilestone(\n feature, featureConcepts, currentSteps, currentMinutes,\n featureId, milestoneIndex,\n ));\n milestoneIndex++;\n currentSteps = [];\n currentMinutes = [];\n }\n\n currentSteps.push(step);\n currentMinutes.push(mins);\n }\n\n // Don't forget the last group\n if (currentSteps.length > 0) {\n milestones.push(buildMilestone(\n feature, featureConcepts, currentSteps, currentMinutes,\n featureId, milestoneIndex,\n ));\n }\n\n return milestones;\n}\n\n/**\n * Build a single AssembledMilestone from steps.\n * Concept codes are mapped per-step, not per-feature.\n */\nfunction buildMilestone(\n feature: Feature,\n featureConcepts: ConceptMapping[],\n steps: Step[],\n stepMinutes: number[],\n featureId: string,\n milestoneIndex: number,\n): AssembledMilestone {\n const rawMinutes = stepMinutes.reduce((a, b) => a + b, 0);\n const levels = steps.map(s => s.completion_level || 'mvp');\n const completionLevel = levels.includes('extend') ? 'extend'\n : levels.includes('mvp') ? 'mvp'\n : 'base';\n\n // Collect concept codes PER STEP (not per feature)\n const milestoneConcepts = new Set<string>();\n const milestoneKeywords = new Set<string>();\n for (const step of steps) {\n // Use step-level concept_codes if propagated, else match by keyword\n const stepConceptCodes = step.concept_codes || [];\n for (const code of stepConceptCodes) {\n milestoneConcepts.add(code);\n }\n // Also match by keyword presence\n const stepKws = [...(step.keywords || []), ...(step.api_usage || [])];\n for (const cm of featureConcepts) {\n if (stepKws.includes(cm.keyword)) {\n milestoneConcepts.add(cm.concept_code);\n milestoneKeywords.add(cm.keyword);\n }\n }\n }\n\n // Determine dominant depth from step-level concept mappings\n const depthCounts = { ulo: 0, cio: 0, sio: 0 };\n for (const cm of featureConcepts) {\n if (milestoneKeywords.has(cm.keyword)) {\n depthCounts[cm.depth]++;\n }\n }\n const dominantDepth: 'ulo' | 'cio' | 'sio' =\n depthCounts.sio >= depthCounts.cio && depthCounts.sio >= depthCounts.ulo ? 'sio'\n : depthCounts.cio >= depthCounts.ulo ? 'cio'\n : 'ulo';\n\n return {\n id: milestoneIndex === 1 ? featureId : `${featureId}-M${milestoneIndex}`,\n name: milestoneIndex === 1 ? (feature.name || featureId) : `${feature.name || featureId} (Part ${milestoneIndex})`,\n description: feature.description || '',\n feature_id: featureId,\n feature_name: feature.name || '',\n concept_code: [...milestoneConcepts].join(', '),\n depth: dominantDepth,\n all_keywords: [],\n new_keywords: [],\n prerequisite_keywords: [],\n steps,\n estimated_minutes: rawMinutes,\n adjusted_minutes: rawMinutes, // placeholder — assembleRoadmap() applies actual overheadFactor\n completion_level: completionLevel,\n };\n}\n\n// ─── Keyword Tracking ────────────────────────────────────────────────────────\n\n/**\n * Build keyword map: concept_code → [keywords]\n */\nfunction buildKeywordMap(\n featureConcepts: Map<string, ConceptMapping[]>,\n): Map<string, string[]> {\n const map = new Map<string, string[]>();\n for (const mappings of featureConcepts.values()) {\n for (const m of mappings) {\n const existing = map.get(m.concept_code) || [];\n if (!existing.includes(m.keyword)) {\n existing.push(m.keyword);\n map.set(m.concept_code, existing);\n }\n }\n }\n return map;\n}\n\n/**\n * Attach keywords to milestones, computing new vs prerequisite.\n */\nfunction attachKeywordsToMilestones(\n milestones: AssembledMilestone[],\n keywordMap: Map<string, string[]>,\n): AssembledMilestone[] {\n const cumulativeKeywords = new Set<string>();\n\n for (const milestone of milestones) {\n // Aggregate keywords from concept codes\n const allKw = new Set<string>();\n const conceptCodes = milestone.concept_code.split(',').map((c: string) => c.trim()).filter(Boolean);\n for (const code of conceptCodes) {\n const kws = keywordMap.get(code) || [];\n for (const kw of kws) allKw.add(kw);\n }\n\n milestone.all_keywords = Array.from(allKw).sort();\n\n // Compute new vs prerequisite\n const newKw: string[] = [];\n const prereqKw: string[] = [];\n for (const kw of milestone.all_keywords) {\n if (cumulativeKeywords.has(kw)) {\n prereqKw.push(kw);\n } else {\n newKw.push(kw);\n cumulativeKeywords.add(kw);\n }\n }\n\n milestone.new_keywords = newKw;\n milestone.prerequisite_keywords = prereqKw;\n }\n\n return milestones;\n}\n\n// ─── Phase Grouping ──────────────────────────────────────────────────────────\n\n/**\n * Group milestones into phases based on time budget and concept progression.\n */\nfunction groupIntoPhases(\n milestones: AssembledMilestone[],\n sessionMinutes: number,\n): AssembledPhase[] {\n const phases: AssembledPhase[] = [];\n let currentMilestones: AssembledMilestone[] = [];\n let currentMinutes = 0;\n let phaseNum = 1;\n\n for (const milestone of milestones) {\n const milestoneMinutes = milestone.adjusted_minutes;\n\n // If adding this milestone would exceed session budget, start new phase\n if (currentMinutes + milestoneMinutes > sessionMinutes && currentMilestones.length > 0) {\n phases.push(buildPhase(currentMilestones, phaseNum));\n phaseNum++;\n currentMilestones = [];\n currentMinutes = 0;\n }\n\n currentMilestones.push(milestone);\n currentMinutes += milestoneMinutes;\n }\n\n // Don't forget the last phase\n if (currentMilestones.length > 0) {\n phases.push(buildPhase(currentMilestones, phaseNum));\n }\n\n return phases;\n}\n\nfunction buildPhase(milestones: AssembledMilestone[], phaseNum: number): AssembledPhase {\n const totalMinutes = milestones.reduce((sum, m) => sum + m.adjusted_minutes, 0);\n\n // Determine concept progression\n const depths = milestones.map(m => m.depth);\n const uniqueDepths = [...new Set(depths)];\n const progression = uniqueDepths.map(d => d.toUpperCase()).join(' → ');\n\n return {\n phase_id: phaseNum,\n phase_name: `Phase ${phaseNum}`,\n milestones,\n total_minutes: totalMinutes,\n concept_progression: progression,\n };\n}\n\n// ─── Main Assembly ───────────────────────────────────────────────────────────\n\n/**\n * Assemble project graph into a roadmap with phases and keyword tracking.\n */\nexport function assembleRoadmap(options: AssembleOptions): AssembledRoadmap {\n const {\n projectGraph,\n featureConcepts = new Map(),\n sessionMinutes = 90,\n overheadFactor = 1.15,\n maxMilestoneMinutes = 120,\n } = options;\n\n const features = projectGraph.features || [];\n const keywordMap = buildKeywordMap(featureConcepts);\n\n // Build milestones from features (with splitting)\n const allMilestones: AssembledMilestone[] = [];\n\n for (const feature of features) {\n const fid = feature.id || 'F_UNK';\n const fConcepts = featureConcepts.get(fid) || [];\n\n const milestones = splitFeatureIntoMilestones(\n feature,\n fConcepts,\n maxMilestoneMinutes,\n overheadFactor,\n );\n\n allMilestones.push(...milestones);\n }\n\n // Apply overhead factor\n for (const milestone of allMilestones) {\n milestone.adjusted_minutes = calculateOverhead(milestone.estimated_minutes, overheadFactor);\n }\n\n // Attach keywords (new vs prerequisite)\n attachKeywordsToMilestones(allMilestones, keywordMap);\n\n // Group into phases based on session time\n const phases = groupIntoPhases(allMilestones, sessionMinutes);\n\n // Calculate totals\n const totalEstimatedMinutes = allMilestones.reduce((sum, m) => sum + m.estimated_minutes, 0);\n const totalAdjustedMinutes = allMilestones.reduce((sum, m) => sum + m.adjusted_minutes, 0);\n\n return {\n project: projectGraph.project,\n product: projectGraph.product,\n phases,\n feature_concepts: featureConcepts,\n time_budget: {\n session_minutes: sessionMinutes,\n overhead_factor: overheadFactor,\n total_estimated_minutes: totalEstimatedMinutes,\n total_adjusted_minutes: totalAdjustedMinutes,\n },\n };\n}\n"]}