shilp-sutra
CLAUDE.md4 starsChanged 4 months agoMITView on GitHub
Other AI agents (Cursor, Copilot, Codex, Aider): read AGENTS.md — generic agent contract. Consumer-facing setup recipes: packages/core/docs/recipes/ — ship inside the npm tarball, available at node_modules/@devalok/shilp-sutra/docs/recipes/ once installed. This file (CLAUDE.md) is the maintainer-facing repo guide loaded by Claude Code when working IN this repository. It is not shipped to consumers. CSS-first, no JS preset. Consumers do: Token source-of-truth layout (at packages/core/src/tokens/): - primitives.css — private palette in :root { } + .dark { } (NOT @theme) - semantic.css —…
- Installs packages
In this repository4 other files it gives its agents.
- AGENTS.mdAGENTS.md
- finish-bar-auditSkill
- shilp-sutraSkill
- shilp-sutraSkill
The file
We split this CLAUDE.md into the rules it gives an agent
12 rules. About 0 are common, 4 are distinctive, and 8 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈4
Distinctive · estimate
This author's own choices. Worth a look.
8
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 364
Every shadow the CVA references (shadow-raised, shadow-brand, etc.) must exist as a named Effect Style
- Distinctive: line 376
Publishing: Only the user can click "Publish library" in Figma — flag it explicitly, don't assume done without it.
- Very specific: line 397
Every component MUST use the correct surface level.
- Very specific: line 418
The rule: if a component renders as a card/widget/panel on the page, its background is bg-surface-panel, NOT bg-surface-base.
- Very specific: line 485
When CI is broken: Use /publish-release's emergency manual runbook.
- Distinctive: line 508
Before writing "non-breaking" / "type widening only" on any prop-type change, classify the direction per prop, against the prop's PREVIOUS …
- Very specific: line 516
When unsure whether old ⊂ new or new ⊂ old, write a @ts-expect-error/expectTypeOf probe with a value valid under the old type (a …
- Very specific: line 530
When the Storybook dev server is running (pnpm dev), an MCP server at localhost:6006/mcp provides AI agents with:
- Very specific: line 543
Write: report_issue (files a public agent-feedback issue).
- Distinctive: line 558
You do NOT check or act on these automatically: Only act when triggered:
- Very specific: line 562
Read all open issues labeled karm-ai-agent-feedback OR mcp-submitted on devalok-design/shilp-sutra.
- Distinctive: line 572
Use the DS Notice format:
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
shilp-sutra Design System
Other AI agents (Cursor, Copilot, Codex, Aider): read
AGENTS.md— generic agent contract. Consumer-facing setup recipes:packages/core/docs/recipes/— ship inside the npm tarball, available atnode_modules/@devalok/shilp-sutra/docs/recipes/once installed.This file (
CLAUDE.md) is the maintainer-facing repo guide loaded by Claude Code when working IN this repository. It is not shipped to consumers.
Quick Reference
- Monorepo: pnpm workspaces —
packages/core,packages/brand - Stack: React 19, TypeScript 6, Vite 8 (Rolldown), Tailwind 4 (CSS-first via
@theme), CVA - Test:
pnpm test(Vitest + RTL + vitest-axe) - Build:
pnpm build(per-package) - Lint:
pnpm lint - Typecheck:
pnpm typecheck
Tailwind 4 Architecture (0.37.0+)
CSS-first, no JS preset. Consumers do:
@import "tailwindcss";
@import "@devalok/shilp-sutra/css";Token source-of-truth layout (at packages/core/src/tokens/):
primitives.css— private palette in:root { }+.dark { }(NOT@theme)semantic.css— public utility-generating tokens in@theme { }+.dark { }overrides +@media (forced-colors)typography.css—@font-facedeclarationstypography-semantic.css—--text-ds-*,--leading-ds-*in@themebase.css—@layer base { @property + iOS @media fix }animations.css—@keyframes+@theme { --animate-* }utilities.css—@utilityblocks (typography composites, focus-ring, touch-target, safe-area, z-layer, duration names)variants.css—@custom-variant dark (&:where(.dark *));shilp-sutra.css— consumer entry: imports all above +@source "../../dist"+@source "@devalok/shilp-sutra"
Namespace rules:
- Spacing is
--spacing-ds-*(generatesp-ds-03, notp-3) — avoids collision with consumer numeric spacing - Typography is
--text-ds-*/--leading-ds-*— avoids collision with consumer text sizes --radius(unsuffixed) generates barerounded;--radius-ds-*generatesrounded-ds-lgetc.--z-*and--duration-*do NOT auto-generate utilities (TW4 has no such namespaces); they live in:rootand get explicit@utility z-popover,@utility duration-fast-01blocks- Bare
shadowclass is dead in TW4 — always useshadow-raised,shadow-overlay, etc. w-[--var]is dead — usew-(--var)(TW4 shorthand)bg-gradient-to-*is dead — usebg-linear-to-*theme(spacing.N)inside arbitrary values is dead — use the literal value
Peer dependencies:
framer-motion ^12— REQUIRED peer. Module-scoped React contexts (MotionConfig, AnimatePresence, LayoutGroup) must be single-copy; peer-declaration forces consumer dedupe.sonner ^2— optional peer (only needed if consumer renders a<Toaster />).tailwindcss ^4.0.0— tightened from^3.4.0 || ^4.0.0in 0.37.@tiptap/*×12 — optional peers, REQUIRED as of 0.56.0 for RichTextEditor / RichChatInput (see externalization rule below).prosemirror-*is never imported directly — route through@tiptap/pm/stateso it rides the existing@tiptap/pmpeer.
Runtime dependencies (0.56.0): class-variance-authority, clsx, tailwind-merge, tw-animate-css. That's the whole list — keep it that way. use-sync-external-store was removed in 0.56.0: React 18+ has the hook built in (primitives/_internal/react-use-is-hydrated.ts calls it directly) and the dep existed only to feed the bundled tiptap chunk.
Build externalization (vite.config.ts rollupOptions.external):
framer-motion,sonner— bundling splits consumer React contexts.@tiptap/*,prosemirror-*(0.56.0) — were declared as optional peers AND bundled (641 KB chunk). A consumer following our own peer instructions ran two ProseMirror copies; plugin keys are module-scoped, so the copies couldn't see each other's plugins.clsx,class-variance-authority,tailwind-merge(0.56.0) — they leak into our published.d.ts(25 files referenceVariantProps; cva's inferred return type embedsclass-variance-authority/types#ClassProp;utils.d.tsimportsClassValue), so consumers must resolve them fortscregardless. Bundling on top of declaring shipped the code twice and blocked dedupe.
HARD RULE: never declare a package as a peer AND bundle it
Pick one. Declared-and-bundled is the bug that shipped twice (framer-motion/sonner in 0.37, tiptap through 0.55): the component works for consumers who ignore the peer instruction, and breaks subtly for the ones who follow it, because two copies of a module-scoped context / plugin registry can't see each other. If it leaks into our .d.ts, it must be declared and external. If it's an internal implementation detail, it must be bundled and undeclared. derive-peer-map.mjs --check (a release gate) enforces the recipe tables against the externalization set — but it can't catch "bundled AND declared", so that one is on you.
No install scripts (0.56.0). packages/core/package.json has no postinstall and must not regain one. The old one printed a banner and wrote a project-scoped .mcp.json into the consumer's repo. Writing files outside our own directory on install — especially to point someone's agent at our server — is what npm's install-script blocking exists to stop, and it cost us trust publicly. MCP setup is an opt-in README command.
Never re-introduce:
- JS preset (
packages/core/src/tailwind/preset.tsis a deprecated no-op stub, scheduled for removal in 0.38) @configdirective in consumer CSStailwind.config.tsat repo root (deleted in 0.37)process.getBuiltinModule/createRequirepatches ininject-use-client.mjs(Phase 0 spike made the bridge unnecessary)
Design Preferences (default to these)
Prefer variant="soft" over variant="outline" for non-primary Button actions. Soft (tinted step-3 bg, step-11 text, no visible border) feels warmer, brand-consistent, and reads better in data-dense UIs than outline's bordered-transparent look. When generating examples, docs, stories, or writing new screens, default to soft for secondary actions and use outline only when:
- The button sits on a colored or surface-panel background where soft's tint would disappear
- A toolbar/icon-dense context where soft would feel visually heavy
- Paired adjacent to a primary action where you want a clear hierarchy that outline provides
This applies to: Button, SplitButton, and anywhere else variant="outline" | "soft" is a choice. It does NOT override explicit design decisions already in existing components.
Figma Library (2026-08-18 rebuild)
Read these before touching the Figma file — they supersede the checklist below:
docs/plans/2026-08-18-figma-library-build-plan.md— architecture and decisions (D1–D23)docs/plans/implemented/2026-08-18-figma-build-playbook.md— API traps, layout tricks, per-component audit, verification protocoldocs/plans/implemented/2026-08-18-figma-foundations-spec.md— every collection, mode and variable as builtdocs/plans/2026-08-18-figma-port-retrospective.md— how the work went, the full bug ledger, and what caught whatdocs/plans/implemented/2026-08-19-figma-components-build.md— Phase 3 as built: 32 sets, 505 variants, the mode-chain architecture, native slots, the shells, and 10 findings in the DS itself
Live file: bcBO7RgVYR4ulwPr3j2heY. Icon library: Vst4WnV0LYfRZdC1dc7qv6 (owned, editable, 4,962 icons bound to component/fg). The April 2026 plan and its Figma file are superseded.
A published variable and its local original are TWO OBJECTS. (Measured 2026-08-27; cost a shipped bug.) The icons bound to
component/fgby published key, which resolves to a snapshot of the collection — one taken when it was still namedSPIKE Stylewith 4 modes. The DS file's Button sets modes on the local collection (Component/Style, 5 modes). Same key, different objects, different mode contexts, so the icon could never follow the Button's Intent or Style. Republishing the DS does not refresh it — the subscribing file holds its own snapshot; only re-importing by key inside that file pulls the current definition:const fresh = await figma.variables.importVariableByKeyAsync(KEY) // current, not the snapshot paint = figma.variables.setBoundVariableForPaint(paint, 'color', fresh)Symptom to recognise: a label and an icon bind to the same variable name and render different colours. Check
variable.remoteand the collection's mode count — if they differ, you have two objects. Only visible on non-accent components, which is why a full port and audit missed it.
Components publish from EVERY page, not just
Components. A spike or scratch component set left on any page ships to consumers on the next publish. Before publishing, assert zeroCOMPONENT/COMPONENT_SETnodes outside theComponentspage.
Built: 32 sets, 505 variants, 7 standalone components. Button 55, Input 64, Textarea 64, Badge 56, Select 48, Checkbox 27, Radio 18, Switch 18, Alert 15, Combobox 12, Slider 12, Progress 12, Avatar 10, Segment item 9, Tab item 9, Sidebar item 9, Card 6, Toast 6, Sheet 4, Label 4, Tooltip 4, Sidebar 4, Segmented control 3, Tabs 3, Skeleton 3, Dialog 2, Separator 2, Top bar 2, Bottom nav item 2, plus Menu item 12, Breadcrumb item 6, Accordion item 4. Standalone components (no variant axes): Bottom navbar, Menu, Menu label, Menu separator, Popover, Breadcrumb, Breadcrumb separator. 31 collections, 20 text styles, 13 effect styles, 37 native slot properties across 26 components (20 when first recorded; the 2026-08-29 build added 17 — see docs/audits/2026-08-27-figma-composability-gap.md gap 3). The menu family, Popover, Breadcrumb and Accordion are built but deliberately NOT published — held for review. Everything else is published. Publishing is a human step — republish after any change.
UNPUBLISHED CHANGES pending a republish (2026-09-05). The 0.60.0 form
refresh was back-ported into the Figma variables — it had shipped in code (#303)
and never been written back, so the file taught the pre-refresh spec for a full
release. Twelve changes, all measured, listed in
docs/audits/2026-09-05-updated-components-pass.md §2:
control/opacity 38 → 45; new field / field-hover semantic tokens with
control/bg and select/bg-base/select/bg-hover repointed at them (Select
routes through Component/Select, not control/bg, so it needs its own write —
and Checkbox/Radio route through a third variable, field/bg-tint, which
correctly stays on surface-panel-hover); new brand/error/8,
brand/success/8, error/8, success/8 with field/border-color moved to
step 8 (warning held at 7); avatar/ring-color 7 → 6; Switch Off track →
neutral/5, hover → neutral/6, resting stroke transparent-at-2px; and the
sm Switch thumb travel bug fixed (x: 18 → 16, rightGap 0 → 2 — Figma had
reproduced the exact defect #303 fixed in code).
Also cleared on Updated Components: three accidental VIDEO stroke paints, a
section mislabelled Tabs that held Sidebar item specimens, a duplicate
Notification center COMPONENT_SET that was publishing alongside the real one
(the first live instance of the "components publish from EVERY page" rule), and
all 18 zombie Button instances from the 330 → 55 collapse, repaired with
modes preserved across each swap. Zero publishable nodes and zero zombies remain.
The design pass itself SHIPPED as drawn (2026-09-06) — all twelve proposals
are in code, and a Decisions — 2026-09-05 page renders every one
before/after with light and dark side by side.
A measurement is an input, not a verdict, and the port is not where the call gets made. A first pass held six of the twelve on contrast grounds and presented that as a conclusion. Wrong twice over:
docs/deviations.mdexists precisely because this library ships below-threshold values on purpose, and the decision belongs to the maintainer and the designers. Build what they built, measure it, show it, let someone else decide. Where the artifact and the code model genuinely cannot line up — a CSS ring follows its element's radius, so a 2px-offset ring cannot keep its 4px corners — port as close as possible and say plainly what diverged.
Two plugin-API traps, both invisible in the data (2026-09-05):
figma.createAutoLayout()ships a default WHITE fill, exactly likecreateSlot()in rule 6 — harmless on a light ground, a white band straight across a dark one. Setfills = []on every structural frame you create. And a specimen that needs absolute positioning must not be an auto-layout frame: settingx/yon children of one is silently ignored and they stack, so a slider thumb rendered below its track. Both read back from the API exactly as written; only the screenshot showed them. Rule 4 extends — measure, don't eyeball, and look at the picture, not only the numbers.
UNPUBLISHED CHANGES pending a republish (2026-08-27): Card gained Show footer and Sidebar gained Show header, both BOOLEAN, both defaulting to true so existing instances are unchanged. They exist because an empty slot keeps the height it was created at and nothing else collapses it — a footerless Card was 40px too tall. Composability gap 3 is now CLOSED (2026-08-29): all 37 slot properties across 26 components are wired to a visibility boolean, 0 unwired. The counts in this file were wrong in both directions — there are 37 slots, not 20, and 8 were already wired, not 1 (Alert.Action among them; the 2026-08-29 build added 17 more slots). 29 booleans were added, every one defaulting true, so no existing instance changes. Measured working end to end: a Card went 158px → 125px with content off → 81px with the footer off too → 158px restored, and 574 variable bindings across Card, Sidebar and Top bar all still resolve. See docs/audits/2026-08-27-figma-composability-gap.md gap 3, and rule 6 for why displayEmptyByDefault is not the cheap alternative.
Open question, not a defect: ~7 of those 29 slots are structurally mandatory —
Menu.Items,Tabs.Items,Segmented control.Items,Breadcrumb.Trail,Table row.Cells,Table footer row.Cells,Schedule view.Days. Hiding them yields empty chrome rather than a useful state, and the audit's own wording was "anywhere a slot is legitimately optional". The booleans are harmless (defaulttrue) but they are dead toggles in the right panel. Deleting them is a judgement call about designer UX, so they were left in place pending one.
Colour is a variable MODE on Button, not a variant axis (2026-08-27). Button went 330 → 55 variants by deleting its Color axis: every variant had been pinning Component/Intent via explicitVariableModes, so the axis existed only to select a mode. Designers now set colour by selecting the instance and switching the Component/Intent mode — the same way they already set Style. Verified: 6 distinct fills from 55 variants, icon matching label throughout.
How a designer changes a Button colour now: select the instance, right-click > Change variable mode > Component/Intent, pick one of the six. Also in the right panel under Variable modes. This is less discoverable than the dropdown it replaced — a real cost, accepted knowingly for the variant reduction — so the instruction leads the Button set's description, which is what shows in the right panel at the moment of use. Style, Shape and Weight already worked this way, so the gesture is not new.
A consuming file CANNOT add a palette. Measured: addMode and setValueForMode on a library collection both throw "Cannot write to internal and read-only node". The mode list is ours, capped at 10 (40 on Enterprise), and we ship 6. A consumer's only route to a bespoke colour is rebinding an instance's fill to their own variable — which does work and survives a variant switch, but is per-instance, per-layer, and does not ride the hover/active roles. Adding a palette for a team means adding a mode here.
Every set's defaultVariant now matches its code default. It is READ-ONLY and derived from geometry (top-left-most variant), so a tidy ascending grid silently hands consumers the smallest size — 18 of 25 sets did. Assert set.defaultVariant.name after any re-layout.
Accessibility review page carried three measured contrast failures that were CODE bugs this library reproduced faithfully: Alert dismiss on solid (1.01:1), Badge category solid in dark (3.28–3.70:1), Input/Textarea placeholder in light (4.14:1). All three are FIXED in code on feat/surface-model (changeset clear-badges-see-clearly.md) — Alert inherits its own fg on solid, --color-category-fg inverts with the theme, and the four field controls moved to surface-fg-muted.
Figma is already synced — verified by resolving the bindings, not by reading this note: Alert */dismiss aliases the alert's own */body in Solid mode, Badge category */fg aliases category-fg (neutral/0 light, neutral/1 dark), and Component/Field Content field/text-color resolves to surface-fg-muted in Placeholder mode. The Accessibility review page carries before/after specimens bound to live variables and is labelled Fixed. Nothing to do there.
Headline architecture: style is a variable mode, colour is a variant, interactive state is a variant, icons come from our own published Tabler copy with colour bound in each icon's main component. Code Connect is blocked — the Devalok plan is Pro, and Code Connect needs Organization/Enterprise. Use description + documentationLinks.
Fourteen rules that cost the most time when broken:
- The collection a variable lives in is the OUTERMOST selector of its resolution chain. A value that varies by state and style must live in the state collection and alias into the style one. Get it backwards and the value is unreachable. This is what lets one
component/fgserve 4,962 icons across every state. Regenerate the component spec before every build (
figma-sync-components.mjs <name>) and read the component body for prop interactions — the CVA describes appearance, not which prop overrides which.A spec is not a substitute for reading the source, and for many components it is nearly empty. The script now resolves across
src/{ui,composed,shell}/, flat or in its own directory, and emits"cva": falseplus the names and line numbers of the style objects when a component has no CVA at all — Badge, Card, Table, DataTable, Autocomplete, TreeView, MasterDetail, NotificationCenter and ScheduleView all style from plain objects. Until 2026-08-29 it resolvedsrc/ui/<name>.tsxonly and threw on a missingcva(), so it failed on 7 of the 8 components in that build while this rule still called it mandatory.- Test with real scenarios and varied copy, not a variant grid. A grid hides layout bugs because every label is the same length.
- Measure, don't eyeball — but also read the numbers you get back. Four of ten bugs in the Button spike were silent, and a later one sat unnoticed inside a verification output I had already looked at. A returned
0is a finding. - Never write
.visibleon a variable-bound node — it silently clears the binding. An audit that reveals hidden nodes to inspect them will destroy what it inspects (it cost 264 spinner bindings).
Before building any Figma component, load the
figma-component-authoringskill (user-level, alongsidefigma-use). It carries the mechanism decision table (variant vs boolean vs instance-swap vs slot vs variable mode), the verified build order, and every silent failure this project paid for. It exists because we shipped a whole library before discovering native slots.
Assume a Figma limitation is your ignorance until three distinct mechanisms have failed. This has now been wrong six times. Two examples: "instances can't hold content" after trying exactly one approach (Figma has native slots,
component.createSlot()); and the rule below, which we believed for the whole port and which is only half true.Slot content IS authorable from the plugin API (measured 2026-08-27; we believed the opposite and wrote it into an audit).
setPropertieson a slot property fails with "Slot component property values cannot be edited", andappendChildstacks under the inherited defaults — but.remove()the defaults first andappendChildthen replaces cleanly, and it persists. Overriding a nested instance already in a slot works too.// clear, then fill. RE-QUERY the slot after every mutation — never cache .children let s = inst.findAll(n => n.type === 'SLOT').find(x => x.name === 'Content') s.children[0].remove() // ONE remove per slot per run s = inst.findAll(n => n.type === 'SLOT').find(x => x.name === 'Content') s.appendChild(myNode) // append is unlimitedTwo invisible rate limits, both of which return success and then fail on the next call:
- One
.remove()per slot per run. After the first, every node id inside that slot stops resolving (Node with id "…" not found). A 3-item slot takes 3 runs. Card's slots each held exactly 1 default, which is why a naive loop appeared to work there and died on Top bar's 3-itemEnd. - One
setPropertiesper nested slot instance per run. The write persists but kills the slot subtree. Different instances are unaffected, so N components can each take one write in the same run.
Four more slot traps (measured 2026-08-29). The handle invalidation above is now documented by Figma, which recommends the same fix — re-find through
slot.children:slotNode.clone()returns a plainFrameNode, not a SLOT. The clone looks right and is inert.- A
ComponentNodecannot be appended to a slot — append an instance of it. - Deleting a slot property deletes every instance's content in that slot. There is no warning and no undo across a run; treat
deleteComponentPropertyon a SLOT as destructive to consumer work. SlotSettingscan be retrofitted onto existing slots viaeditComponentProperty, with no rebuild — then gate onslotNode.limitViolations.
Also: an empty slot keeps the space it was created at, and neither
HUGnorresize()collapses it. This was recorded as "a ~32px minimum" from the Card measurement; re-measured 2026-08-28 on aVERTICALslot it cost 100px, so the number is the slot's created size, not a floor — it varies by construction and you have to measure the slot you actually built.displayEmptyByDefault: falsedoes not reclaim the space. It round-trips correctly (falsereads back asfalse) and changes nothing about layout: 121px component, 121px instance, 100px slot with it either way. It governs whether the empty drop-target is drawn, not whether it occupies space — so it is not the cheap fix for composability gap 3.The only way to remove an unused slot is a boolean wired to its
visible(componentPropertyReferences = { visible: key }) — which, unlike a raw.visiblewrite, does not clear variable bindings. Verify bindings after wiring anyway. That means each of the remaining 17 slots needs its own boolean; there is no global switch.A slot CAN be added to an already-combined set (measured 2026-08-21). The naive path does fail: calling
createSlot()per variant aftercombineAsVariantsgives one property per variant (Action#274:0ANDAction#274:3), so dropped content dies on every variant switch. But this works:const key = set.addComponentProperty('Action', 'SLOT', '') // merged, set-level for (const v of set.children) { const s = v.createSlot() const orphan = s.componentPropertyReferences.slotContentId // auto-made, per-variant s.componentPropertyReferences = { slotContentId: key, visible: boolKey } set.deleteComponentProperty(orphan) }slotContentIdis the reference field.addComponentPropertyalone creates an orphan property and no nodes;createSlotalone creates per-variant properties. Only the pair merges. Note the bundled typings documentaddComponentPropertyasBOOLEAN | TEXT | INSTANCE_SWAP | VARIANT.'SLOT'is documented as of Figma's 2026-06-10 plugin-API update — it is only the.d.tsthat lags, so trust the published API over the types here.VariableCollection.defaultModeIdis read-only, and is alwaysmodes[0]. This is the mode-level twin of thedefaultVariantgeometry trap: the default is derived from position, not chosen, so re-ordering modes silently re-points it.collection.setDefaultMode(modeId)is the writer — reach for it rather than renaming or re-creating modes to get the ordering you want.Two traps when doing this:
createSlot()gives the node a white SOLID fill (setfills = [], or you ship a white band), and a SLOT node is not auto-layout by default — setlayoutModebefore anyHUG/FILLsizing or it throws.- One
Deleting variants leaves ZOMBIE instances that still render. Collapsing Button 330 -> 55 orphaned 18 instances across the example screens. They kept pointing at the deleted main components (
Button/md/neutral/Default, old#115:*property ids) and looked completely fine, so no visual check would find them. They are frozen: no Size/State switch, and they track nothing the library does next.The obvious probes all return a clean bill of health.
detachedInfois null, andgetMainComponentAsync()returns a real node — Figma keeps the deleted main alive off-page to service the instance. The only tell is that the main has no page:const pageOf = n => { let p=n; while(p&&p.type!=='PAGE'&&p.type!=='DOCUMENT') p=p.parent return p&&p.type==='PAGE' ? p.name : null } const mc = await inst.getMainComponentAsync() const zombie = mc && !mc.remote && !pageOf(mc) // `remote` matters — see belowExclude
mc.remoteor you get a 100% false-positive rate. Icons from the published Tabler library legitimately have no page in this document; a naive check called all 92 of them orphans.swapComponent(liveVariant)repairs one cleanly and carries Label, icon booleans, size and child index across by matching property NAME — including for instances sitting inside a SLOT. Sweep by re-querying the page each pass rather than reusing cached nested ids (I535:2031;235:597;535:2178-style paths do not survive their host being mutated).swapComponentsilently dropsexplicitVariableModes. The instance keeps its properties and loses its modes. Now that colour is a variable mode this means a swap resets the colour, with no error. Read the modes first, swap, then set them back:const keep = { ...inst.explicitVariableModes } // BEFORE the swap inst.swapComponent(variant) for (const [cid, mid] of Object.entries(keep)) inst.setExplicitVariableModeForCollection(await figma.variables.getVariableCollectionByIdAsync(cid), mid)Never blanket a variable mode on a container frame. Each example screen set
Component/Style = GhostandComponent/Intent = Neutralon the screen frame, so the whole subtree inherited it — every Button on all 10 screens rendered transparent with grey text, including "Start free", "New task" and "Save changes". The screens had no visual hierarchy at all and had looked plausible for weeks, because a ghost button is still perfectly legible on its own.A blanket is worse than a wrong value: it is invisible at the point of use, and anything dropped onto that frame later silently inherits it. Set the mode on the instance that means it. A container should only carry a mode when the mode is genuinely a property of the container (theme:
Semantic/Color = Darkon a dark screen is correct).Figma effect STYLES do not follow variable modes, so every layer needs its own bound variable — FIXED 2026-08-29, all 13 styles / 35 layers. An
EffectStyleholds one fixed set of effects, so a mode-aware shadow is only possible by binding a variable per layer:figma.variables.setBoundVariableForEffect(effect, 'color', v)works inside anEffectStyle, not just on a node.The original entry here said the ring layers were uncorrected. That half was already fixed —
shadow/ringandshadow/ring-subtleexisted and were bound. The real gap was the other 29 layers, and it was bigger: CSS sets--shadow-strength: 2.5in dark, so every drop layer in Figma was 2.5× too weak;kbd's inset offset never flipped sign; andsegment's dark-only hairline did not exist at all.Now 35/35 layers bound, every light value byte-identical to before. Dark ring contrast on
surface-panel: 1.011:1 → 1.418:1.offsetYbinds and flips too, not just colour.Two things this surfaced that are NOT fixed, both because they change light rendering for every consumer and that is a design call:
shadow/floatingandshadow/overlayare each missing their outermost layer (code has 4 and 5 drop layers; Figma has 3 and 4).- Figma's shadow ink is
#1c2533(oklch 0.263 0.029 259) where code's--shadow-colorisoklch(0.15 0.015 260)=#080b12. Every layer is lighter than code. shadow/successisoklch(0.512 0.125 150.3)against code'soklch(0.55 0.14 145); its two siblings match code exactly, so this one drifted alone.
--shadow-pressedwas a real CODE bug this uncovered (fixed): it is a 1px ring built from--shadow-colorwith no.darkoverride, so it composited to 1.012:1 in dark — a pressed control had no pressed state. Its two sibling rings had been corrected and it had not. Figma had been masking it by binding the wrong variable. The deliberate stopping point of all three rings is recorded asSHADOW-RING-BELOW-NONTEXTindocs/deviations.md.Ten per-component shadow values still cannot follow dark mode.
card/shadow-1..5,btn/shadow-1..4andtabs/pill-shadowlive inComponent/Card,Component/StyleandComponent/Tabs— none of which has a Light/Dark mode at all, so a mode switch cannot reach them. In dark, an Elevated Card, a Solid Button and a contained Tab pill each cast a near-black shadow on a near-black ground. Same fault as this rule, in collections nobody thought to check because the fix went into the shared styles. Cheap to fix now thatshadow/ink-*exists — alias those ten at it.Figma dark mode needs TWO collection modes set, and reviewing with one shows you a hybrid (measured 2026-08-29).
surface-panel[Dark]is not a value, it is an alias toPrimitives/Color :: neutral/2, and that collection has its own Light/Dark modes defaulting to Light. Setting onlySemantic/Color = Darkfollows the pointer in dark and then reads it in light: you get light-grey panels wearing dark-mode shadows, which reads as "the dark shadows are broken" rather than "the ground is wrong".Set both. Verified correct output: ground
#0a0a0a, panels#171717.This also means any dark-mode review of this file done by setting one mode was looking at a hybrid — including measurements. A contrast number obtained by walking aliases and forcing Dark everywhere is the intended value, not the one a designer sees; say which you are quoting.
An effect object is frozen.
delete effect.boundVariablesthrows "could not delete property", andstyle.effects = […]has already applied by the time a revert fails — a read-only probe silently leftshadow/floatingmodified for every consumer of it. Rebuild the array from literals to restore, and read it back. Same lesson as rule 5: an audit that writes is not an audit.- A slot can ship EMPTY, and nothing warns you.
Menu'sItemsslot has no default content, so dragging it in gives a blank 240×107 white box. Its siblingsPopoverandBreadcrumbboth carry defaults, which is what tells a designer what belongs there. Checkslot.children.lengthon every slotted component before publishing. - Appending a bare TEXT to an existing auto-layout frame in a LATER plugin run
does not reflow it — the node lands at
y = 0and paints over the frame's first child, whilechildrenorder looks correct. Wrapping the text in a FRAME and appending that reflows properly. Read backchild.yafter appending, not just the child list. Every form control in Figma is bound to the DECORATIVE border tierRESOLVED — re-measured 2026-08-29 and this describes a state that no longer exists.field/border-colorandselect/border-baseboth already aliassurface-border-interactive, and Switch's stroke does too. (Switch'ssurface-border-strongis the unchecked track fill, which correctly matchesdata-[state=unchecked]:bg-surface-border-stronginswitch.tsx:71— reading a fill as a stroke is what made this look unfixed.)Figma and the browser now agree: 2.00:1 light / 2.07:1 dark, against
surface-border-strong's 1.38:1 / 1.63:1. The old numbers here were right; the diagnosis had simply gone stale. Both tiers still miss the 3:1 bar — that is the STEP question and is untouched.Kept rather than deleted because the lesson holds: a stale "known bug" is expensive in both directions. This one nearly got re-fixed, and two other entries in this list were also found stale on the same pass. Re-measure before acting on any rule here.
Legacy checklist (2026-04-20)
Still broadly valid for component completeness; ignore its Code Connect item. Original note: the Button went through four rebuilds on 2026-04-20 because we skipped these:
Component properties (right-panel UX):
- TEXT property for any visible string (label/heading/body) — never hardcode "Button"
- BOOLEAN property for each icon slot the CVA supports (startIcon, endIcon)
- BOOLEAN property for every CVA boolean prop (disabled, fullWidth, shape=pill, loading)
- VARIANT axis for every CVA axis, including State (default/hover/pressed/disabled/loading) where meaningful
Variable bindings (never raw numbers):
- Padding, cornerRadius (all 4 corners), itemSpacing, height, width → bound to Primitives/Spacing, /Radius, /Size
- Fill, stroke, text color → bound to Semantic/Color
- Font size → bound OR uses a DS text style (one of the two — no raw px values)
Effects as Figma Effect Styles:
- Every shadow the CVA references (
shadow-raised,shadow-brand, etc.) must exist as a named Effect Style - Apply the style to the variant CVA specifies
Documentation:
- ComponentSet
.description— purpose + 2-3 example use cases + SOURCE path - Code Connect mapping: Figma node → GitHub source URL at
packages/core/src/ui/*.tsx
Workflow scripts (in repo, re-runnable without an agent session):
packages/core/scripts/figma-sync-tokens.mjs— parsestokens/*.css→ Figma-ready JSONpackages/core/scripts/figma-sync-components.mjs— parses CVA → Figma component specpackages/core/scripts/figma-drift-check.mjs— diffs Figma live state vs CVA
Publishing: Only the user can click "Publish library" in Figma — flag it explicitly, don't assume done without it.
Skipping any of the above is NOT a time-saver. The cost of rebuild is 3-5× the cost of doing it right first time.
Deviations register
docs/deviations.md records deliberate departures from a
measurable standard — a value knowingly shipped that fails a stated threshold,
with the number it misses and why it was chosen anyway.
A measured threshold is one input, not the verdict: a 1px hairline can read clearly to the eye at a contrast ratio the formula calls invisible. Those calls are legitimate. Losing them is not — an unrecorded deviation gets rediscovered as a bug and "fixed" by someone who never knew it was chosen.
If you knowingly ship a value that fails a stated threshold, add an entry.
Fixing one means deleting its entry, not editing the number. Entries carry stable
IDs so code can cite them (// deviation: <ID>) and a gate can skip known cases.
Surface Layering (MANDATORY)
Every component MUST use the correct surface level. This is a hard rule, enforced by pre-publish-audit.mjs.
Use the SEMANTIC NAMED tokens — never the numbered classes. bg-surface-1..4 (and text-/border-/ring-surface-1..4) are DEPRECATED and hard-flagged by the audit's Source Hygiene gate (No deprecated surface tokens in components) — no per-file allowlist, no exceptions. They map to raw neutral steps and do NOT invert for dark mode; the named tokens are theme-aware (base/raised swap neutral steps between light and dark so elevation reads correctly in both). This gate is release-only, not in PR CI — a numbered class sails through the PR and only fails post-merge in integration.yml. Cost a release cycle on 0.53.0 (schedule-view rebuild used bg-surface-2).
bg-surface-base → Page background (the canvas everything sits on)
bg-surface-panel → Cards, widgets, panels, editor containers — anything ON the page
bg-surface-overlay → Overlays: Dialog, Sheet, Popover, DropdownMenu, Select,
Combobox, Toast, HoverCard, floating toolbars
bg-surface-panel-hover → Hover on panels, skeleton shimmers, track fills
bg-surface-panel-active → Active/pressed states, hover on panel-hover elements
bg-surface-sunken → Wells/insets that recede below the page
bg-surface-sunken-hover → Hover on a wellsurface-raised was renamed surface-panel in 0.57.0, because in light it is
not raised — it is the same white as the page. Old names still resolve as
deprecated aliases; pnpm eslint . --fix rewrites them. surface-chrome is
gone — chrome is an arrangement decision, not a theme value, and comes from
AppShell (variant + chrome) or surface-base.
The rule: if a component renders as a card/widget/panel on the page, its
background is bg-surface-panel, NOT bg-surface-base. When unsure which tier,
grep a sibling component and match — never reach for a numbered class.
The trap this model creates
In LIGHT, base, panel and overlay are all #ffffff. That is deliberate
— an edge is what makes a card a card, not a fill. Two consequences:
- Never paint an interaction state with a container value.
hover:bg-surface-panelon anything sitting on base/panel/overlay is invisible. Use-panel-hover/-panel-active.shilp-sutra/no-renamed-surface-tokencatches the Tailwind-modifier form, but it cannot see a JS conditional —isActive ? 'bg-surface-panel' : …compiles to a plain string and slipped past both the codemod and a full audit. Three components shipped that way. - You cannot verify "is this the right surface?" by sampling a colour. It has to be read from intent. Any audit that compares pixels will report false agreement.
- The same applies to STRUCTURAL differentiators, not just interaction states
(2026-08-28). A groove, a zebra stripe, a recess, a well, a bubble — anything
whose whole job is to differ from the thing behind it — is a no-op if it uses
a container value.
Table stripedand linearProgressboth shipped this way and rendered nothing at all in light: 1.00:1. Neither had a test, and neither looks broken in dark, where the tiers do differ. Reach for-panel-hoveror-sunken, and check the value against the ground the component actually sits on, not against the page.
Borders split into two families. surface-border-subtle / -border /
-border-strong are decorative, translucent, and mark objects. surface-border-interactive
/ -interactive-strong are control edges, solid, and carry WCAG 1.4.11. A form
control on a decorative tier loses required contrast.
Two more asymmetries that only bite in dark (both fixed 2026-08-28, both worth knowing before you add a token):
- Steps 1–2 of every colour ramp sit BELOW
surface-panelin dark, whilepanel-hoversits above it. So a selection painted withaccent-2recedes exactly as its own hover advances — the hovered row out-reads the selected one, in the opposite direction. Selections start at step 4. Step 2 is asurface-basedevice only. - A near-black shadow is not an edge on a dark ground.
--shadow-edge-ringflips to a light ring under.darkfor this reason; anything that hardcodesoklch(var(--shadow-color) …)instead of consuming that var will silently measure ~1.00:1 in dark. If you add an elevation token, give it a.darkentry or route it through the shared ring.
Both are recorded with measurements in
docs/audits/2026-08-28-surface-model-audit.md,
along with the four root causes a full sweep of 205 files turned up.
Full model: docs/plans/implemented/2026-08-26-surface-model-rebuild.md.
Publishing
Day-to-day (release split 2026-07-22): Publishing is decoupled from merging so releases can be paced, not churned. Three workflows:
version.yml(push→main):changesets/actionopens/updates the Version Packages PR. Never publishes.integration.yml(push→main): runs the release-UNIQUE gates PR CI can't (pre-publish-audit, consumer-smoke, compiled-CSS coverage, skill-drift, Chromatic) as a post-merge net. Never publishes.release.yml(workflow_dispatchONLY): full gauntlet + publish via OIDC Trusted Publisher (sigstore provenance).
Flow: land changesets → they accumulate in the Version PR → merge the Version PR when ready to ship (bumps versions, deletes changesets; no longer auto-publishes) → a maintainer dispatches release.yml (Actions UI "Run workflow" or gh workflow run release.yml). A stable dispatch is refused if unreleased changesets are still pending (you forgot to merge the Version PR). Do not run npm publish manually.
Gate steps in
integration.ymlare a subset ofrelease.yml's — when you add/change a release gate, keep both in sync or the post-merge net has a hole.
Authority on gates: scripts/pre-publish-audit.mjs is the single source of truth — 45 hard gates (git clean, version ↔ CHANGELOG match, per-component docs coverage, CVA/doc prop accuracy, typecheck, lint, tests, build, SSR smoke, surface/shadow token hygiene, TW4 migration hygiene, published-exports ordering, bundle size). It runs in integration.yml (every main push) AND release.yml's Audit step before publish, AND can be invoked locally (node scripts/pre-publish-audit.mjs) for pre-flight checks.
Human judgment lives on the Version Packages PR. See /publish-release for the reviewer checklist (changeset body quality, bump magnitude, Chromatic review, Storybook spot-check). CI can't evaluate these — they gate on merge.
When CI is broken: Use /publish-release's emergency manual runbook. Not optional gates — every one still runs locally before publish. The Iron Law ("NO PUBLISHING WITHOUT EVERY GATE PASSING") applies regardless of who's pressing the button.
Auth state (2026-04-21+): OIDC Trusted Publisher is active. NPM_TOKEN is no longer set; release.yml requires id-token: write permission and npm 11.5.1+ (the workflow bootstraps npm 11 before the publish step). See commits 79d60a8c, 1f23742c, 2c1f6ee0 for the saga that got us here.
If docs slip past a publish (happened with 0.36.0's llms.txt gap): publish a patch immediately. Don't wait.
HARD RULE: read the pnpm-lock.yaml diff before committing it (learned 2026-07-26, 0.56.0)
pnpm-lock.yaml is generated, so it gets git add-ed on autopilot — and a lockfile is the one generated file where a single stray line breaks every consumer of the repo. 0.56.0's first CI run died on ERR_PNPM_OUTDATED_LOCKFILE because the packages/core importer had picked up
'==rich-chat-input?RCI:RTE':
specifier: link:==rich-chat-input?RCI:RTE— a fragment of c==='rich-chat-input'?RCI:RTE, from a mangled inline node -e whose shell quoting broke and word-split into something that reached pnpm. Always git diff pnpm-lock.yaml before staging; for a dependency change the diff should be small and every line should be one you can explain.
Why nothing local caught it: pnpm install --frozen-lockfile short-circuits on an up-to-date node_modules — it printed Already up to date and exited 0 against the poisoned lockfile. --force didn't defeat it. Deleting node_modules/.modules.yaml didn't defeat it. Only CI caught it, because CI starts from a fresh checkout with no node_modules.
pnpm check:lockfile (scripts/check-lockfile.mjs) closes that gap and runs first in pnpm verify: it copies the workspace manifests + lockfile into a temp dir with no node_modules and runs pnpm install --frozen-lockfile --lockfile-only there, which is the only condition under which pnpm actually re-validates. Verified both ways — passes clean, exits 1 on the real bogus entry. Don't "simplify" it into an in-repo pnpm install --frozen-lockfile; that is precisely the check that lies. (Also: it invokes cmd.exe explicitly on Windows — a bare spawnSync('pnpm.cmd') fails EINVAL, and shell:true works but emits DEP0190 on every run.)
HARD RULE: a type NARROWING is breaking — never label it "non-breaking" (learned 2026-05-27, 0.40.0)
Before writing "non-breaking" / "type widening only" on any prop-type change, classify the direction per prop, against the prop's PREVIOUS type:
- Widening (old type ⊂ new type) → accepts more → non-breaking. Safe to label.
- Narrowing (new type ⊂ old type) → accepts less → BREAKING. A consumer whose value was valid under the old type now fails
tsc. - Mixed → it's breaking. Label it breaking and name which props narrowed.
React.ReactNode is the widest icon type (ReactElement | string | number | boolean | null | undefined | Iterable). Anything tighter than it — e.g. IconInput (ReactElement | ComponentType | null | undefined) — is a narrowing for every prop that was ReactNode. 0.40.0's F-10 unification was labeled "type widening only"; it widened the ComponentType-only props but narrowed the 14 ReactNode props, breaking 3 karm-v2 call sites (devalok-design/shilp-sutra#61). The /publish-release checklist's "if types changed, it IS breaking" box was read and still passed — don't repeat that.
When unsure whether old ⊂ new or new ⊂ old, write a @ts-expect-error/expectTypeOf probe with a value valid under the old type (a Record<string, ReactNode> entry, a string) and check it still compiles against the new type. If it doesn't, it's a narrowing → breaking.
Figma Make Kit
packages/core/make-kit/ ships in the npm tarball. 26 files: Guidelines.md + setup.md + 7 foundations/*.md + components/overview.md + 15 per-component guides. Authored to be pasted into Figma Make when registering shilp-sutra as a Make kit (https://developers.figma.com/docs/code/bring-your-design-system-package/).
Subpath exports: @devalok/shilp-sutra/make-kit → Guidelines.md, @devalok/shilp-sutra/make-kit/* → individual files.
Authoring rules. Voice is direct + prescriptive, no marketing copy. Sections per component: import → When to use → Variants/Colors/Sizes tables → Props table → Examples (4–6) → Rules. Props/defaults MUST come from mcp-manifest.json or actual CVA source — when those disagree, the source code wins (caught one stale llms-full.txt Form section during initial authoring, before llms-full was removed in 0.45). When updating components in src/ui/, also update the matching make-kit/components/*.md if the prop surface changed.
Smoke-tested 2026-06-01 in fresh Vite 8 + React 19 + TW4 + framer-motion 12 app. Build/dev/utility emission all green. Make eligibility confirmed pending only the human registration step in Figma UI.
Storybook MCP Server
When the Storybook dev server is running (pnpm dev), an MCP server at localhost:6006/mcp provides AI agents with:
- Live component metadata (props, stories, docs)
- Component and accessibility testing
- Live preview embedding
This complements the static llms.txt router + mcp-manifest.json with interactive capabilities.
Hosted Docs MCP (packages/mcp-server, live at https://shilp-sutra.devalok.in/mcp)
Serves version-exact docs from published npm tarballs. 13 tools (spec: docs/specs/mcp-manifest-standard.md):
- Reference:
how_to_use(self-teaching bootstrap — tool map + sequences),find_component,get_component,get_tokens,get_setup,upgrade,search_docs - Setup journey (0.47+):
detect_framework,preflight,validate_snippet,verify_setup— close the peer-dep-cliff, TW4-dead-class, wrong-recipe, mis-wired-config traps.preflight/verify_setupread the manifest's per-componentpeersfield. - Quality (0.50+):
check_slop— deterministic pre-emit design-quality gate. Two passes: regex corpus (slop-corpus.json) + a@babel/parserAST pass (nested-cards, filled+outline button duo, identical card grids, skipped heading levels). Returns findings + strengths + DO-guidance (slop-guidance.json, incl. a versioned Setu-principle snapshot + one-line Setu pointer) + aself_critiqueblock (a taste-prompt the CALLING agent runs on itself — no LLM on our end). Escape// slop-allow: <id> <reason>. Version-independent (no tarball). Complementsvalidate_snippet(correctness). Still-deferred (fuzzy/agent-judged): hero-metric, decorative-numbering, safe-face. - Write:
report_issue(files a public agent-feedback issue).
Tool list is GENERATED into README/AGENTS via scripts/generate-tool-list.mjs (<!-- BEGIN:mcp-tools --> markers; drift gate) — add new tools to its CATEGORY map. Manifest emitter (build-mcp-manifest.mjs) attaches structured peers[] per component. Smoke: packages/mcp-server/scripts/smoke.mjs covers all 13 (runs in CI on any MCP-relevant change).
CI: Turborepo remote cache (0.47+)
build/typecheck/lint/test route through turbo run. PR CI reads+writes a self-hosted turborepo-remote-cache on Railway (turbo-ss.devalok.dev, TURBO_TOKEN repo secret). Safety: the release path never uses the cache — release.yml sets TURBO_FORCE=true with no cache creds, and pnpm release uses build:fresh (turbo run build --force), so a published artifact is always freshly built. turbo.json outputs list ONLY gitignored generated artifacts (dist, skill, mcp-manifest.json, AGENTS.md, MIGRATION.md, .next) — NEVER committed files the build also touches (llms.txt, docs/components, README.md), or a cache restore would misrepresent source.
The pre-publish-audit skips its build/typecheck/test/ssr gates when SS_AUDIT_SKIP_REDUNDANT=1 (release.yml sets it — those ran as prior steps). version-packages auto-stubs a MIGRATION.md section for the target version (scripts/stub-migration-section.mjs) so the MIGRATION-section gate can't block a release.
Consumer AI Agent Feedback Protocol
This repo receives feedback from AI agents working on consumer apps (e.g., Karm).
Feedback arrives as GitHub Issues on devalok-design/shilp-sutra labeled karm-ai-agent-feedback (Karm's flow) or mcp-submitted (filed via the MCP report_issue tool by any consumer agent).
You do NOT check or act on these automatically. Only act when triggered:
/check-karm-feedback
Read all open issues labeled karm-ai-agent-feedback OR mcp-submitted on devalok-design/shilp-sutra.
For each issue:
- Investigate the reported problem against the actual codebase
- Summarize findings (confirmed bug, already works, docs gap, etc.)
- Present to the user
- Do NOT fix, comment on, or close issues until the user approves
/send-karm-notice
File an issue on devalok-design/karm with label shilp-sutra-ai-agent-feedback.
Use the DS Notice format:
Title: [DS Notice] <short summary>
## Type
<!-- one of: deprecation | migration-required | new-feature | usage-guidance -->
## Affects
- Component(s): <names>
- Current version: @devalok/shilp-sutra@X.Y.Z
- Target version: <if applicable>
## Description
<what's changing or what we noticed>
## Action Required
<!-- before -> after migration code, or recommended usage -->
## Timeline
<!-- immediate | next-minor | next-major -->See docs/plans/2026-03-07-ai-agent-feedback-protocol-design.md for full protocol details.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

