@ikas/code-components-mcp 1.4.0-beta.4 → 1.4.0-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -15,6 +15,59 @@ function loadJsonFile(relativePath) {
15
15
  }
16
16
  return JSON.parse(fs.readFileSync(filePath, "utf-8"));
17
17
  }
18
+ // Resolve theme.json from either raw string or absolute file path.
19
+ // Exactly one of the two must be provided.
20
+ function resolveThemeJson(themeJson, themeJsonPath) {
21
+ const hasInline = typeof themeJson === "string" && themeJson.length > 0;
22
+ const hasPath = typeof themeJsonPath === "string" && themeJsonPath.length > 0;
23
+ if (hasInline === hasPath) {
24
+ throw new Error("Provide exactly one of `theme_json` (raw JSON string) or `theme_json_path` (absolute path to theme.json).");
25
+ }
26
+ let raw;
27
+ if (hasPath) {
28
+ if (!path.isAbsolute(themeJsonPath)) {
29
+ throw new Error(`theme_json_path must be absolute: ${themeJsonPath}`);
30
+ }
31
+ if (!fs.existsSync(themeJsonPath)) {
32
+ throw new Error(`theme_json_path not found: ${themeJsonPath}`);
33
+ }
34
+ try {
35
+ raw = fs.readFileSync(themeJsonPath, "utf-8");
36
+ }
37
+ catch (e) {
38
+ throw new Error(`Failed to read theme_json_path "${themeJsonPath}": ${e.message}`);
39
+ }
40
+ }
41
+ else {
42
+ raw = themeJson;
43
+ }
44
+ try {
45
+ return JSON.parse(raw);
46
+ }
47
+ catch (e) {
48
+ throw new Error(`Invalid JSON in theme.json: ${e.message}`);
49
+ }
50
+ }
51
+ // Atomic file write: temp file in same dir, then rename. Same-fs rename is atomic on POSIX.
52
+ function writeFileAtomic(targetPath, content) {
53
+ const dir = path.dirname(targetPath);
54
+ const base = path.basename(targetPath);
55
+ const tmp = path.join(dir, `.${base}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`);
56
+ try {
57
+ fs.writeFileSync(tmp, content, "utf-8");
58
+ fs.renameSync(tmp, targetPath);
59
+ }
60
+ catch (e) {
61
+ try {
62
+ if (fs.existsSync(tmp))
63
+ fs.unlinkSync(tmp);
64
+ }
65
+ catch {
66
+ // ignore cleanup failure
67
+ }
68
+ throw e;
69
+ }
70
+ }
18
71
  // Try multiple paths for storefront data (generated output or local data dir)
19
72
  function loadStorefrontData() {
20
73
  const paths = [
@@ -506,18 +559,23 @@ function generateMigrationPlan(theme, projectName, oldSourceDir) {
506
559
  }
507
560
  const sharedSubs = oldSourceDir ? scanSharedSubcomponents(oldSourceDir) : [];
508
561
  const parts = [];
509
- parts.push(`# Theme Migration Plan`);
562
+ parts.push(`# Theme Migration Plan — \`${projectName}\``);
510
563
  parts.push("");
511
564
  parts.push(`**Generated:** ${new Date().toISOString().slice(0, 10)}`);
512
- parts.push(`**Project ID:** \`${projectName}\``);
513
565
  parts.push(`**Source:** ${components.length} old components, ${customData.filter(cd => cd.isRoot).length} custom data types, ${(theme.pages || []).length} pages`);
514
566
  parts.push("");
515
- parts.push(`This file is the **source of truth** for the migration. All sessions must read it before starting work.`);
516
- parts.push("");
517
- parts.push(`## Status Legend`);
518
- parts.push(`- \`[ ]\` Not started`);
519
- parts.push(`- \`[~]\` In progress`);
520
- parts.push(`- \`[x]\` Complete`);
567
+ parts.push(`> ## READ THIS FIRST`);
568
+ parts.push(`>`);
569
+ parts.push(`> This file is your responsibility from here. The MCP wrote this initial scaffold **once**. You own all updates — no MCP tool will modify this file again.`);
570
+ parts.push(`>`);
571
+ parts.push(`> 1. **Tick checkboxes** as you finish work. Use \`[~]\` for in-progress and \`[x]\` for done. Edit the file directly with your file-editing tools.`);
572
+ parts.push(`> 2. **theme.json is incomplete.** Atomic components (Button, Input, Card, icons, etc.) often live only in \`src/\` and are NOT referenced from theme.json. Before you start section migration, scan the old source directory and ADD entries to this file for anything the initial scan missed — list them under \`## Source Code Analysis\` and add shared ones to \`### Shared Sub-Components\`.`);
573
+ parts.push(`> 3. **Custom data types are NOT pre-converted.** For each customData entry used by a section, decide enum-vs-component when you migrate that section. Log every decision in \`## Custom Data Decisions\` with reasoning. See \`get_migration_guide("custom-data-conversion")\` for the heuristic.`);
574
+ parts.push(`> 4. **Preserve feature parity. Do NOT silently simplify or drop features.** If an old prop has richer fields than a new built-in prop type can carry (e.g. a navigation link with a per-link image), the answer is to build a child component — never to flatten and "add it later." Later doesn't come. If the user explicitly wants a feature removed, log that as an explicit decision in \`## Notes\`; otherwise migrate to functional parity.`);
575
+ parts.push(`> 5. **Per-section work:** call \`get_section_migration_plan({theme_json_path, section_name, project_name: "${projectName}"})\` for each section. The MCP returns concrete CLI commands and flags any customData-referencing props with a "Decide: enum or component?" callout.`);
576
+ parts.push(`> 6. **If you discover new shared sub-components mid-migration**, add them under \`### Shared Sub-Components\` and any notes under \`## Notes\`.`);
577
+ parts.push(`>`);
578
+ parts.push(`> Status legend: \`[ ]\` not started · \`[~]\` in progress · \`[x]\` complete.`);
521
579
  parts.push("");
522
580
  parts.push(`## Foundation`);
523
581
  parts.push("");
@@ -537,27 +595,9 @@ function generateMigrationPlan(theme, projectName, oldSourceDir) {
537
595
  parts.push(`- [ ] ${settings.fontFamily.name} (weights: ${settings.fontFamily.variants?.join(", ") || "default"})`);
538
596
  parts.push("");
539
597
  }
540
- // Custom Enums
541
- const enumCustomData = customData.filter(cd => cd.type === "ENUM" && cd.isRoot);
542
- if (enumCustomData.length > 0) {
543
- parts.push(`### Custom Enums (run these BEFORE any \`config add-component\`)`);
544
- parts.push("");
545
- for (const cd of enumCustomData) {
546
- const enumName = cd.typescriptName || (cd.name ? cd.name.replace(/[^a-zA-Z0-9]/g, "") : "Enum");
547
- const options = (cd.enumOptions || []).reduce((acc, o) => {
548
- if (o.displayName && o.value)
549
- acc[o.displayName] = o.value;
550
- return acc;
551
- }, {});
552
- const optionsStr = JSON.stringify(options);
553
- parts.push(`- [ ] **${enumName}**`);
554
- parts.push(` \`\`\`bash`);
555
- parts.push(` npx ikas-component config add-enum --name "${enumName}" --options '${optionsStr}'`);
556
- parts.push(` \`\`\``);
557
- parts.push(` Save the returned \`enumId\` and update this file with: \`enumId: <id>\``);
558
- }
559
- parts.push("");
560
- }
598
+ // (Custom Enums foundation subsection intentionally removed — see ## Custom Data Types below.
599
+ // Old customData entries are NOT pre-migrated as enums; each is a per-section decision.
600
+ // See get_migration_guide("custom-data-conversion") for the enum-vs-component heuristic.)
561
601
  // Shared sub-components
562
602
  if (sharedSubs.length > 0) {
563
603
  parts.push(`### Shared Sub-Components (→ \`src/sub-components/\`)`);
@@ -581,6 +621,51 @@ function generateMigrationPlan(theme, projectName, oldSourceDir) {
581
621
  parts.push(`_Old source directory not provided — shared sub-components cannot be detected automatically. If you have access to the old source, call \`plan_migration\` again with \`old_source_dir\` to populate this section._`);
582
622
  parts.push("");
583
623
  }
624
+ parts.push(`> **This scan is partial.** \`scanSharedSubcomponents\` only detects relative imports used by **3 or more** old components. Atomic components used by fewer sections (often Button/Input/Card/icon primitives) will be missed. Scan \`src/\` yourself and add any others under \`## Source Code Analysis\` below.`);
625
+ parts.push("");
626
+ // Custom Data Types — deferred decisions (reference list, not checkboxes)
627
+ const rootCustomData = customData.filter((cd) => cd.isRoot);
628
+ if (rootCustomData.length > 0) {
629
+ // Build a usage map: which sections reference each customData type
630
+ const usageByCustomDataId = new Map();
631
+ for (const comp of components) {
632
+ const sectionName = comp.displayName || comp.dir || comp.id || "?";
633
+ for (const p of comp.props || []) {
634
+ if (p.type === "CUSTOM" && p.customDataId) {
635
+ const list = usageByCustomDataId.get(p.customDataId) || [];
636
+ if (!list.includes(sectionName))
637
+ list.push(sectionName);
638
+ usageByCustomDataId.set(p.customDataId, list);
639
+ }
640
+ }
641
+ }
642
+ parts.push(`### Custom Data Types — decide during section migration`);
643
+ parts.push("");
644
+ parts.push(`Each entry below is an OLD \`theme.customData[]\` type. Do **not** pre-migrate these as enums. When you migrate the section that uses one, decide:`);
645
+ parts.push(`- **Flat scalar set** (e.g. \`"left" | "right" | "center"\`) → new-system **enum prop** via \`config add-enum\`.`);
646
+ parts.push(`- **Structured record** (e.g. \`{image, link, title}\`, repeated in a list) → new-system **component** via \`config add-component\` + COMPONENT_LIST wiring on the parent.`);
647
+ parts.push("");
648
+ parts.push(`Log every decision in \`## Custom Data Decisions\` below. See \`get_migration_guide("custom-data-conversion")\` for the full heuristic and worked examples (Position, Slide, MenuItem).`);
649
+ parts.push("");
650
+ for (const cd of rootCustomData) {
651
+ const cdName = cd.typescriptName || cd.name || cd.id || "Unknown";
652
+ const cdType = cd.type || "?";
653
+ let shape = "";
654
+ if (cd.type === "ENUM") {
655
+ const opts = (cd.enumOptions || []).map((o) => o.value || o.displayName).filter(Boolean);
656
+ shape = ` — shape: \`enum {${opts.slice(0, 6).join(", ")}${opts.length > 6 ? ", ..." : ""}}\``;
657
+ }
658
+ else if (cd.nestedData && cd.nestedData.length > 0) {
659
+ const first = cd.nestedData[0];
660
+ const fields = (first?.nestedData || cd.nestedData || []).map((f) => `${f.key || f.name || "?"}: ${f.type || "?"}`).slice(0, 8);
661
+ shape = ` — shape: \`{${fields.join(", ")}}\``;
662
+ }
663
+ const usedBy = cd.id ? usageByCustomDataId.get(cd.id) || [] : [];
664
+ const usedByStr = usedBy.length > 0 ? ` — used by: ${usedBy.slice(0, 6).join(", ")}${usedBy.length > 6 ? `, +${usedBy.length - 6} more` : ""}` : ` — _not directly referenced by any section's props (may be nested inside another customData)_`;
665
+ parts.push(`- \`${cdName}\` (${cdType})${shape}${usedByStr}`);
666
+ }
667
+ parts.push("");
668
+ }
584
669
  // Sections queue
585
670
  parts.push(`## Sections`);
586
671
  parts.push("");
@@ -638,49 +723,43 @@ function generateMigrationPlan(theme, projectName, oldSourceDir) {
638
723
  }
639
724
  parts.push("");
640
725
  }
641
- // Known Environmental Issues (agents fill in during work)
642
- parts.push(`## Known Environmental Issues`);
726
+ // Source Code Analysis placeholder for the LLM to fill in
727
+ parts.push(`## Source Code Analysis`);
643
728
  parts.push("");
644
- parts.push(`_Agents working on this migration: record any non-component build/TS errors here so future sessions don't waste time diagnosing them._`);
729
+ parts.push(`> **Before starting section migration**, scan the old \`src/\` for components NOT listed above. theme.json does not see atomic primitives — buttons, inputs, cards, icon wrappers, layout helpers, etc. — that are imported by sections but never appear as theme components. Add them here, then decide which become shared sub-components vs which collapse into section bodies.`);
645
730
  parts.push("");
646
- parts.push(`- [ ] _(none recorded yet)_`);
731
+ parts.push(`<!-- Example: \`- Button (src/atoms/Button/) used by ~all sections → promote to Shared Sub-Component\` -->`);
647
732
  parts.push("");
648
- // Usage section
649
- parts.push(`## Per-Section Usage`);
733
+ // Custom Data Decisions — append-only log the LLM fills as it makes per-section decisions
734
+ parts.push(`## Custom Data Decisions`);
650
735
  parts.push("");
651
- parts.push(`Once the Foundation is complete, for each section above:`);
736
+ parts.push(`> Log each customData enum-vs-component decision here as you encounter it during section migration. Format: \`- \\\`<CustomDataName>\\\` → enum/component \\\`<target name>\\\` (YYYY-MM-DD) — reasoning\`.`);
652
737
  parts.push("");
653
- parts.push(`1. Find the first unchecked \`[ ]\` section (start with Simple).`);
654
- parts.push(`2. Call \`get_section_migration_plan(theme_json, "<old section name>", "${projectName}")\`.`);
655
- parts.push(`3. Read the old source files listed in the plan.`);
656
- parts.push(`4. Run the CLI commands in the plan (they create parent + children with auto-generated types.ts).`);
657
- parts.push(`5. Write \`index.tsx\` and \`styles.css\` using the patterns in the plan. DO NOT manually edit types.ts.`);
658
- parts.push(`6. Mark the section \`[x]\` when it builds cleanly. Append a short note to the **Session Log** below (what libraries you replaced, any ad-hoc props you had to add, the actual folder name the CLI created if different from the name you passed).`);
738
+ parts.push(`<!-- Example: \`- SlideData component \\\`hero-slide\\\` (2026-05-11) structured record {image,link,title}; LIST_OF_LINK would drop the image\` -->`);
659
739
  parts.push("");
660
- // Session Log agents append notes here
661
- parts.push(`## Session Log`);
740
+ // Known Environmental Issues (agents fill in during work)
741
+ parts.push(`## Known Environmental Issues`);
662
742
  parts.push("");
663
- parts.push(`_Each agent: append a bullet after completing work. Format: \`- [YYYY-MM-DD] <section-id>: <brief note>\`. This is how future sessions learn about decisions not encoded in the plan structure._`);
743
+ parts.push(`_Record any non-component build/TS errors here so future sessions don't waste time diagnosing them._`);
664
744
  parts.push("");
665
- parts.push(`_After completing Foundation, also record which sub-components were built and which were skipped, e.g.:_`);
666
- parts.push(`<!-- \`- [2026-04-15] Foundation: built Input, SubmitButton, Modal, SectionHeader, StarRating. Skipped: GoogleCaptcha (needs investigation), BlogCard, Pagination (low priority).\` -->`);
667
- parts.push(`<!-- \`- [2026-04-15] ${projectName}-footer: swapped react-hot-toast for inline status text; newsletter uses form-model pattern (getNewsletterSubscriptionForm). CLI created folder as "Footer/" as expected.\` -->`);
745
+ parts.push(`- [ ] _(none recorded yet)_`);
668
746
  parts.push("");
669
- // Cross-references
747
+ // Notes — append-only log for decisions not captured elsewhere
748
+ parts.push(`## Notes`);
749
+ parts.push("");
750
+ parts.push(`_Append a bullet after completing work — library swaps, ad-hoc props, CLI folder-name oddities, user-approved feature drops, etc. Format: \`- [YYYY-MM-DD] <section-id>: <brief note>\`._`);
751
+ parts.push("");
752
+ parts.push(`<!-- Example: \`- [2026-04-15] ${projectName}-footer: swapped react-hot-toast for inline status text; CLI created Footer/ as expected\` -->`);
753
+ parts.push("");
754
+ // Cross-references — keep terse; LLM can call `get_migration_guide("list")` or `get_framework_guide("list")` for more
670
755
  parts.push(`## Cross-References`);
671
756
  parts.push("");
672
- parts.push(`Essential MCP tools to call during migration:`);
757
+ parts.push(`- \`get_migration_guide("iterative-workflow")\` the full per-phase protocol`);
758
+ parts.push(`- \`get_migration_guide("custom-data-conversion")\` — enum-vs-component decisions`);
759
+ parts.push(`- \`get_migration_guide("prop-runtime-shapes")\` — runtime shapes & access patterns`);
760
+ parts.push(`- \`get_framework_guide("common-pitfalls")\` — gotchas & old→new property migrations`);
673
761
  parts.push("");
674
- parts.push(`- \`get_migration_guide("iterative-workflow")\` full protocol for resumable migrations`);
675
- parts.push(`- \`get_migration_guide("component-renderer-limitations")\` — critical constraints when using COMPONENT_LIST`);
676
- parts.push(`- \`get_migration_guide("prop-runtime-shapes")\` — \`.data\` vs \`.links\`, \`.variant\` vs \`.product\`, etc.`);
677
- parts.push(`- \`get_migration_guide("link-prop-decision-guide")\` — LINK vs LIST_OF_LINK vs COMPONENT_LIST`);
678
- parts.push(`- \`get_migration_guide("library-replacements")\` — swiper, headlessui, tailwind, etc.`);
679
- parts.push(`- \`get_migration_guide("react-to-preact")\` — observer rules, imports, IkasSlider removal`);
680
- parts.push(`- \`get_framework_guide("component-renderer-patterns")\` — full IkasComponentRenderer usage`);
681
- parts.push(`- \`get_framework_guide("common-pitfalls")\` — general gotchas`);
682
- parts.push(`- \`get_framework_guide("navigation-patterns")\` — Router.navigate, Router.navigateToPage`);
683
- parts.push(`- \`get_model_guide("<TypeName>")\` — IkasCart, IkasProduct, IkasCustomer shapes`);
762
+ parts.push(`Call \`get_migration_guide("list")\` or \`get_framework_guide("list")\` for the full topic catalog.`);
684
763
  parts.push("");
685
764
  return parts.join("\n");
686
765
  }
@@ -1057,6 +1136,101 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1057
1136
  parts.push(`| \`${oldName}\` | ${oldType} | → | \`${newName}\` | ${newType} | ${notes} |`);
1058
1137
  }
1059
1138
  parts.push("");
1139
+ // Custom Data Decision Callouts — per prop referencing a customData type
1140
+ const customDataPropsForCallouts = (target.props || []).filter((p) => p.type === "CUSTOM" && p.customDataId && customDataMap.has(p.customDataId));
1141
+ if (customDataPropsForCallouts.length > 0) {
1142
+ parts.push(`## Custom Data Decisions to Make`);
1143
+ parts.push("");
1144
+ parts.push(`Each prop below references an old \`customData\` type. Verify the MCP's default against the actual data semantics, then run the CLI command. **Log every decision in MIGRATION.md → \`## Custom Data Decisions\`** with reasoning. See \`get_migration_guide("custom-data-conversion")\` for the heuristic and worked examples.`);
1145
+ parts.push("");
1146
+ for (const p of customDataPropsForCallouts) {
1147
+ const cd = customDataMap.get(p.customDataId);
1148
+ if (!cd)
1149
+ continue;
1150
+ const cdName = cd.typescriptName || cd.name || cd.id || "Unknown";
1151
+ const cdType = cd.type || "?";
1152
+ let shape = "";
1153
+ let shapeKind = "unknown";
1154
+ if (cd.type === "ENUM") {
1155
+ const opts = (cd.enumOptions || []).map((o) => o.value || o.displayName).filter(Boolean);
1156
+ shape = `enum {${opts.slice(0, 6).join(", ")}${opts.length > 6 ? ", ..." : ""}}`;
1157
+ shapeKind = "enum";
1158
+ }
1159
+ else if (cd.type === "DYNAMIC_LIST" || cd.type === "STATIC_LIST") {
1160
+ const first = cd.nestedData?.[0];
1161
+ const fields = (first?.nestedData || []).map((f) => `${f.key || f.name || "?"}: ${f.type || "?"}`);
1162
+ shape = `${cdType} of {${fields.slice(0, 6).join(", ")}}`;
1163
+ shapeKind = "list";
1164
+ }
1165
+ else if (cd.type === "OBJECT") {
1166
+ const fields = (cd.nestedData || []).map((f) => `${f.key || f.name || "?"}: ${f.type || "?"}`);
1167
+ shape = `OBJECT {${fields.slice(0, 6).join(", ")}}`;
1168
+ shapeKind = "record";
1169
+ }
1170
+ else {
1171
+ shape = cdType;
1172
+ }
1173
+ // Build the field source + names list once so we can use it for the lost-fields enumeration
1174
+ // AND for the component-path CLI template.
1175
+ const fieldSource = cd.type === "DYNAMIC_LIST" || cd.type === "STATIC_LIST"
1176
+ ? cd.nestedData?.[0]?.nestedData || []
1177
+ : cd.nestedData || [];
1178
+ const fieldDescriptions = fieldSource
1179
+ .filter((f) => f.key)
1180
+ .map((f) => `\`${f.key}\` (${f.type || "?"})`);
1181
+ parts.push(`### Prop \`${p.name || "?"}\` → customData \`${cdName}\``);
1182
+ parts.push("");
1183
+ parts.push(`**Shape:** \`${shape}\``);
1184
+ parts.push("");
1185
+ if (shapeKind === "enum") {
1186
+ parts.push(`**Default: enum prop.** Flat scalar set; use \`config add-enum\`.`);
1187
+ parts.push("");
1188
+ const enumName = cd.typescriptName || (cd.name ? cd.name.replace(/[^a-zA-Z0-9]/g, "") : "Enum");
1189
+ const enumOptions = (cd.enumOptions || []).reduce((acc, o) => {
1190
+ if (o.displayName && o.value)
1191
+ acc[o.displayName] = o.value;
1192
+ return acc;
1193
+ }, {});
1194
+ parts.push("```bash");
1195
+ parts.push(`npx ikas-component config add-enum --name "${enumName}" --options '${JSON.stringify(enumOptions)}'`);
1196
+ parts.push("```");
1197
+ parts.push("");
1198
+ parts.push(`If you believe this should be a component instead (e.g. each option secretly carries richer data not visible in the customData shape), see \`get_migration_guide("custom-data-conversion")\`.`);
1199
+ parts.push("");
1200
+ }
1201
+ else if (shapeKind === "list" || shapeKind === "record") {
1202
+ parts.push(`**Default: component + COMPONENT_LIST.** Multiple fields per item — a single enum value cannot carry this structure.`);
1203
+ parts.push("");
1204
+ if (fieldDescriptions.length > 0) {
1205
+ parts.push(`⚠️ **Fields you would lose if you flatten this:** ${fieldDescriptions.join(", ")}. Flattening to a simpler prop type drops these from the editor UI permanently. **Do not "simplify for later"** — if the feature genuinely isn't wanted, log that explicitly in MIGRATION.md → \`## Notes\` with reasoning. Otherwise build the component.`);
1206
+ parts.push("");
1207
+ }
1208
+ const compName = cd.typescriptName || (cd.name ? cd.name.replace(/[^a-zA-Z0-9]/g, "") : `${sectionPascal}Item`);
1209
+ const compPropsForCli = [];
1210
+ for (const f of fieldSource) {
1211
+ if (!f.key)
1212
+ continue;
1213
+ let fType = f.type;
1214
+ if (fType === "SLIDER")
1215
+ fType = "NUMBER";
1216
+ else if (fType === "PRODUCT_DETAIL")
1217
+ fType = "PRODUCT";
1218
+ compPropsForCli.push({ name: f.key, displayName: f.name || f.key, type: fType });
1219
+ }
1220
+ parts.push("```bash");
1221
+ parts.push(`npx ikas-component config add-component --name "${compName}" --type component --props '${JSON.stringify(compPropsForCli)}'`);
1222
+ parts.push(`# Then on the parent, set the prop's filteredComponentIds to the new component's id.`);
1223
+ parts.push("```");
1224
+ parts.push("");
1225
+ parts.push(`If you believe this should be an enum despite the structure, see \`get_migration_guide("custom-data-conversion")\`.`);
1226
+ parts.push("");
1227
+ }
1228
+ else {
1229
+ parts.push(`**Unable to classify automatically — you decide.** See \`get_migration_guide("custom-data-conversion")\` for the enum-vs-component heuristic.`);
1230
+ parts.push("");
1231
+ }
1232
+ }
1233
+ }
1060
1234
  // Enums to create first
1061
1235
  if (enumsNeeded.length > 0) {
1062
1236
  parts.push(`## 3. Create Enums FIRST (if not already done)`);
@@ -1222,30 +1396,19 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1222
1396
  parts.push("");
1223
1397
  }
1224
1398
  }
1225
- // Relevant guides
1226
- parts.push(`## ${nextStep + 1}. Relevant Guides (call these for details)`);
1399
+ // Relevant guides — keep terse; LLM can call get_migration_guide("list") for the full catalog
1400
+ parts.push(`## ${nextStep + 1}. Relevant Guides`);
1227
1401
  parts.push("");
1228
1402
  parts.push(`- \`get_migration_guide("react-to-preact")\` — code conversion patterns`);
1229
- parts.push(`- \`get_migration_guide("library-replacements")\` — library vanilla Preact patterns`);
1230
- parts.push(`- \`get_migration_guide("prop-runtime-shapes")\` exact runtime shapes (.data vs .links)`);
1231
- if (children.length > 0) {
1232
- parts.push(`- \`get_migration_guide("component-renderer-limitations")\` — critical COMPONENT_LIST constraints`);
1233
- parts.push(`- \`get_framework_guide("component-renderer-patterns")\` — full IkasComponentRenderer usage`);
1234
- parts.push(`- \`get_migration_example("custom-dynamic-list-to-component-list")\` — concrete example`);
1235
- }
1236
- if (target.isHeader || target.isFooter) {
1237
- parts.push(`- \`get_framework_guide("header-footer-patterns")\` — header/footer specifics`);
1403
+ parts.push(`- \`get_migration_guide("prop-runtime-shapes")\` — exact runtime shapes (\`.data\` vs \`.links\`, etc.)`);
1404
+ if (children.length > 0 || target.isHeader || target.isFooter) {
1405
+ parts.push(`- \`get_framework_guide("header-footer-patterns")\` COMPONENT_LIST + IkasComponentRenderer wiring`);
1238
1406
  }
1239
- parts.push(`- \`get_framework_guide("common-pitfalls")\` — observer rules, common mistakes`);
1240
1407
  parts.push("");
1241
1408
  // Completion
1242
1409
  parts.push(`## ${nextStep + 2}. Mark Complete`);
1243
1410
  parts.push("");
1244
- parts.push(`Once the section builds cleanly with \`npx ikas-component build\`:`);
1245
- parts.push(`1. Edit \`MIGRATION.md\` at the project root`);
1246
- parts.push(`2. Change the checkbox for \`${sectionId}\` from \`[ ]\` to \`[x]\``);
1247
- parts.push(`3. Also mark each child component as \`[x]\``);
1248
- parts.push(`4. Append an entry to the **Session Log** section of \`MIGRATION.md\` noting: libraries replaced, any props added beyond the generated plan, the actual folder name the CLI created (in case it differs from the name you passed — e.g., \`FAQ\` → \`Faq/\`), and any other decisions a future agent should know.`);
1411
+ parts.push(`Once the section builds cleanly with \`npx ikas-component build\`: edit MIGRATION.md → tick \`[x]\` for \`${sectionId}\` and each child component, log any customData decisions under \`## Custom Data Decisions\`, and append a brief entry to \`## Notes\` with anything future sessions should know.`);
1249
1412
  parts.push("");
1250
1413
  return parts.join("\n");
1251
1414
  }
@@ -1271,6 +1434,54 @@ function matchScore(text, query) {
1271
1434
  }
1272
1435
  return score;
1273
1436
  }
1437
+ // Levenshtein edit distance — small DP, fine for the 28 short kebab-case section template names.
1438
+ function levenshtein(a, b) {
1439
+ if (a === b)
1440
+ return 0;
1441
+ if (a.length === 0)
1442
+ return b.length;
1443
+ if (b.length === 0)
1444
+ return a.length;
1445
+ const m = a.length;
1446
+ const n = b.length;
1447
+ const prev = new Array(n + 1);
1448
+ const curr = new Array(n + 1);
1449
+ for (let j = 0; j <= n; j++)
1450
+ prev[j] = j;
1451
+ for (let i = 1; i <= m; i++) {
1452
+ curr[0] = i;
1453
+ for (let j = 1; j <= n; j++) {
1454
+ const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;
1455
+ curr[j] = Math.min(curr[j - 1] + 1, // insertion
1456
+ prev[j] + 1, // deletion
1457
+ prev[j - 1] + cost // substitution
1458
+ );
1459
+ }
1460
+ for (let j = 0; j <= n; j++)
1461
+ prev[j] = curr[j];
1462
+ }
1463
+ return prev[n];
1464
+ }
1465
+ // Suggest up to `max` closest candidates for an unknown input.
1466
+ // Primary: matchScore (substring/word). Fallback: Levenshtein when nothing scores well.
1467
+ function suggestClosestNames(input, candidates, opts) {
1468
+ const min = opts?.min ?? 8;
1469
+ const max = opts?.max ?? 3;
1470
+ const scored = candidates
1471
+ .map((c) => ({ name: c, score: matchScore(c, input) }))
1472
+ .filter((s) => s.score >= min)
1473
+ .sort((a, b) => b.score - a.score);
1474
+ if (scored.length > 0)
1475
+ return scored.slice(0, max).map((s) => s.name);
1476
+ // Levenshtein fallback — tolerate up to ceil(len/3) edits.
1477
+ const maxDistance = Math.max(1, Math.ceil(input.length / 3));
1478
+ const lower = input.toLowerCase();
1479
+ const edits = candidates
1480
+ .map((c) => ({ name: c, d: levenshtein(lower, c.toLowerCase()) }))
1481
+ .filter((s) => s.d <= maxDistance)
1482
+ .sort((a, b) => a.d - b.d);
1483
+ return edits.slice(0, max).map((s) => s.name);
1484
+ }
1274
1485
  function searchFunctions(query) {
1275
1486
  const scored = storefrontData.functions
1276
1487
  .map((fn) => {
@@ -2141,11 +2352,19 @@ server.tool("get_section_template", "Get the root files of a starter section tem
2141
2352
  }
2142
2353
  const normalizedType = normalizeName(sectionType);
2143
2354
  if (!sectionTemplateNames.includes(normalizedType)) {
2355
+ const suggestions = suggestClosestNames(normalizedType, sectionTemplateNames);
2356
+ let suggestionText = "";
2357
+ if (suggestions.length === 1) {
2358
+ suggestionText = ` Did you mean "${suggestions[0]}"?`;
2359
+ }
2360
+ else if (suggestions.length > 1) {
2361
+ suggestionText = ` Did you mean one of: ${suggestions.map((s) => `"${s}"`).join(", ")}?`;
2362
+ }
2144
2363
  return {
2145
2364
  content: [
2146
2365
  {
2147
2366
  type: "text",
2148
- text: `Unknown section type "${sectionType}". Call \`list_section_types()\` to see all ${sectionTemplateNames.length} valid types.`,
2367
+ text: `Unknown section type "${sectionType}".${suggestionText} Call \`list_section_types()\` to see all ${sectionTemplateNames.length} valid types.`,
2149
2368
  },
2150
2369
  ],
2151
2370
  };
@@ -2602,7 +2821,7 @@ const migrationTopicAliases = {
2602
2821
  const migrationTopicKeys = migrationData
2603
2822
  ? Object.keys(migrationData.topics)
2604
2823
  : [];
2605
- server.tool("get_migration_guide", `Get a migration guide for converting old ikas themes to the new code-component system.${migrationTopicKeys.length > 0 ? ` Available topics: ${migrationTopicKeys.join(", ")}. Also supports aliases like "custom", "slider", "react", "libraries", "imports", "settings".` : ""} Call with topic "list" to see all available topics.`, { topic: z.string().describe("Migration topic key, alias, or 'list' to see all topics") }, async ({ topic }) => {
2824
+ server.tool("get_migration_guide", `Get a migration guide for converting old ikas themes to the new code-component system. **Start with \`get_migration_guide("iterative-workflow")\` if you're new to this MCP** — it explains the MCP-vs-LLM responsibility split and the four phases.${migrationTopicKeys.length > 0 ? ` Available topics: ${migrationTopicKeys.join(", ")}. Also supports aliases like "custom", "slider", "react", "libraries", "imports", "settings".` : ""} Call with topic "list" to see all available topics.`, { topic: z.string().describe("Migration topic key, alias, or 'list' to see all topics") }, async ({ topic }) => {
2606
2825
  if (!migrationData) {
2607
2826
  return { content: [{ type: "text", text: "Migration data not available. Ensure data/migration.json exists." }] };
2608
2827
  }
@@ -2686,39 +2905,95 @@ server.tool("get_migration_example", `Get a concrete before/after migration exam
2686
2905
  return { content: [{ type: "text", text: parts.join("\n") }] };
2687
2906
  });
2688
2907
  // Tool: plan_migration
2689
- server.tool("plan_migration", "Generate a complete, resumable migration plan (MIGRATION.md) for converting an old ikas theme to the new code-component system. The LLM should save the returned markdown to <new-project-root>/MIGRATION.md as the source of truth for the entire migration. This is the FIRST tool to call for any multi-section (>5 sections) theme migration. Output includes: extracted CSS variables, font setup, custom enums with CLI commands, shared sub-components (when old_source_dir provided), and an ordered section queue grouped by complexity with canonical component IDs.", {
2690
- theme_json: z.string().describe("Raw JSON content of the old theme.json"),
2691
- project_name: z.string().optional().describe("Target new project name, used to prefix component IDs (default: 'my-theme')"),
2692
- old_source_dir: z.string().optional().describe("Absolute path to the old project's src/ directory. When provided, the tool scans .tsx files to detect shared sub-components used across 3+ components."),
2693
- }, async ({ theme_json, project_name, old_source_dir }) => {
2908
+ server.tool("plan_migration", "Generate the **initial** migration plan and (when `project_root` is provided) write it to <project_root>/MIGRATION.md. **This is the only time the MCP writes that file.** From here, you own it: tick checkboxes as you finish work, log custom-data decisions, scan the old source for atomic components (Button, Input, Card, etc.) that theme.json doesn't see, and append them to MIGRATION.md yourself. theme.json is incomplete by design the MCP can only describe what's listed there. Pass `theme_json_path` for large themes (raw `theme_json` string is supported for backward compat but fails on real-world sizes).", {
2909
+ theme_json: z.string().optional().describe("Raw JSON content of the old theme.json. EITHER this OR theme_json_path is required (not both). For real themes use theme_json_path — raw strings exceed tool/context limits at production sizes."),
2910
+ theme_json_path: z.string().optional().describe("Absolute path to the old theme.json file on disk. Preferred for any real-world theme."),
2911
+ project_name: z.string().optional().describe("Target new project name, used to prefix migration-tracking IDs (default: 'my-theme')"),
2912
+ old_source_dir: z.string().optional().describe("Absolute path to the old project's src/ directory. When provided, the tool scans .tsx files to detect shared sub-components used across 3+ components. This scan is partial — atomic components used by only 1-2 sections will be missed and must be added by the LLM."),
2913
+ project_root: z.string().optional().describe("Absolute path to the new project root. When provided, the MCP writes MIGRATION.md to <project_root>/MIGRATION.md and returns a short summary instead of the full markdown body."),
2914
+ overwrite: z.boolean().optional().describe("If MIGRATION.md already exists at <project_root>/MIGRATION.md and is non-empty, refuse the write unless this is true. Default: false."),
2915
+ }, async ({ theme_json, theme_json_path, project_name, old_source_dir, project_root, overwrite }) => {
2694
2916
  try {
2695
- const parsed = JSON.parse(theme_json);
2917
+ const parsed = resolveThemeJson(theme_json, theme_json_path);
2696
2918
  const projectName = project_name || "my-theme";
2697
2919
  const plan = generateMigrationPlan(parsed, projectName, old_source_dir);
2698
- return { content: [{ type: "text", text: plan }] };
2920
+ if (!project_root) {
2921
+ return { content: [{ type: "text", text: plan }] };
2922
+ }
2923
+ // Write MIGRATION.md to project_root
2924
+ if (!path.isAbsolute(project_root)) {
2925
+ throw new Error(`project_root must be absolute: ${project_root}`);
2926
+ }
2927
+ if (!fs.existsSync(project_root)) {
2928
+ throw new Error(`project_root not found: ${project_root}`);
2929
+ }
2930
+ if (!fs.statSync(project_root).isDirectory()) {
2931
+ throw new Error(`project_root is not a directory: ${project_root}`);
2932
+ }
2933
+ const targetPath = path.join(project_root, "MIGRATION.md");
2934
+ if (fs.existsSync(targetPath)) {
2935
+ const existing = fs.readFileSync(targetPath, "utf-8").trim();
2936
+ if (existing.length > 0 && !overwrite) {
2937
+ return {
2938
+ content: [
2939
+ {
2940
+ type: "text",
2941
+ text: `Refusing to overwrite existing non-empty MIGRATION.md at ${targetPath}. ` +
2942
+ `Pass overwrite: true to replace it, or delete the file first. ` +
2943
+ `If you intended to RESUME an in-progress migration, do not call plan_migration again — read the existing MIGRATION.md and continue from the first unchecked item.`,
2944
+ },
2945
+ ],
2946
+ };
2947
+ }
2948
+ }
2949
+ writeFileAtomic(targetPath, plan);
2950
+ const components = parsed.components || [];
2951
+ const customData = parsed.customData || [];
2952
+ const cssVarCount = parsed.settings?.colors?.length || 0;
2953
+ const fontCount = parsed.settings?.fontFamily?.name ? 1 : 0;
2954
+ const customDataCount = customData.filter((cd) => cd.isRoot).length;
2955
+ const sectionCount = components.length;
2956
+ const summary = [
2957
+ `Wrote initial migration plan to ${targetPath}`,
2958
+ "",
2959
+ `**Summary:**`,
2960
+ `- Sections to migrate: ${sectionCount}`,
2961
+ `- CSS variables: ${cssVarCount}`,
2962
+ `- Fonts: ${fontCount}`,
2963
+ `- Custom data types (deferred decisions, not pre-migrated): ${customDataCount}`,
2964
+ "",
2965
+ `**Next steps for the LLM:**`,
2966
+ `1. Read \`${targetPath}\` start-to-finish. The "READ THIS FIRST" preamble explains your responsibilities.`,
2967
+ `2. Scan the old source directory (\`${old_source_dir || "<old-src>"}\`) for atomic components (Button, Input, Card, icons, etc.) NOT referenced from theme.json. Add them to \`## Source Code Analysis\` in MIGRATION.md.`,
2968
+ `3. Start the Foundation work (CSS variables, fonts, shared sub-components).`,
2969
+ `4. For each section, call \`get_section_migration_plan({theme_json_path, section_name, project_name})\`. The MCP will tell you which props need enum-vs-component decisions.`,
2970
+ `5. Log every custom-data decision in \`## Custom Data Decisions\`. Tick checkboxes as you finish.`,
2971
+ ].join("\n");
2972
+ return { content: [{ type: "text", text: summary }] };
2699
2973
  }
2700
2974
  catch (err) {
2701
2975
  return {
2702
- content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : String(err)}. Make sure theme_json is valid JSON.` }],
2976
+ content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : String(err)}` }],
2703
2977
  };
2704
2978
  }
2705
2979
  });
2706
2980
  // Tool: get_section_migration_plan
2707
- server.tool("get_section_migration_plan", "Get a concrete, actionable migration plan for a single section/component from the old theme. Returns: old source file paths to read, a prop-by-prop conversion table, CLI commands to create children and parent components (with auto-generated types.ts), library replacement hints, and cross-references to relevant framework/migration guides. Use this tool once per section in Phase C of the iterative workflow. Call after `plan_migration` has generated MIGRATION.md.", {
2708
- theme_json: z.string().describe("Raw JSON content of the old theme.json"),
2981
+ server.tool("get_section_migration_plan", "Returns concrete CLI commands and prop conversions for one section. For each prop that references a customData type, you'll see a 'Decide: enum or component?' callout log your decision in MIGRATION.md under `## Custom Data Decisions`. Pass `theme_json_path` for large themes.", {
2982
+ theme_json: z.string().optional().describe("Raw JSON content of the old theme.json. EITHER this OR theme_json_path is required (not both)."),
2983
+ theme_json_path: z.string().optional().describe("Absolute path to the old theme.json file on disk. Preferred for any real-world theme."),
2709
2984
  section_name: z.string().describe("Old component name (e.g. 'Navbar', 'ProductGrid') or dir name, OR the new section ID (e.g. 'my-theme-navbar')"),
2710
2985
  project_name: z.string().optional().describe("Target new project name (must match what was used in plan_migration). Default: 'my-theme'"),
2711
2986
  old_source_dir: z.string().optional().describe("Absolute path to old src/ directory (used to output exact source file paths to read)"),
2712
- }, async ({ theme_json, section_name, project_name, old_source_dir }) => {
2987
+ }, async ({ theme_json, theme_json_path, section_name, project_name, old_source_dir }) => {
2713
2988
  try {
2714
- const parsed = JSON.parse(theme_json);
2989
+ const parsed = resolveThemeJson(theme_json, theme_json_path);
2715
2990
  const projectName = project_name || "my-theme";
2716
2991
  const plan = generateSectionMigrationPlan(parsed, section_name, projectName, old_source_dir);
2717
2992
  return { content: [{ type: "text", text: plan }] };
2718
2993
  }
2719
2994
  catch (err) {
2720
2995
  return {
2721
- content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : String(err)}. Make sure theme_json is valid JSON.` }],
2996
+ content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : String(err)}` }],
2722
2997
  };
2723
2998
  }
2724
2999
  });