figma-console-mcp 1.40.5 → 1.40.7

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.
@@ -4,11 +4,12 @@
4
4
  * and generating platform-agnostic component documentation.
5
5
  */
6
6
  import { z } from "zod";
7
+ import { basename, dirname, isAbsolute, relative } from "node:path";
7
8
  import { extractFileKey, withTimeout } from "./figma-api.js";
8
9
  import { createChildLogger } from "./logger.js";
9
10
  import { EnrichmentService } from "./enrichment/index.js";
10
11
  import { buildDesignHistory, DEFAULT_HISTORY_VERSIONS, MAX_HISTORY_VERSIONS, } from "./history/component-history.js";
11
- import { buildGitHistory, DEFAULT_GIT_LIMIT, MAX_GIT_LIMIT, } from "./history/git-history.js";
12
+ import { blobUrl, buildGitHistory, commitUrl, DEFAULT_GIT_LIMIT, MAX_GIT_LIMIT, resolveSourceRevision, } from "./history/git-history.js";
12
13
  import { formatHistorySection } from "./history/history-formatter.js";
13
14
  const logger = createChildLogger({ component: "design-code-tools" });
14
15
  const enrichmentService = new EnrichmentService(logger);
@@ -323,6 +324,54 @@ export function buildVariableNameMap(variables, collections) {
323
324
  }
324
325
  return out;
325
326
  }
327
+ /**
328
+ * A code path as it may appear in published docs: repo-relative paths as given;
329
+ * absolute local paths made relative to `root` when inside it, else reduced to
330
+ * the file name — never the author's home directory layout.
331
+ */
332
+ export function displayPath(path, root) {
333
+ if (!isAbsolute(path))
334
+ return path;
335
+ if (root) {
336
+ const rel = relative(root, path);
337
+ if (rel && !rel.startsWith("..") && !isAbsolute(rel))
338
+ return rel;
339
+ }
340
+ return basename(path);
341
+ }
342
+ /** The boolean component property that controls this layer's visibility, if any */
343
+ export function visibilityProperty(node) {
344
+ const ref = node?.componentPropertyReferences?.visible;
345
+ return typeof ref === "string" ? stripPropertyIdSuffix(ref) : null;
346
+ }
347
+ /**
348
+ * How to label a layer's visibility: "(hidden — shown when Is Focused = true)"
349
+ * for a hidden layer a boolean property reveals, "(toggled by Show Icon)" for a
350
+ * visible one it can hide, "(hidden)" otherwise. Empty for ordinary layers.
351
+ */
352
+ export function visibilityNote(node) {
353
+ const prop = visibilityProperty(node);
354
+ if (node?.visible === false)
355
+ return prop ? `hidden — shown when ${prop} = true` : "hidden";
356
+ return prop ? `toggled by ${prop}` : "";
357
+ }
358
+ /** The component an instance is made from — its component SET's name for a variant */
359
+ export function componentNameOf(instance, lookup = {}) {
360
+ const comp = lookup.components?.[instance?.componentId];
361
+ if (comp?.componentSetId) {
362
+ const setName = lookup.componentSets?.[comp.componentSetId]?.name;
363
+ if (setName)
364
+ return setName;
365
+ }
366
+ return comp?.name ?? instance?.name ?? "instance";
367
+ }
368
+ /** "Tab Item (Is Selected=True)" — an instance, qualified by its variant */
369
+ export function describeInstance(node) {
370
+ const variantProps = Object.entries(node?.componentProperties ?? {})
371
+ .filter(([, p]) => p?.type === "VARIANT")
372
+ .map(([k, p]) => `${stripPropertyIdSuffix(k)}=${p.value}`);
373
+ return variantProps.length > 0 ? `${node.name} (${variantProps.join(", ")})` : node?.name ?? "instance";
374
+ }
326
375
  /** Strip Figma's internal "#123:4" id suffix from a component property name */
327
376
  function stripPropertyIdSuffix(rawName) {
328
377
  return rawName.replace(/#\d+:\d+$/, "").trim();
@@ -506,13 +555,30 @@ function walkVariantNode(node, data, ctx, depth, maxDepth,
506
555
  /** Label of the icon instance we're inside of, or null when outside any icon */
507
556
  insideIcon,
508
557
  /** An ancestor is hidden, so nothing beneath it paints either */
509
- ancestorHidden = false) {
558
+ ancestorHidden = false,
559
+ /** Property that shows the nearest hidden ancestor, when one does */
560
+ ancestorShownWhen = null,
561
+ /** Nearest nested instance ("Tab Item (Is Selected=True)") */
562
+ owner = null,
563
+ /** Component that nearest nested instance is made from ("Tab Item") */
564
+ ownerComponent = null) {
510
565
  if (depth > maxDepth)
511
566
  return;
512
567
  const isText = node.type === "TEXT";
513
568
  // Hidden layers are COLLECTED, not skipped: a hidden focus ring is real design
514
- // intent. They are labeled so a reader can tell it from what actually renders.
515
- const hidden = ancestorHidden || node.visible === false;
569
+ // intent. They are labeled so a reader can tell it from what actually renders —
570
+ // and, when a boolean property reveals them, with the property that does.
571
+ const hiddenHere = node.visible === false;
572
+ const hidden = ancestorHidden || hiddenHere;
573
+ // A layer inside a nested instance is controlled by THAT component's property,
574
+ // not this one's: "Avatar's notification", never a bare "notification" that
575
+ // reads as if the documented component had it.
576
+ const ownProp = hiddenHere ? visibilityProperty(node) : null;
577
+ // Named by the COMPONENT, not the instance: every tab's "Is Focused" is the Tab
578
+ // Item's property, so "Tab 1" and "Tab 2" must not split it into two facts.
579
+ const shownWhen = ownProp
580
+ ? (ownerComponent ? `${ownerComponent}'s ${ownProp}` : ownProp)
581
+ : hiddenHere ? null : ancestorShownWhen;
516
582
  // Icons are reported once, at the outermost instance — everything beneath it
517
583
  // (vectors, nested instances) is that icon's artwork, not a separate icon.
518
584
  if (insideIcon === null) {
@@ -526,11 +592,15 @@ ancestorHidden = false) {
526
592
  const varId = paint.boundVariables?.color?.id;
527
593
  return {
528
594
  hex: value,
529
- // The variant root's own name is "Size=lg, State=hover" — not a layer name
530
- nodeName: depth === 0 ? "" : node.name || "",
595
+ // The variant root's own name is "Size=lg, State=hover" — not a layer name.
596
+ // A paint on a nested INSTANCE (a tab's underline) names the instance with its
597
+ // variant, so the selected tab's stroke reads as the selected tab's.
598
+ nodeName: depth === 0 ? "" : node.type === "INSTANCE" ? describeInstance(node) : node.name || "",
531
599
  variableId: varId,
532
600
  variableName: varId ? ctx.varNameMap.get(varId) : undefined,
533
601
  ...(hidden ? { hidden: true } : {}),
602
+ ...(hidden && shownWhen ? { shownWhen } : {}),
603
+ ...(owner ? { owner } : {}),
534
604
  };
535
605
  };
536
606
  // Collect fills. Only the variant root (or its full-bleed stand-in) is a
@@ -591,14 +661,15 @@ ancestorHidden = false) {
591
661
  // Recurse into children
592
662
  if (node.children && Array.isArray(node.children)) {
593
663
  for (const child of node.children) {
594
- walkVariantNode(child, data, ctx, depth + 1, maxDepth, insideIcon, hidden);
664
+ const isNestedInstance = node.type === "INSTANCE" && depth > 0;
665
+ walkVariantNode(child, data, ctx, depth + 1, maxDepth, insideIcon, hidden, shownWhen, isNestedInstance ? describeInstance(node) : owner, isNestedInstance ? componentNameOf(node, ctx.lookup) : ownerComponent);
595
666
  }
596
667
  }
597
668
  }
598
669
  /**
599
670
  * Collect typography data from all text nodes in a component tree.
600
671
  */
601
- export function collectTypographyData(node, depth = 0, maxDepth = DOC_TREE_DEPTH, ancestorHidden = false) {
672
+ export function collectTypographyData(node, depth = 0, maxDepth = DOC_TREE_DEPTH, ancestorHidden = false, owner = null) {
602
673
  const results = [];
603
674
  if (depth > maxDepth)
604
675
  return results;
@@ -624,6 +695,7 @@ export function collectTypographyData(node, depth = 0, maxDepth = DOC_TREE_DEPTH
624
695
  lineHeight: s.lineHeightPx || s.fontSize || 14,
625
696
  letterSpacing: s.letterSpacing || 0,
626
697
  ...(hidden ? { hidden: true } : {}),
698
+ ...(owner ? { owner } : {}),
627
699
  // REST: characterStyleOverrides maps characters → styleOverrideTable ids; any
628
700
  // non-zero entry means part of the text departs from `style`
629
701
  ...(Array.isArray(node.characterStyleOverrides) && node.characterStyleOverrides.some((id) => id !== 0)
@@ -632,7 +704,7 @@ export function collectTypographyData(node, depth = 0, maxDepth = DOC_TREE_DEPTH
632
704
  }
633
705
  if (node.children && Array.isArray(node.children)) {
634
706
  for (const child of node.children) {
635
- results.push(...collectTypographyData(child, depth + 1, maxDepth, hidden));
707
+ results.push(...collectTypographyData(child, depth + 1, maxDepth, hidden, node.type === "INSTANCE" && depth > 0 ? describeInstance(node) : owner));
636
708
  }
637
709
  }
638
710
  return results;
@@ -668,6 +740,13 @@ export function collectTypographyAcrossVariants(setNode) {
668
740
  }
669
741
  }
670
742
  }
743
+ // An element name shared by rows with DIFFERENT styles (the selected tab's
744
+ // SemiBold Label vs the others' Regular Label) is qualified by its instance.
745
+ const stylesPerName = new Map();
746
+ for (const key of order) {
747
+ const n = styles.get(key).nodeName;
748
+ stylesPerName.set(n, (stylesPerName.get(n) ?? 0) + 1);
749
+ }
671
750
  return order.map((key) => {
672
751
  const style = styles.get(key);
673
752
  const having = perVariant.filter((pv) => pv.keys.has(key));
@@ -681,7 +760,8 @@ export function collectTypographyAcrossVariants(setNode) {
681
760
  : scopeLabel(having.map((pv) => pv.name), perVariant.length);
682
761
  }
683
762
  // Text layers are often auto-named after their content — keep the table readable
684
- const label = style.nodeName.length > 40 ? `${style.nodeName.slice(0, 40)}…` : style.nodeName;
763
+ const base = style.nodeName.length > 40 ? `${style.nodeName.slice(0, 40)}…` : style.nodeName;
764
+ const label = (stylesPerName.get(style.nodeName) ?? 0) > 1 && style.owner ? `${base} in ${style.owner}` : base;
685
765
  return { style: { ...style, nodeName: label }, scope };
686
766
  });
687
767
  }
@@ -774,7 +854,8 @@ suffix = "") {
774
854
  }
775
855
  // Hidden layers stay in the tree, marked: the color table names them (a hidden
776
856
  // focus ring is real design intent), so the tree must not pretend they don't exist.
777
- const hiddenHint = node.visible === false ? " (hidden)" : "";
857
+ const note = visibilityNote(node);
858
+ const hiddenHint = note ? ` (${note})` : "";
778
859
  lines.push(`${prefix}${connector}${label}${typeHint}${suffix}${hiddenHint}${layoutInfo}${sizingInfo}`);
779
860
  // Recurse into children, collapsing RUNS of siblings that would print
780
861
  // identically (ten nav items, five list rows) into one entry marked ×N. Compared
@@ -800,18 +881,89 @@ suffix = "") {
800
881
  }
801
882
  }
802
883
  /**
803
- * Collect spacing tokens with their bound variable names.
884
+ * The variable a spacing-table property is bound to, read from where Figma
885
+ * actually stores the binding. Radius and per-side stroke weights are bound PER
886
+ * CORNER / PER SIDE (`topLeftRadius`, `strokeBottomWeight`, …) — there is never a
887
+ * `cornerRadius` key in `boundVariables`, even when all four corners share one
888
+ * token — so a lookup by the row's own key reported every radius token as
889
+ * hardcoded.
890
+ *
891
+ * `name` is the display text for the Figma Variable column (undefined = unbound);
892
+ * `signature` identifies the binding for cross-variant comparison.
804
893
  */
894
+ export function resolvePropertyBinding(node, key, varNameMap = new Map()) {
895
+ const bound = node?.boundVariables ?? {};
896
+ // The same binding has two shapes. Plugin API: flat keys (`topLeftRadius`,
897
+ // `strokeBottomWeight`). REST — which this tool reads — nests them:
898
+ // `rectangleCornerRadii.RECTANGLE_TOP_LEFT_CORNER_RADIUS`,
899
+ // `individualStrokeWeights.BORDER_BOTTOM_WEIGHT` (verified against JSON_REST_V1).
900
+ const REST_NESTED = {
901
+ topLeftRadius: ["rectangleCornerRadii", "RECTANGLE_TOP_LEFT_CORNER_RADIUS"],
902
+ topRightRadius: ["rectangleCornerRadii", "RECTANGLE_TOP_RIGHT_CORNER_RADIUS"],
903
+ bottomRightRadius: ["rectangleCornerRadii", "RECTANGLE_BOTTOM_RIGHT_CORNER_RADIUS"],
904
+ bottomLeftRadius: ["rectangleCornerRadii", "RECTANGLE_BOTTOM_LEFT_CORNER_RADIUS"],
905
+ strokeTopWeight: ["individualStrokeWeights", "BORDER_TOP_WEIGHT"],
906
+ strokeRightWeight: ["individualStrokeWeights", "BORDER_RIGHT_WEIGHT"],
907
+ strokeBottomWeight: ["individualStrokeWeights", "BORDER_BOTTOM_WEIGHT"],
908
+ strokeLeftWeight: ["individualStrokeWeights", "BORDER_LEFT_WEIGHT"],
909
+ };
910
+ const idOf = (k) => {
911
+ let b = bound[k];
912
+ if (b === undefined && REST_NESTED[k])
913
+ b = bound[REST_NESTED[k][0]]?.[REST_NESTED[k][1]];
914
+ const id = Array.isArray(b) ? b[0]?.id : b?.id;
915
+ return typeof id === "string" ? id : undefined;
916
+ };
917
+ const nameOf = (id) => varNameMap.get(id) || id;
918
+ let parts = null;
919
+ if (key === "cornerRadius") {
920
+ if (idOf("cornerRadius"))
921
+ parts = null;
922
+ else
923
+ parts = [
924
+ ["top-left", idOf("topLeftRadius")], ["top-right", idOf("topRightRadius")],
925
+ ["bottom-right", idOf("bottomRightRadius")], ["bottom-left", idOf("bottomLeftRadius")],
926
+ ];
927
+ }
928
+ else if (key === "strokeWeight" && !idOf("strokeWeight")) {
929
+ const sides = node?.individualStrokeWeights;
930
+ const all = [
931
+ ["top", "strokeTopWeight", sides?.top ?? 1], ["right", "strokeRightWeight", sides?.right ?? 1],
932
+ ["bottom", "strokeBottomWeight", sides?.bottom ?? 1], ["left", "strokeLeftWeight", sides?.left ?? 1],
933
+ ];
934
+ // Only sides that actually paint a border say anything about it
935
+ parts = all.filter(([, , w]) => w > 0).map(([side, k]) => [side, idOf(k)]);
936
+ }
937
+ if (!parts) {
938
+ const id = idOf(key);
939
+ return id ? { name: nameOf(id), signature: id } : { signature: "" };
940
+ }
941
+ const ids = parts.map(([, id]) => id);
942
+ const boundIds = ids.filter((id) => !!id);
943
+ if (boundIds.length === 0)
944
+ return { signature: "" };
945
+ const signature = parts.map(([p, id]) => `${p}:${id ?? ""}`).join(",");
946
+ if (boundIds.length === ids.length && new Set(boundIds).size === 1) {
947
+ return { name: nameOf(boundIds[0]), signature: boundIds[0] };
948
+ }
949
+ if (new Set(boundIds).size === 1) {
950
+ const on = parts.filter(([, id]) => id).map(([p]) => p);
951
+ return { name: `${nameOf(boundIds[0])} (${on.join(", ")} only)`, signature };
952
+ }
953
+ return { name: parts.map(([p, id]) => `${p}: ${id ? nameOf(id) : "unbound"}`).join(", "), signature };
954
+ }
955
+ /** Collect spacing tokens with their bound variable names. */
805
956
  function collectSpacingTokens(node, varNameMap = new Map()) {
806
957
  const tokens = [];
807
958
  const autoLayout = !!node.layoutMode && node.layoutMode !== "NONE";
808
- const boundVars = node.boundVariables || {};
809
959
  const spacingProps = [
810
960
  { key: "paddingTop", label: "Padding top" },
811
961
  { key: "paddingRight", label: "Padding right" },
812
962
  { key: "paddingBottom", label: "Padding bottom" },
813
963
  { key: "paddingLeft", label: "Padding left" },
814
964
  { key: "itemSpacing", label: "Gap" },
965
+ // Cross-axis gap between wrapped rows (auto-layout WRAP); bound as its own key
966
+ { key: "counterAxisSpacing", label: "Row gap (wrap)" },
815
967
  { key: "cornerRadius", label: "Border radius" },
816
968
  { key: "strokeWeight", label: "Border width" },
817
969
  ];
@@ -827,16 +979,10 @@ function collectSpacingTokens(node, varNameMap = new Map()) {
827
979
  value = node.rectangleCornerRadii.map((r) => `${r}px`).join(" / ");
828
980
  }
829
981
  if (value !== undefined && value !== null) {
830
- const varBinding = boundVars[key];
831
- // Bound spacing variables expose their id as boundVariables[key].id.
832
- // Resolve it to a friendly token name (e.g. `spacing/1`) when the caller
833
- // supplied a name map; fall back to the raw id so the binding stays visible.
834
- const varId = typeof varBinding?.id === "string" ? varBinding.id : undefined;
835
- const varName = varId ? varNameMap.get(varId) || varId : undefined;
836
982
  tokens.push({
837
983
  property: label,
838
984
  value,
839
- variableName: typeof varName === "string" ? varName : undefined,
985
+ variableName: resolvePropertyBinding(node, key, varNameMap).name,
840
986
  });
841
987
  }
842
988
  }
@@ -920,6 +1066,8 @@ const SPACING_COMPARISON_PROPS = [
920
1066
  { key: "paddingBottom", label: "Padding bottom" },
921
1067
  { key: "paddingLeft", label: "Padding left" },
922
1068
  { key: "itemSpacing", label: "Gap" },
1069
+ // Cross-axis gap between wrapped rows (auto-layout WRAP); bound as its own key
1070
+ { key: "counterAxisSpacing", label: "Row gap (wrap)" },
923
1071
  { key: "cornerRadius", label: "Border radius" },
924
1072
  { key: "strokeWeight", label: "Border width" },
925
1073
  ];
@@ -971,15 +1119,13 @@ export function collectSpacingAcrossVariants(setNode, varNameMap = new Map()) {
971
1119
  }
972
1120
  if (key === "strokeWeight")
973
1121
  value = describeStrokeWeight(v);
974
- const varId = typeof v.boundVariables?.[key]?.id === "string"
975
- ? v.boundVariables[key].id
976
- : undefined;
1122
+ const binding = resolvePropertyBinding(v, key, varNameMap);
977
1123
  return {
978
1124
  displayName: cleanVariantName(v.name || "Unknown"),
979
1125
  props: parseVariantProperties(v.name || ""),
980
1126
  value,
981
- variableName: varId ? varNameMap.get(varId) || varId : undefined,
982
- signature: `${value}|${varId ?? ""}`,
1127
+ variableName: binding.name,
1128
+ signature: `${value}|${binding.signature}`,
983
1129
  display: "",
984
1130
  };
985
1131
  });
@@ -1984,7 +2130,11 @@ export function generateFrontmatter(componentName, description, node, componentM
1984
2130
  * pulled. Emitted as its own `figmaVersion` field rather than folded into
1985
2131
  * `version` — that one is the code-side semver and means something different.
1986
2132
  */
1987
- latestDesignVersion) {
2133
+ latestDesignVersion,
2134
+ /** The commit the code-side information was read at (local mode, git repos only) */
2135
+ sourceRevision,
2136
+ /** Directory absolute code paths are shown relative to */
2137
+ sourceRoot) {
1988
2138
  // Only state what is actually known. "stable" / "1.0.0" used to be emitted for
1989
2139
  // every component and read as extracted facts.
1990
2140
  const status = componentMeta?.description?.toLowerCase().includes("deprecated")
@@ -2010,7 +2160,7 @@ latestDesignVersion) {
2010
2160
  `figma: ${fileUrl}`,
2011
2161
  ];
2012
2162
  if (codeInfo?.filePath) {
2013
- lines.push(`source: ${codeInfo.filePath}`);
2163
+ lines.push(`source: ${displayPath(codeInfo.filePath, sourceRoot)}`);
2014
2164
  }
2015
2165
  if (codeInfo?.packageName) {
2016
2166
  lines.push(`package: ${codeInfo.packageName}`);
@@ -2018,6 +2168,15 @@ latestDesignVersion) {
2018
2168
  if (canonicalSource) {
2019
2169
  lines.push(`canonical: ${canonicalSource}`);
2020
2170
  }
2171
+ if (sourceRevision) {
2172
+ // Pins the code side of this page: without it nothing says whether the
2173
+ // code it describes is still current.
2174
+ lines.push(`sourceCommit: ${sourceRevision.commit}`);
2175
+ if (sourceRevision.dirty)
2176
+ lines.push("sourceDirty: true # documented files had uncommitted changes");
2177
+ if (sourceRevision.webBase)
2178
+ lines.push(`sourceRepository: ${sourceRevision.webBase}`);
2179
+ }
2021
2180
  if (latestDesignVersion) {
2022
2181
  // Quote the label — it's user-authored and may contain YAML-significant
2023
2182
  // characters (a colon in "v2: buttons" would otherwise break parsing).
@@ -2035,20 +2194,34 @@ latestDesignVersion) {
2035
2194
  lines.push("---");
2036
2195
  return lines.join("\n");
2037
2196
  }
2038
- export function generateOverviewSection(componentName, description, fileUrl, parsedDesc, codeInfo) {
2197
+ export function generateOverviewSection(componentName, description, fileUrl, parsedDesc, codeInfo,
2198
+ /** Stable web URL for a code path (pinned to a commit), when one can be resolved */
2199
+ sourceUrl,
2200
+ /** Directory absolute paths are shown relative to */
2201
+ sourceRoot) {
2039
2202
  const lines = [
2040
2203
  `# ${componentName}`,
2041
2204
  "",
2042
2205
  ];
2043
- // Build links line
2206
+ // Never publish an absolute local path (it discloses the author's username and
2207
+ // directory layout) — show it relative to the repo when known, else the file name.
2208
+ const shown = (p) => displayPath(p, sourceRoot);
2209
+ // Build links line. A raw repo-relative path is NOT a link — it resolves to
2210
+ // nothing once the page is published anywhere else — so link only what
2211
+ // resolves to a stable URL, and show anything else as a path.
2044
2212
  const links = [`**[Open in Figma](${fileUrl})**`];
2045
2213
  if (codeInfo?.filePath) {
2046
- links.push(`**[View Source](${codeInfo.filePath})**`);
2214
+ const url = sourceUrl?.(codeInfo.filePath);
2215
+ links.push(url ? `**[View Source](${url})**` : `Source: \`${shown(codeInfo.filePath)}\``);
2216
+ }
2217
+ if (codeInfo?.storybookUrl) {
2218
+ links.push(`**[Storybook](${codeInfo.storybookUrl})**`);
2047
2219
  }
2048
- // Add Storybook link if stories file exists in sourceFiles
2220
+ // A stories FILE is the stories' source, not a running Storybook — say so
2049
2221
  const storiesFile = codeInfo?.sourceFiles?.find((f) => f.role.toLowerCase().includes("storybook") || f.role.toLowerCase().includes("stories") || f.path.includes(".stories."));
2050
2222
  if (storiesFile) {
2051
- links.push(`**[Storybook](${storiesFile.path})**`);
2223
+ const url = sourceUrl?.(storiesFile.path);
2224
+ links.push(url ? `**[Stories source](${url})**` : `Stories source: \`${shown(storiesFile.path)}\``);
2052
2225
  }
2053
2226
  lines.push(links.join(" | "));
2054
2227
  lines.push("");
@@ -2144,6 +2317,24 @@ export function generateStatesAndVariantsSection(node, variantData, lookup = {})
2144
2317
  const lines = ["", "## Variants", ""];
2145
2318
  const variants = [];
2146
2319
  const booleans = [];
2320
+ // Which layers each boolean property shows/hides — read from the layers' own
2321
+ // componentPropertyReferences.visible. Nested instances are not descended
2322
+ // into: their references point at THEIR component's properties, not ours.
2323
+ const layersByBoolean = new Map();
2324
+ const collectVisibilityRefs = (n, isRoot) => {
2325
+ const ref = n?.componentPropertyReferences?.visible;
2326
+ if (!isRoot && typeof ref === "string") {
2327
+ if (!layersByBoolean.has(ref))
2328
+ layersByBoolean.set(ref, new Set());
2329
+ layersByBoolean.get(ref).add(n.name);
2330
+ }
2331
+ if (!isRoot && n?.type === "INSTANCE")
2332
+ return;
2333
+ for (const c of n?.children ?? [])
2334
+ collectVisibilityRefs(c, false);
2335
+ };
2336
+ for (const root of node.type === "COMPONENT_SET" ? node.children ?? [] : [node])
2337
+ collectVisibilityRefs(root, true);
2147
2338
  const textProps = [];
2148
2339
  const instanceSwaps = [];
2149
2340
  const slots = [];
@@ -2158,7 +2349,7 @@ export function generateStatesAndVariantsSection(node, variantData, lookup = {})
2158
2349
  });
2159
2350
  }
2160
2351
  else if (def.type === "BOOLEAN") {
2161
- booleans.push({ name, defaultValue: def.defaultValue ?? true });
2352
+ booleans.push({ name, defaultValue: def.defaultValue ?? true, controls: [...(layersByBoolean.get(rawName) ?? [])] });
2162
2353
  }
2163
2354
  else if (def.type === "TEXT") {
2164
2355
  textProps.push({ name, defaultValue: def.defaultValue || "" });
@@ -2257,7 +2448,12 @@ export function generateStatesAndVariantsSection(node, variantData, lookup = {})
2257
2448
  lines.push(`| **${v.name}** | \`${v.values.map((val) => `"${val}"`).join(" \\| ")}\` | \`"${v.defaultValue}"\` | Changes visual treatment |`);
2258
2449
  }
2259
2450
  for (const b of booleans) {
2260
- lines.push(`| **${b.name}** | \`boolean\` | \`${b.defaultValue}\` | Shows/hides ${b.name.toLowerCase()} element |`);
2451
+ // Describe the property by the layer it actually controls; never invent an
2452
+ // element from the property's name ("Is Focused" → "is focused element")
2453
+ const what = b.controls.length > 0
2454
+ ? `Shows/hides ${b.controls.map((l) => `**${l}**`).join(", ")}`
2455
+ : "Boolean toggle";
2456
+ lines.push(`| **${b.name}** | \`boolean\` | \`${b.defaultValue}\` | ${what} |`);
2261
2457
  }
2262
2458
  for (const t of textProps) {
2263
2459
  lines.push(`| **${t.name}** | \`string\` | \`"${t.defaultValue}"\` | Sets ${t.name.toLowerCase()} content |`);
@@ -2353,50 +2549,94 @@ setNode) {
2353
2549
  lines.push("");
2354
2550
  lines.push("| Element | Figma Variable | Value |");
2355
2551
  lines.push("|---------|---------------|-------|");
2356
- for (const vd of variantData) {
2357
- // Same naming as the Variant Matrix: every property value, whatever the
2358
- // properties are called ("Variant=Secondary, Appearance=Critical" → "Secondary / Critical").
2359
- const displayName = cleanVariantName(vd.variantName);
2360
- // Section header for this variant
2361
- lines.push(`| **${displayName}** | | |`);
2362
- const tokenCell = (c) => {
2363
- const varName = c.variableName || (c.variableId ? varNameMap.get(c.variableId) : undefined);
2364
- return varName ? `\`${varName}\`` : "—";
2365
- };
2366
- // Multi-path icons and repeated shapes would otherwise emit identical rows
2367
- const emitted = new Set();
2368
- // Text layers are often auto-named after their content ("Lorem ipsum dolor…")
2369
- const short = (name) => (name.length > 40 ? `${name.slice(0, 40)}…` : name);
2370
- const pushRow = (label, c) => {
2371
- const row = `| ${label}${c.hidden ? " _(hidden layer)_" : ""} | ${tokenCell(c)} | ${c.hex} |`;
2372
- if (emitted.has(row))
2552
+ const tokenCell = (c) => {
2553
+ const varName = c.variableName || (c.variableId ? varNameMap.get(c.variableId) : undefined);
2554
+ return varName ? `\`${varName}\`` : "—";
2555
+ };
2556
+ // Text layers are often auto-named after their content ("Lorem ipsum dolor…")
2557
+ const short = (name) => (name.length > 40 ? `${name.slice(0, 40)}…` : name);
2558
+ const rowText = (r, withVisibility) => {
2559
+ const visibility = !withVisibility ? ""
2560
+ : r.shownWhen ? ` _(hidden — shown when ${r.shownWhen} = true)_`
2561
+ : r.plainHidden ? " _(hidden layer)_" : "";
2562
+ return `| ${r.label}${visibility} | ${r.token} | ${r.value} |`;
2563
+ };
2564
+ // Pass 1 — each variant's rows
2565
+ const perVariant = variantData.map((vd) => {
2566
+ const rows = [];
2567
+ const seen = new Set(); // multi-path icons / repeated shapes → one row
2568
+ const add = (label, c) => {
2569
+ const r = { label, token: tokenCell(c), value: c.hex, ...(c.hidden && c.shownWhen ? { shownWhen: c.shownWhen } : {}), ...(c.hidden && !c.shownWhen ? { plainHidden: true } : {}) };
2570
+ const key = rowText(r, true);
2571
+ if (seen.has(key))
2373
2572
  return;
2374
- emitted.add(row);
2375
- lines.push(row);
2573
+ seen.add(key);
2574
+ rows.push(r);
2575
+ };
2576
+ // Same-named layers with DIFFERENT colors (a selected and an unselected tab's
2577
+ // Label) are told apart by the nested instance they live in
2578
+ const qualify = (list) => {
2579
+ const byName = new Map();
2580
+ for (const e of list) {
2581
+ if (!byName.has(e.nodeName))
2582
+ byName.set(e.nodeName, new Set());
2583
+ byName.get(e.nodeName).add(`${e.hex}|${e.variableName ?? ""}`);
2584
+ }
2585
+ return (e) => ((byName.get(e.nodeName)?.size ?? 0) > 1 && e.owner ? ` in ${e.owner}` : "");
2376
2586
  };
2377
2587
  // Background — the variant's own surface only. Say so when there isn't one.
2378
2588
  const bgLabel = vd.backgroundLayer ? `Background (${vd.backgroundLayer})` : "Background";
2379
- if (vd.fills.length === 0) {
2380
- lines.push("| Background | — | none (transparent) |");
2381
- }
2589
+ if (vd.fills.length === 0)
2590
+ rows.push({ label: "Background", token: "—", value: "none (transparent)" });
2382
2591
  for (const fill of vd.fills)
2383
- pushRow(bgLabel, fill);
2592
+ add(bgLabel, fill);
2384
2593
  // Fills on inner layers — reported under the layer's name, never as a background
2594
+ const fillQ = qualify(vd.descendantFills);
2385
2595
  for (const fill of vd.descendantFills)
2386
- pushRow(`Fill (${fill.nodeName})`, fill);
2387
- // Icon artwork colors
2596
+ add(`Fill (${fill.nodeName}${fillQ(fill)})`, fill);
2388
2597
  for (const c of vd.iconColors)
2389
- pushRow(c.iconLabel ? `Icon (${c.iconLabel})` : "Icon", c);
2390
- // Text colors
2598
+ add(c.iconLabel ? `Icon (${c.iconLabel})` : "Icon", c);
2599
+ const textQ = qualify(vd.textColors);
2391
2600
  for (const text of vd.textColors)
2392
- pushRow(`Text (${short(text.nodeName)})`, text);
2393
- // Strokes — through the same writer, so a visible underline and a hidden
2394
- // focus ring sharing one color don't print as two indistinguishable rows
2601
+ add(`Text (${short(text.nodeName)}${textQ(text)})`, text);
2602
+ // Strokes go through the same writer, so a visible underline and a hidden focus
2603
+ // ring sharing one color don't print as two indistinguishable rows
2604
+ const strokeQ = qualify(vd.strokes);
2395
2605
  for (const stroke of vd.strokes)
2396
- pushRow(stroke.nodeName ? `Stroke (${stroke.nodeName})` : "Stroke", stroke);
2606
+ add(stroke.nodeName ? `Stroke (${stroke.nodeName}${strokeQ(stroke)})` : "Stroke", stroke);
2397
2607
  // Shadows, blurs, opacity — dropping them would imply the component is flat
2398
2608
  for (const fx of vd.effects)
2399
- pushRow(fx.nodeName ? `Effect (${fx.nodeName})` : "Effect", fx);
2609
+ add(fx.nodeName ? `Effect (${fx.nodeName})` : "Effect", fx);
2610
+ return { name: cleanVariantName(vd.variantName), rows };
2611
+ });
2612
+ // Pass 2 — a layer a boolean property reveals, identical in EVERY variant, is a
2613
+ // fact about the property, not about each variant: print it once, under the
2614
+ // property. If it differs between variants, it stays with each variant.
2615
+ const hoisted = new Map();
2616
+ const hoistedKeys = new Set();
2617
+ if (perVariant.length > 1) {
2618
+ for (const r of perVariant[0].rows) {
2619
+ if (!r.shownWhen)
2620
+ continue;
2621
+ const key = rowText(r, true);
2622
+ if (!perVariant.every((pv) => pv.rows.some((x) => rowText(x, true) === key)))
2623
+ continue;
2624
+ hoistedKeys.add(key);
2625
+ if (!hoisted.has(r.shownWhen))
2626
+ hoisted.set(r.shownWhen, []);
2627
+ hoisted.get(r.shownWhen).push(r);
2628
+ }
2629
+ }
2630
+ for (const pv of perVariant) {
2631
+ lines.push(`| **${pv.name}** | | |`);
2632
+ for (const r of pv.rows)
2633
+ if (!hoistedKeys.has(rowText(r, true)))
2634
+ lines.push(rowText(r, true));
2635
+ }
2636
+ for (const [prop, rows] of hoisted) {
2637
+ lines.push(`| **When ${prop} = true** _(every variant; hidden otherwise)_ | | |`);
2638
+ for (const r of rows)
2639
+ lines.push(rowText(r, false));
2400
2640
  }
2401
2641
  lines.push("");
2402
2642
  }
@@ -2492,7 +2732,7 @@ setNode) {
2492
2732
  }
2493
2733
  return lines.join("\n");
2494
2734
  }
2495
- function generateImplementationSection(codeInfo) {
2735
+ function generateImplementationSection(codeInfo, sourceRoot) {
2496
2736
  if (!codeInfo)
2497
2737
  return "";
2498
2738
  const lines = ["", "## Implementation", ""];
@@ -2503,7 +2743,7 @@ function generateImplementationSection(codeInfo) {
2503
2743
  lines.push("| File | Role | Variants |");
2504
2744
  lines.push("|------|------|----------|");
2505
2745
  for (const sf of codeInfo.sourceFiles) {
2506
- lines.push(`| \`${sf.path}\` | ${sf.role} | ${sf.variants ?? "—"} |`);
2746
+ lines.push(`| \`${displayPath(sf.path, sourceRoot)}\` | ${sf.role} | ${sf.variants ?? "—"} |`);
2507
2747
  }
2508
2748
  lines.push("");
2509
2749
  }
@@ -2820,6 +3060,9 @@ export function generateTypographySection(node) {
2820
3060
  if (seen.has(key))
2821
3061
  continue;
2822
3062
  seen.add(key);
3063
+ const sameName = textStyles.filter((o) => o.nodeName === ts.nodeName && `${o.fontFamily}:${o.fontWeight}:${o.fontSize}:${o.lineHeight}` !== `${ts.fontFamily}:${ts.fontWeight}:${ts.fontSize}:${ts.lineHeight}`);
3064
+ if (sameName.length > 0 && ts.owner)
3065
+ ts.nodeName = `${ts.nodeName} in ${ts.owner}`;
2823
3066
  lines.push(`| ${ts.nodeName}${ts.hidden ? " _(hidden layer)_" : ""}${ts.mixed ? " _(mixed styles — base style shown)_" : ""} | ${ts.fontFamily} | ${ts.fontWeightName} (${ts.fontWeight}) | ${ts.fontSize}px | ${ts.lineHeight}px | ${ts.letterSpacing === 0 ? "0" : `${ts.letterSpacing}px`} |`);
2824
3067
  }
2825
3068
  lines.push("");
@@ -2846,63 +3089,122 @@ function generateContentGuidelinesSection(parsedDesc) {
2846
3089
  return lines.join("\n");
2847
3090
  }
2848
3091
  export function generateParitySection(node, codeInfo) {
2849
- const lines = ["", "## Design-Code Parity", ""];
2850
- // Variant coverage — compare each Figma variant PROPERTY with the code prop of
2851
- // the same name, value by value. (This used to look only for a property
2852
- // literally named "Variant" and otherwise captured the first property's NAME —
2853
- // so a Size × State set was reported as having a Figma-only variant "Size".)
3092
+ // Names match ignoring case/punctuation and a leading is/has, so Figma's
3093
+ // "Is Selected" meets code's `isSelected` / `selected`.
2854
3094
  const normalize = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, "");
3095
+ const keysFor = (name) => {
3096
+ const n = normalize(name);
3097
+ const stripped = n.replace(/^(is|has)(?=[a-z0-9])/, "");
3098
+ return stripped && stripped !== n ? [n, stripped] : [n];
3099
+ };
3100
+ const BOOL = /^(true|false)$/i;
2855
3101
  const figmaProps = new Map();
2856
3102
  if (node.type === "COMPONENT_SET" && node.children) {
2857
3103
  for (const child of node.children) {
2858
3104
  for (const [propName, value] of parseVariantProperties(child.name || "")) {
2859
3105
  const key = normalize(propName);
2860
3106
  if (!figmaProps.has(key))
2861
- figmaProps.set(key, { name: propName, values: new Map() });
3107
+ figmaProps.set(key, { name: propName, kind: "values", values: new Map() });
2862
3108
  figmaProps.get(key).values.set(value.toLowerCase(), value);
2863
3109
  }
2864
3110
  }
2865
3111
  }
2866
- // Code props whose type is a union of string literals: "sm" | "md" | 'lg'
2867
- const codeProps = new Map();
3112
+ // A variant property whose only values are True/False is a boolean in all but name
3113
+ for (const p of figmaProps.values()) {
3114
+ if (p.values.size > 0 && [...p.values.keys()].every((v) => BOOL.test(v)))
3115
+ p.kind = "boolean";
3116
+ }
3117
+ // BOOLEAN component properties (show/hide toggles) are booleans too
3118
+ for (const [rawName, def] of Object.entries(node.componentPropertyDefinitions ?? {})) {
3119
+ if (def?.type !== "BOOLEAN")
3120
+ continue;
3121
+ const name = stripPropertyIdSuffix(rawName);
3122
+ if (!figmaProps.has(normalize(name)))
3123
+ figmaProps.set(normalize(name), { name, kind: "boolean", values: new Map() });
3124
+ }
3125
+ const codeProps = [];
2868
3126
  for (const prop of codeInfo.props ?? []) {
2869
- const literals = prop.type?.match(/["']([^"']+)["']/g);
2870
- if (!literals)
3127
+ const type = prop.type ?? "";
3128
+ const literals = type.match(/["']([^"']+)["']/g);
3129
+ const isBoolean = /^\s*boolean\s*(\|\s*(undefined|null)\s*)*$/i.test(type)
3130
+ || /^\s*(true\s*\|\s*false|false\s*\|\s*true)\s*(\|\s*(undefined|null)\s*)*$/i.test(type);
3131
+ if (isBoolean) {
3132
+ codeProps.push({ name: prop.name, kind: "boolean", values: new Map() });
3133
+ }
3134
+ else if (literals) {
3135
+ const values = new Map();
3136
+ for (const m of literals) {
3137
+ const raw = m.replace(/["']/g, "");
3138
+ values.set(raw.toLowerCase(), raw);
3139
+ }
3140
+ codeProps.push({ name: prop.name, kind: "values", values });
3141
+ }
3142
+ }
3143
+ // Pair each Figma property with at most one code prop, exact name first
3144
+ const pairs = [];
3145
+ const usedCode = new Set();
3146
+ for (const fp of figmaProps.values()) {
3147
+ const fKeys = keysFor(fp.name);
3148
+ const match = codeProps.find((cp) => !usedCode.has(cp) && normalize(cp.name) === fKeys[0])
3149
+ ?? codeProps.find((cp) => !usedCode.has(cp) && keysFor(cp.name).some((k) => fKeys.includes(k)));
3150
+ if (match) {
3151
+ usedCode.add(match);
3152
+ pairs.push({ figma: fp, code: match });
3153
+ }
3154
+ }
3155
+ const unmatchedFigma = [...figmaProps.values()].filter((fp) => !pairs.some((p) => p.figma === fp));
3156
+ const unmatchedCode = codeProps.filter((cp) => !usedCode.has(cp));
3157
+ // Long-standing behavior: a "variant" prop on one side is compared even with no counterpart
3158
+ for (const fp of unmatchedFigma.filter((p) => normalize(p.name) === "variant" && p.kind === "values"))
3159
+ pairs.push({ figma: fp });
3160
+ for (const cp of unmatchedCode.filter((p) => normalize(p.name) === "variant" && p.kind === "values"))
3161
+ pairs.push({ code: cp });
3162
+ const rows = [];
3163
+ const labelProperty = pairs.length > 1 || (pairs[0] && normalize((pairs[0].figma ?? pairs[0].code).name) !== "variant");
3164
+ for (const { figma, code } of pairs) {
3165
+ const propLabel = figma?.name || code?.name || "";
3166
+ const bothBoolean = figma?.kind === "boolean" && code?.kind === "boolean";
3167
+ if (bothBoolean) {
3168
+ rows.push(`| ${figma.name} ↔ \`${code.name}\` | Yes | Yes | In sync (boolean) |`);
2871
3169
  continue;
2872
- const values = new Map();
2873
- for (const m of literals) {
2874
- const raw = m.replace(/["']/g, "");
2875
- values.set(raw.toLowerCase(), raw);
2876
- }
2877
- codeProps.set(normalize(prop.name), { name: prop.name, values });
2878
- }
2879
- // Compare properties present on BOTH sides, plus "variant" when either side has
2880
- // it (the long-standing behavior). A property with no counterpart gets no
2881
- // claim at all — a boolean in code and a True/False variant in Figma aren't comparable here.
2882
- const compared = [...figmaProps.keys()].filter((k) => codeProps.has(k));
2883
- if (!compared.includes("variant") && (figmaProps.has("variant") || codeProps.has("variant")))
2884
- compared.push("variant");
2885
- if (compared.length > 0) {
2886
- const labelProperty = compared.length > 1 || compared[0] !== "variant";
2887
- lines.push("### Variant Coverage");
2888
- lines.push("");
3170
+ }
3171
+ if (figma && code && figma.kind !== code.kind && !(figma.values.size > 0 && code.values.size > 0)) {
3172
+ rows.push(`| ${figma.name} ↔ \`${code.name}\` | Yes | Yes | **Type mismatch** — Figma ${figma.kind === "boolean" ? "True/False" : "named values"}, code \`${codeInfo.props?.find((p) => p.name === code.name)?.type ?? code.kind}\` |`);
3173
+ continue;
3174
+ }
3175
+ const allValues = new Set([...(figma?.values.keys() ?? []), ...(code?.values.keys() ?? [])]);
3176
+ for (const valueKey of allValues) {
3177
+ const inFigma = figma?.values.has(valueKey) ?? false;
3178
+ const inCode = code?.values.has(valueKey) ?? false;
3179
+ const display = figma?.values.get(valueKey) || code?.values.get(valueKey) || valueKey;
3180
+ const status = inFigma && inCode
3181
+ ? "In sync"
3182
+ : inFigma ? "Figma-only — needs code variant" : "Code-only — needs Figma variant";
3183
+ rows.push(`| ${labelProperty ? `${propLabel}: ${display}` : display} | ${inFigma ? "Yes" : "**No**"} | ${inCode ? "Yes" : "**No**"} | ${status} |`);
3184
+ }
3185
+ }
3186
+ const leftoverFigma = unmatchedFigma.filter((p) => !pairs.some((x) => x.figma === p));
3187
+ const leftoverCode = unmatchedCode.filter((p) => !pairs.some((x) => x.code === p));
3188
+ // Nothing on either side that could be compared: leave the section out rather
3189
+ // than print a heading with nothing under it.
3190
+ if (rows.length === 0 && leftoverFigma.length === 0 && leftoverCode.length === 0)
3191
+ return "";
3192
+ const lines = ["", "## Design-Code Parity", ""];
3193
+ if (rows.length > 0) {
3194
+ lines.push("### Variant Coverage", "");
2889
3195
  lines.push("| Variant | In Figma | In Code | Status |");
2890
3196
  lines.push("|---------|----------|---------|--------|");
2891
- for (const key of compared) {
2892
- const figma = figmaProps.get(key);
2893
- const code = codeProps.get(key);
2894
- const propLabel = figma?.name || code?.name || key;
2895
- const allValues = new Set([...(figma?.values.keys() ?? []), ...(code?.values.keys() ?? [])]);
2896
- for (const valueKey of allValues) {
2897
- const inFigma = figma?.values.has(valueKey) ?? false;
2898
- const inCode = code?.values.has(valueKey) ?? false;
2899
- const display = figma?.values.get(valueKey) || code?.values.get(valueKey) || valueKey;
2900
- const status = inFigma && inCode
2901
- ? "In sync"
2902
- : inFigma ? "Figma-only — needs code variant" : "Code-only — needs Figma variant";
2903
- lines.push(`| ${labelProperty ? `${propLabel}: ${display}` : display} | ${inFigma ? "Yes" : "**No**"} | ${inCode ? "Yes" : "**No**"} | ${status} |`);
2904
- }
2905
- }
3197
+ lines.push(...rows, "");
3198
+ }
3199
+ else {
3200
+ lines.push("_No Figma property matched a code prop by name and type, so nothing was compared._", "");
3201
+ }
3202
+ if (leftoverFigma.length > 0 || leftoverCode.length > 0) {
3203
+ lines.push("**Not compared** — no counterpart on the other side:", "");
3204
+ if (leftoverFigma.length > 0)
3205
+ lines.push(`- Figma: ${leftoverFigma.map((p) => `${p.name} (${p.kind === "boolean" ? "True/False" : [...p.values.values()].join(" | ")})`).join(", ")}`);
3206
+ if (leftoverCode.length > 0)
3207
+ lines.push(`- Code: ${leftoverCode.map((p) => `\`${p.name}\``).join(", ")}`);
2906
3208
  lines.push("");
2907
3209
  }
2908
3210
  return lines.join("\n");
@@ -3042,6 +3344,7 @@ const codeDocInfoSchema = z.object({
3042
3344
  changes: z.string(),
3043
3345
  })).optional().describe("Changelog entries"),
3044
3346
  filePath: z.string().optional().describe("Component file path"),
3347
+ storybookUrl: z.string().optional().describe("URL of a running Storybook (or the component's story) to link from the doc. Without it, a stories file in sourceFiles is linked as \"Stories source\", not \"Storybook\"."),
3045
3348
  packageName: z.string().optional().describe("Package name"),
3046
3349
  variantDefinition: z.string().optional().describe("CVA or variant definition code block"),
3047
3350
  subComponents: z.array(z.object({
@@ -3566,6 +3869,30 @@ export function registerDesignCodeTools(server, getFigmaAPI, getCurrentUrl, vari
3566
3869
  // in frontmatter as design provenance — deliberately NOT merged into
3567
3870
  // the code-side semver `version` field, which means something else.
3568
3871
  const latestDesignVersion = designHistory?.entries[0] ?? null;
3872
+ // Pin the code side to a commit and build stable links (local mode only —
3873
+ // the Worker has no filesystem). Only files git actually TRACKS get links:
3874
+ // code read from an installed package (node_modules) or an unrelated
3875
+ // working directory is shown as a path, never as a guessed URL.
3876
+ let sourceRevision = null;
3877
+ const codePaths = [
3878
+ ...(codeInfo?.filePath ? [codeInfo.filePath] : []),
3879
+ ...(codeInfo?.sourceFiles?.map((f) => f.path) ?? []),
3880
+ ];
3881
+ // Which repo? An explicit history.repoPath, or the repo that CONTAINS an
3882
+ // absolute path. Never the server's own working directory: relative paths
3883
+ // resolved there could match a same-named file in an unrelated project
3884
+ // and pin the page to the wrong history.
3885
+ const firstAbsolute = codePaths.find((p) => isAbsolute(p));
3886
+ const repoPathForLinks = history?.repoPath ?? (firstAbsolute ? dirname(firstAbsolute) : undefined);
3887
+ if (!isRemoteMode && codePaths.length > 0 && repoPathForLinks) {
3888
+ sourceRevision = await resolveSourceRevision({ paths: codePaths, repoPath: repoPathForLinks }).catch(() => null);
3889
+ if (sourceRevision && sourceRevision.tracked.size === 0)
3890
+ sourceRevision = null;
3891
+ }
3892
+ const sourceUrl = (path) => {
3893
+ const rel = sourceRevision?.tracked.get(path);
3894
+ return rel && sourceRevision ? blobUrl(sourceRevision, rel) : null;
3895
+ };
3569
3896
  // Resolve sections with defaults
3570
3897
  const s = {
3571
3898
  overview: true,
@@ -3587,11 +3914,11 @@ export function registerDesignCodeTools(server, getFigmaAPI, getCurrentUrl, vari
3587
3914
  const includedSections = [];
3588
3915
  if (includeFrontmatter) {
3589
3916
  const atomicLevel = await detectAtomicLevel(api, fileKey, nodeId, setInfo.setNodeId, componentMeta, allComponentsMeta);
3590
- parts.push(generateFrontmatter(componentName, description, node, componentMeta, fileUrl_, codeInfo, canonicalSource, atomicLevel, latestDesignVersion));
3917
+ parts.push(generateFrontmatter(componentName, description, node, componentMeta, fileUrl_, codeInfo, canonicalSource, atomicLevel, latestDesignVersion, sourceRevision, repoPathForLinks));
3591
3918
  parts.push("");
3592
3919
  }
3593
3920
  if (s.overview) {
3594
- parts.push(generateOverviewSection(componentName, description, fileUrl_, parsedDesc, codeInfo));
3921
+ parts.push(generateOverviewSection(componentName, description, fileUrl_, parsedDesc, codeInfo, sourceUrl, repoPathForLinks));
3595
3922
  includedSections.push("overview");
3596
3923
  }
3597
3924
  if (s.anatomy) {
@@ -3627,7 +3954,7 @@ export function registerDesignCodeTools(server, getFigmaAPI, getCurrentUrl, vari
3627
3954
  }
3628
3955
  }
3629
3956
  if (s.implementation && codeInfo) {
3630
- parts.push(generateImplementationSection(codeInfo));
3957
+ parts.push(generateImplementationSection(codeInfo, repoPathForLinks ?? history?.repoPath));
3631
3958
  includedSections.push("implementation");
3632
3959
  }
3633
3960
  if (s.accessibility) {
@@ -3640,7 +3967,8 @@ export function registerDesignCodeTools(server, getFigmaAPI, getCurrentUrl, vari
3640
3967
  includedSections.push("designAnnotations");
3641
3968
  }
3642
3969
  if (s.parity && hasCodeInfo && hasFigmaData && codeInfo) {
3643
- const paritySection = generateParitySection(node, codeInfo);
3970
+ // nodeForVariants carries the SET's property definitions when a single variant was requested
3971
+ const paritySection = generateParitySection(nodeForVariants, codeInfo);
3644
3972
  if (paritySection) {
3645
3973
  parts.push(paritySection);
3646
3974
  includedSections.push("parity");
@@ -3656,6 +3984,8 @@ export function registerDesignCodeTools(server, getFigmaAPI, getCurrentUrl, vari
3656
3984
  componentName,
3657
3985
  design: designHistory,
3658
3986
  git: gitHistory,
3987
+ commitLink: (sha) => (sourceRevision ? commitUrl(sourceRevision, sha) : null),
3988
+ showPath: (p) => displayPath(p, gitHistory?._meta.repo_root ?? repoPathForLinks),
3659
3989
  manual: codeInfo?.changelog ?? null,
3660
3990
  });
3661
3991
  if (historySection.trim()) {