@bridge-ds/core 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/validators.ts","../src/id-map.ts","../src/token-merge.ts","../src/token-combine.ts","../src/css-overrides.ts","../src/compose.ts","../src/protection.ts","../src/github-client.ts","../src/protection-github.ts","../src/usage.ts","../src/history-github.ts","../src/history-demo.ts","../src/previews-github.ts","../src/ramps.js","../src/brand.ts","../src/docs-draft.ts","../src/change-drafts.ts","../src/docs-ai.ts","../src/explorations.ts","../src/requests.ts","../src/draft-exchange.ts","../src/explorations-github.ts","../src/requests-github.ts","../src/fidelity.ts","../src/fidelity-references.ts","../src/review-gate.ts","../src/library-update.ts","../src/branch-actions.ts","../src/jira.ts","../src/docs-proposal.ts","../src/share-branch.ts","../src/try-in-product.ts","../src/combine-branches.ts"],"sourcesContent":["// Guardrails checked before a PR can be opened. They mirror the repo rules (AGENTS.md,\n// docs/ARCHITECTURE.md \"Token tiers\", docs/GOVERNANCE.md) so designers get the answer in Figma\n// instead of a red CI run later.\n//\n// Tier rules (what each tier may alias):\n// primitive literal values, or another primitive\n// brand an alias to a primitive (palette, radius and font roles re-point raw scales)\n// base a literal or a primitive (motion, layers, icon sizes)\n// semantic an alias, never a literal. Colors alias a Brand palette role (palette.*); translucent\n// primitives (color.alpha.*) are the only raw colors allowed. Non-color semantic tokens\n// (focus ring width, elevation) may alias a primitive or a brand role.\n// density an alias to a primitive (space and size scales)\n// component an alias to a semantic, base, density or brand role token, or a primitive scale step\n// (space, type). Never a raw color ramp or a palette role.\n// Brand x theme overrides follow the semantic rule and must override an existing semantic token.\n\nimport { findReferenceProblems } from './resolver';\nimport { type TokenSet, modesOf } from './token-set';\nimport { type LogicalToken, SINGLE_MODE, TIER_AXIS, TIER_NAMES, type Tier, isMultiMode, modeDisplayName } from './types';\nimport { aliasTarget, collectRefs, isAlias } from './values';\nimport { type ContrastPair, type ContrastResult, contextLabel, contrastScope, evaluatePairs } from './wcag';\n\nexport type IssueCode =\n | 'file-problem'\n | 'raw-value'\n | 'alias-tier'\n | 'broken-reference'\n | 'alias-cycle'\n | 'all-scopes'\n | 'missing-mode'\n | 'override-orphan'\n | 'override-shadowed'\n | 'contrast'\n | 'contrast-unresolved'\n | 'type-change';\n\nexport interface Issue {\n code: IssueCode;\n severity: 'error' | 'warning';\n message: string;\n path?: string | undefined;\n mode?: string | undefined;\n}\n\nconst issueKey = (i: Issue) => `${i.code}|${i.path ?? ''}|${i.mode ?? ''}|${i.code === 'file-problem' ? i.message : ''}`;\nconst modeName = (mode: string) => (mode === SINGLE_MODE ? 'all modes' : modeDisplayName(mode));\n\nconst isPalette = (t: LogicalToken) => t.tier === 'brand' && t.path.startsWith('palette.');\nconst isRawColor = (t: LogicalToken) => t.tier === 'primitive' && t.type === 'color';\n\n/** Why `owner` (in `tier`) may not alias `target`, or undefined when the alias is allowed. */\nfunction aliasRule(owner: { tier: Tier; type: string }, target: LogicalToken): string | undefined {\n switch (owner.tier) {\n case 'primitive':\n case 'base':\n case 'brand':\n case 'density':\n return target.tier === 'primitive' ? undefined : `${TIER_NAMES[owner.tier]} tokens point to primitives only`;\n case 'semantic':\n if (owner.type === 'color') {\n if (isPalette(target)) return undefined;\n if (target.tier === 'primitive' && target.path.startsWith('color.alpha.')) return undefined;\n return 'Semantic colors point to a Brand palette role (palette.*) so every brand can re-map them';\n }\n return target.tier === 'primitive' || target.tier === 'brand' ? undefined : 'Semantic tokens point to a Brand role or a primitive';\n case 'component':\n if (isPalette(target) || isRawColor(target)) return 'Component tokens point to semantic tokens, never to a palette role or a raw color';\n return target.tier === 'component' ? 'Component tokens point to semantic tokens, not to other component tokens' : undefined;\n }\n}\n\n/** Tiers whose values must be aliases. */\nconst MUST_ALIAS: Tier[] = ['brand', 'semantic', 'density', 'component'];\n\nfunction checkValue(set: TokenSet, owner: { path: string; tier: Tier; type: string }, value: unknown, mode: string, where: string, issues: Issue[]): void {\n if (!isAlias(value)) {\n if (MUST_ALIAS.includes(owner.tier) && value !== undefined) {\n issues.push({\n code: 'raw-value',\n severity: 'error',\n path: owner.path,\n mode,\n message: `${owner.path} uses a raw value in ${where}. ${TIER_NAMES[owner.tier]} tokens must point to another variable (pick one instead of typing a value).`,\n });\n }\n return;\n }\n const target = set.byPath.get(aliasTarget(value));\n if (!target) return; // reported as a broken reference\n const why = aliasRule(owner, target);\n if (why) {\n issues.push({\n code: 'alias-tier',\n severity: 'error',\n path: owner.path,\n mode,\n message: `${owner.path} points to ${target.path} (${TIER_NAMES[target.tier]}) in ${where}. ${why}.`,\n });\n }\n}\n\n/** All rule violations in a token set. */\nexport function validateSet(set: TokenSet, pairs: ContrastPair[]): { issues: Issue[]; contrast: ContrastResult[] } {\n const issues: Issue[] = [];\n for (const p of set.problems) issues.push({ code: 'file-problem', severity: 'error', message: p });\n\n for (const t of set.tokens.values()) {\n if (t.scopes?.includes('ALL_SCOPES')) {\n issues.push({\n code: 'all-scopes',\n severity: 'error',\n path: t.path,\n message: `${t.path} is offered in every Figma picker (\"All supported properties\"). Pick the specific properties it is meant for in the variable's scoping settings.`,\n });\n }\n const modes = modesOf(set.layout, t.tier);\n for (const mode of modes) {\n const v = t.values[mode];\n if (v === undefined) {\n if (isMultiMode(t.tier)) {\n issues.push({\n code: 'missing-mode',\n severity: 'error',\n path: t.path,\n mode,\n message: `${t.path} has no value in ${modeName(mode)}. ${TIER_NAMES[t.tier]} tokens must exist in every ${TIER_AXIS[t.tier]}.`,\n });\n }\n continue;\n }\n checkValue(set, t, v, mode, modeName(mode), issues);\n }\n }\n\n for (const o of set.overrides) {\n const mode = `${o.brand}.${o.theme}`;\n const where = `${modeDisplayName(o.brand)} ${o.theme} (${o.file})`;\n const base = set.byPath.get(o.path);\n if (!base || base.tier !== 'semantic') {\n issues.push({\n code: 'override-orphan',\n severity: 'error',\n path: o.path,\n mode,\n message: `${o.file} overrides ${o.path}, which is not a semantic token. Remove the override or restore the token.`,\n });\n continue;\n }\n checkValue(set, { path: o.path, tier: 'semantic', type: base.type }, o.value, mode, where, issues);\n for (const ref of collectRefs(o.value)) {\n if (!set.byPath.has(ref)) issues.push({ code: 'broken-reference', severity: 'error', path: o.path, mode, message: `${o.path} points to ${ref}, which does not exist (${where}).` });\n }\n }\n\n const axes = { brand: modesOf(set.layout, 'brand'), theme: modesOf(set.layout, 'semantic'), density: modesOf(set.layout, 'density') };\n for (const p of findReferenceProblems(set.byPath, axes)) {\n issues.push(\n p.kind === 'broken'\n ? {\n code: 'broken-reference',\n severity: 'error',\n path: p.path,\n mode: p.mode,\n message: `${p.path} points to ${p.target}, which does not exist (${modeName(p.mode)}).`,\n }\n : {\n code: 'alias-cycle',\n severity: 'error',\n path: p.path,\n mode: p.mode,\n message: `${p.path} is part of a loop of references: ${p.chain.join(' -> ')} (${modeName(p.mode)}).`,\n },\n );\n }\n\n const contrast = evaluatePairs(set.byPath, pairs, contrastScope(set));\n for (const r of contrast) {\n const path = `${r.pair.foreground} on ${r.pair.background}`;\n const mode = `${r.brand ?? ''}.${r.theme}`;\n if (r.error) {\n issues.push({ code: 'contrast-unresolved', severity: 'warning', path, mode, message: `Contrast of ${path} in ${contextLabel(r)} cannot be checked: ${r.error}.` });\n } else if (r.level === 'fail') {\n issues.push({\n code: 'contrast',\n severity: 'error',\n path,\n mode,\n message: `${path} is ${r.ratio}:1 in ${contextLabel(r)}; contrast.checks.json needs ${r.pair.min}:1 (WCAG AA ${r.pair.kind === 'ui' ? 'for interface elements' : 'for text'}).`,\n });\n }\n }\n return { issues, contrast };\n}\n\nexport interface TypeChange {\n path: string;\n from: string;\n to: string;\n}\n\nexport interface ProposalValidation {\n /** Problems this change introduces. They disable the PR button. */\n blocking: Issue[];\n /** Problems that already exist on main, or soft checks. Shown, not blocking. */\n warnings: Issue[];\n contrastBefore: ContrastResult[];\n contrastAfter: ContrastResult[];\n}\n\n/**\n * Semantic edits that some brand does not see because it overrides that token for the theme\n * (brands/<brand>.<theme>.tokens.json). Not an error: a heads-up that the edit is partial.\n */\nexport function shadowedEdits(set: TokenSet, edits: { path: string; tier: Tier; modes: string[] }[]): Issue[] {\n const out: Issue[] = [];\n for (const e of edits) {\n if (e.tier !== 'semantic') continue;\n for (const o of set.overrides) {\n if (o.path !== e.path || !e.modes.includes(o.theme)) continue;\n out.push({\n code: 'override-shadowed',\n severity: 'warning',\n path: e.path,\n mode: `${o.brand}.${o.theme}`,\n message: `${e.path} is overridden for ${modeDisplayName(o.brand)} in ${o.theme} (${o.file}), so this edit does not change ${modeDisplayName(o.brand)} ${o.theme}. Brand overrides stay code-only.`,\n });\n }\n }\n return out;\n}\n\n/**\n * Validate the files a PR would produce. Errors already present on main are reported as warnings\n * so an unrelated, pre-existing problem does not block a designer's change; everything the change\n * introduces blocks.\n */\nexport function validateProposal(proposed: TokenSet, head: TokenSet, pairs: ContrastPair[], typeChanges: TypeChange[] = []): ProposalValidation {\n const after = validateSet(proposed, pairs);\n const before = validateSet(head, pairs);\n const existing = new Set(before.issues.map(issueKey));\n const blocking: Issue[] = [];\n const warnings: Issue[] = [];\n for (const i of after.issues) {\n if (i.severity === 'warning') warnings.push(i);\n else if (existing.has(issueKey(i))) warnings.push({ ...i, severity: 'warning', message: `Already on main: ${i.message}` });\n else blocking.push(i);\n }\n for (const c of typeChanges) {\n blocking.push({\n code: 'type-change',\n severity: 'error',\n path: c.path,\n message: `${c.path} changed type from ${c.from} to ${c.to}. Type changes are not allowed; create a new token instead.`,\n });\n }\n return { blocking, warnings, contrastBefore: before.contrast, contrastAfter: after.contrast };\n}\n","// Stable identity of tokens across renames.\n//\n// Every variable DS Bridge writes carries a token id in its plugin data. The id is the token's\n// `$extensions[\"com.dsbridge.id\"]` when the file declares one, otherwise \"path:<path>\". Matching is\n// by id first, so renaming a variable in Figma is a rename, not a delete plus an add. Only renamed\n// (or re-identified) tokens get the extension written into Git, which keeps the files lean.\n//\n// Variables created in Figma have no id. They are matched by name, then, as a last resort, a\n// heuristic proposes \"this looks like a rename\" (same type, same values, similar path). Heuristic\n// matches are suggestions only: the user confirms each one.\n\nimport { pathId } from './token-set';\nimport type { LogicalToken } from './types';\nimport { valuesEqual } from './values';\n\nexport interface RenameSuggestion {\n /** Id the Figma variable currently has (derived from its new name). */\n figmaId: string;\n /** Id of the Git token it probably is. */\n gitId: string;\n fromPath: string;\n toPath: string;\n similarity: number;\n}\n\nexport interface ReconcileResult {\n tokens: LogicalToken[];\n /** Figma tokens that adopted a Git id because their names matched (no plugin data yet). */\n adoptedByName: string[];\n suggestions: RenameSuggestion[];\n}\n\nexport function levenshtein(a: string, b: string): number {\n const prev = Array.from({ length: b.length + 1 }, (_, i) => i);\n for (let i = 1; i <= a.length; i++) {\n let diag = prev[0]!;\n prev[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const tmp = prev[j]!;\n prev[j] = Math.min(prev[j]! + 1, prev[j - 1]! + 1, diag + (a[i - 1] === b[j - 1] ? 0 : 1));\n diag = tmp;\n }\n }\n return prev[b.length]!;\n}\n\nexport function pathSimilarity(a: string, b: string): number {\n const ratio = 1 - levenshtein(a, b) / Math.max(a.length, b.length, 1);\n const leafA = a.slice(a.lastIndexOf('.') + 1);\n const leafB = b.slice(b.lastIndexOf('.') + 1);\n return leafA === leafB ? Math.max(ratio, 0.75) : ratio;\n}\n\nexport const SIMILARITY_THRESHOLD = 0.5;\n\nfunction sameContent(a: LogicalToken, b: LogicalToken): boolean {\n if (a.type !== b.type || a.tier !== b.tier) return false;\n const modes = new Set([...Object.keys(a.values), ...Object.keys(b.values)]);\n for (const m of modes) if (!valuesEqual(a.type, a.values[m], b.values[m])) return false;\n return true;\n}\n\n/**\n * Align Figma token ids with Git ids. `git` is every token known on the Git side (base and head).\n * Heuristic candidates are restricted to Git tokens that no Figma variable claims.\n */\nexport function reconcileIds(figma: LogicalToken[], git: LogicalToken[]): ReconcileResult {\n const gitById = new Map<string, LogicalToken>();\n const gitByPath = new Map<string, LogicalToken>();\n for (const t of git) {\n if (!gitById.has(t.id)) gitById.set(t.id, t);\n if (!gitByPath.has(t.path)) gitByPath.set(t.path, t);\n }\n const claimed = new Set(figma.filter((t) => gitById.has(t.id)).map((t) => t.id));\n const adoptedByName: string[] = [];\n const tokens = figma.map((t) => ({ ...t }));\n\n for (const t of tokens) {\n if (gitById.has(t.id)) continue;\n const byName = gitByPath.get(t.path);\n if (byName && !claimed.has(byName.id) && byName.type === t.type) {\n t.id = byName.id;\n claimed.add(byName.id);\n adoptedByName.push(t.id);\n }\n }\n\n const suggestions: RenameSuggestion[] = [];\n const unclaimedGit = [...gitById.values()].filter((g) => !claimed.has(g.id));\n for (const t of tokens) {\n if (gitById.has(t.id)) continue;\n let best: RenameSuggestion | undefined;\n for (const g of unclaimedGit) {\n if (!sameContent(t, g)) continue;\n const similarity = pathSimilarity(t.path, g.path);\n if (similarity < SIMILARITY_THRESHOLD) continue;\n if (!best || similarity > best.similarity) {\n best = { figmaId: t.id, gitId: g.id, fromPath: g.path, toPath: t.path, similarity: Math.round(similarity * 100) / 100 };\n }\n }\n if (best) suggestions.push(best);\n }\n // One suggestion per Git token: keep the most similar.\n const byGit = new Map<string, RenameSuggestion>();\n for (const s of suggestions) {\n const prev = byGit.get(s.gitId);\n if (!prev || s.similarity > prev.similarity) byGit.set(s.gitId, s);\n }\n return { tokens, adoptedByName, suggestions: [...byGit.values()] };\n}\n\n/** Apply the rename suggestions the user confirmed: the Figma token takes the Git id. */\nexport function applyConfirmedRenames(tokens: LogicalToken[], confirmed: RenameSuggestion[]): LogicalToken[] {\n const map = new Map(confirmed.map((s) => [s.figmaId, s.gitId]));\n return tokens.map((t) => (map.has(t.id) ? { ...t, id: map.get(t.id)! } : t));\n}\n\n/**\n * Id to write into `$extensions[\"com.dsbridge.id\"]`: only needed when the id no longer matches\n * the default derived from the path (after a rename). Undefined means \"do not write\".\n */\nexport function idExtensionFor(t: LogicalToken): string | undefined {\n return t.id === pathId(t.path) ? undefined : t.id;\n}\n","// Three-way merge of token files: a change (mine) against the latest library (theirs), from the commit they share\n// (base). Same rules as the Figma sync (diff-engine threeWayDiff): a token changed on one side only takes that side,\n// a token changed on both sides the same way is unchanged, and a token changed on both sides differently is a\n// conflict the designer decides (\"Keep mine\" or \"Use the library's\"). A token removed on one side and changed on the\n// other has no default: the designer must pick.\n//\n// Works file by file on the DTCG text, so each mode (semantic/light, semantic/dark, a brand override file) is merged\n// on its own, and edits go through the format-preserving codec: untouched tokens stay byte for byte as the library\n// has them. Pure: no fetch, no DOM.\n\nimport { emptyTokenFile, flattenTokens, parseTokenFile, removeToken, serializeTokenFile, upsertToken, type TokenDocument } from './dtcg-codec';\nimport { threeWayDiff, type DiffEntry } from './diff-engine';\nimport { pathId } from './token-set';\nimport { EXT_ID, EXT_SCOPES, SINGLE_MODE, type FlatToken, type LogicalToken } from './types';\n\n/** Which side a conflict keeps: this change (\"Keep mine\") or the latest library (\"Use the library's\"). */\nexport type MergeSide = 'mine' | 'theirs';\n\nexport interface TokenMergeConflict {\n /** Stable key for the choice: `<file>#<token id>`. */\n key: string;\n /** Token file, relative to the tokens root. */\n file: string;\n /** Display path: this change's name, else the library's, else the shared one. */\n path: string;\n base?: FlatToken | undefined;\n mine?: FlatToken | undefined;\n theirs?: FlatToken | undefined;\n /** The side that removed the token while the other changed it. Null when both sides kept it. */\n removedOn: MergeSide | null;\n /** \"Keep mine\" by default; null when the token was removed on one side and changed on the other. */\n defaultChoice: MergeSide | null;\n}\n\nexport interface TokenMergePlan {\n /** Token files both sides changed, relative to the tokens root. */\n files: string[];\n conflicts: TokenMergeConflict[];\n /** Tokens only this change touched: applied on top of the library as they are. */\n mineOnly: number;\n /** Tokens only the library touched: kept as the library has them. */\n theirsOnly: number;\n /** Files that could not be read (not JSON): nothing can be merged while there is one. */\n problems: string[];\n}\n\nexport interface TokenMergeInput {\n /** File texts at the commit both sides share. Undefined: the file did not exist there. */\n base: Record<string, string | undefined>;\n /** File texts in the change. */\n mine: Record<string, string | undefined>;\n /** File texts in the latest library. */\n theirs: Record<string, string | undefined>;\n /** Token files both sides changed (the others need no merge). */\n files: string[];\n}\n\nexport type MergeChoices = Record<string, MergeSide | undefined>;\n\ninterface Side {\n doc: TokenDocument | undefined;\n flat: Map<string, FlatToken>;\n logical: Map<string, LogicalToken>;\n}\n\nconst idOf = (f: FlatToken) => {\n const id = f.extensions?.[EXT_ID];\n return typeof id === 'string' && id ? id : pathId(f.path);\n};\n\n/** One flat token as a single-mode logical token, so threeWayDiff compares path, type, value, description and scopes. */\nfunction logical(f: FlatToken): LogicalToken {\n const scopes = f.extensions?.[EXT_SCOPES];\n return {\n id: idOf(f),\n path: f.path,\n type: f.type ?? 'unknown',\n // One file holds one tier: the tier only feeds default scopes, the same on every side.\n tier: 'primitive',\n values: { [SINGLE_MODE]: f.value },\n description: f.description,\n scopes: Array.isArray(scopes) ? scopes.map(String) : undefined,\n files: { [SINGLE_MODE]: f.file },\n };\n}\n\nfunction readSide(file: string, text: string | undefined, problems: string[], label: string): Side {\n const side: Side = { doc: undefined, flat: new Map(), logical: new Map() };\n if (text === undefined) return side;\n try {\n side.doc = parseTokenFile(file, text);\n } catch (err) {\n problems.push(`${file} (${label}) is not valid JSON: ${(err as Error).message}`);\n return side;\n }\n for (const f of flattenTokens(side.doc)) {\n const id = idOf(f);\n side.flat.set(id, f);\n side.logical.set(id, logical(f));\n }\n return side;\n}\n\ninterface FileDiff {\n file: string;\n base: Side;\n mine: Side;\n theirs: Side;\n local: DiffEntry[];\n remote: DiffEntry[];\n conflicts: DiffEntry[];\n}\n\nfunction diffFile(input: TokenMergeInput, file: string, problems: string[]): FileDiff {\n const base = readSide(file, input.base[file], problems, 'shared start');\n const mine = readSide(file, input.mine[file], problems, 'this change');\n const theirs = readSide(file, input.theirs[file], problems, 'latest library');\n const r = threeWayDiff(base.logical, mine.logical, theirs.logical);\n return { file, base, mine, theirs, local: r.local, remote: r.remote, conflicts: r.conflicts };\n}\n\n/** The side that removed a token the other side changed, or null. */\nexport function removedSide(c: { base?: unknown; mine?: unknown; theirs?: unknown }): MergeSide | null {\n if (!c.base) return null;\n if (!c.mine && c.theirs) return 'mine';\n if (!c.theirs && c.mine) return 'theirs';\n return null;\n}\n\n/** \"Keep mine\" by default, except for a token removed on one side and changed on the other: no default there. */\nexport const defaultChoiceFor = (c: { base?: unknown; mine?: unknown; theirs?: unknown }): MergeSide | null => (removedSide(c) ? null : 'mine');\n\n/** What both sides did to the token files they both changed, and which tokens need a decision. */\nexport function planTokenMerge(input: TokenMergeInput): TokenMergePlan {\n const problems: string[] = [];\n const files = [...new Set(input.files)].sort();\n const conflicts: TokenMergeConflict[] = [];\n let mineOnly = 0;\n let theirsOnly = 0;\n for (const file of files) {\n const d = diffFile(input, file, problems);\n mineOnly += d.local.length;\n theirsOnly += d.remote.length;\n for (const e of d.conflicts) {\n const c = { base: d.base.flat.get(e.id), mine: d.mine.flat.get(e.id), theirs: d.theirs.flat.get(e.id) };\n conflicts.push({ key: `${file}#${e.id}`, file, path: (c.mine ?? c.theirs ?? c.base)!.path, ...c, removedOn: removedSide(c), defaultChoice: defaultChoiceFor(c) });\n }\n }\n return { files, conflicts, mineOnly, theirsOnly, problems };\n}\n\n/** The side a conflict keeps: the designer's pick, else its default (null: still to pick). */\nexport const choiceFor = (c: TokenMergeConflict, choices: MergeChoices): MergeSide | null => choices[c.key] ?? c.defaultChoice;\n\n/** Conflicts that still need a pick: removed on one side, changed on the other, and not decided yet. */\nexport function missingChoices(plan: Pick<TokenMergePlan, 'conflicts'>, choices: MergeChoices): TokenMergeConflict[] {\n return plan.conflicts.filter((c) => choiceFor(c, choices) === null);\n}\n\n/** Puts this change's version of a token into the library's file: its value, type, description and extensions. Also used by token-combine. */\nexport function takeMine(doc: TokenDocument, mine: FlatToken | undefined, existing: FlatToken | undefined): boolean {\n if (!mine) return existing ? removeToken(doc, existing.path) : false;\n let changed = false;\n if (existing && existing.path !== mine.path) changed = removeToken(doc, existing.path) || changed;\n // Extension keys the library has and this change does not are removed, so the token reads as in the change.\n const extensions: Record<string, unknown> = {};\n for (const k of Object.keys(existing?.path === mine.path ? (existing.extensions ?? {}) : {})) extensions[k] = undefined;\n Object.assign(extensions, mine.extensions ?? {});\n return upsertToken(doc, mine.path, { type: mine.type, value: mine.value, description: mine.description, extensions }) || changed;\n}\n\nexport interface TokenMergeResult {\n /** Merged text per file (relative to the tokens root); null when the merged file holds no token and is removed. */\n files: Record<string, string | null>;\n /** How many conflicts kept each side. */\n kept: Record<MergeSide, number>;\n}\n\n/**\n * The merged token files: the latest library's text, plus every token only this change touched, plus each conflict\n * as chosen. Throws when a file could not be read or a conflict still needs a pick.\n */\nexport function applyTokenMerge(input: TokenMergeInput, choices: MergeChoices): TokenMergeResult {\n const plan = planTokenMerge(input);\n if (plan.problems.length) throw new Error(plan.problems[0]);\n const missing = missingChoices(plan, choices);\n if (missing.length) throw new Error(`Pick a value for ${missing.map((c) => c.path).join(', ')} first.`);\n const byKey = new Map(plan.conflicts.map((c) => [c.key, c]));\n const kept: Record<MergeSide, number> = { mine: 0, theirs: 0 };\n const files: Record<string, string | null> = {};\n for (const file of plan.files) {\n const d = diffFile(input, file, []);\n const doc = d.theirs.doc ?? emptyTokenFile(file);\n for (const e of d.local) takeMine(doc, d.mine.flat.get(e.id), d.theirs.flat.get(e.id) ?? d.base.flat.get(e.id));\n for (const e of d.conflicts) {\n const side = choiceFor(byKey.get(`${file}#${e.id}`)!, choices)!;\n kept[side]++;\n if (side === 'mine') takeMine(doc, d.mine.flat.get(e.id), d.theirs.flat.get(e.id));\n }\n const empty = flattenTokens(doc).length === 0;\n files[file] = empty && (input.theirs[file] === undefined || input.mine[file] === undefined) ? null : serializeTokenFile(doc);\n }\n return { files, kept };\n}\n","// Try several changes together: the latest library plus the token edits of 2 to 4 open changes, combined in the\n// browser. Nothing is written anywhere: no branch, no commit. Each change's own edits are what it did to its token\n// files since it started (its start against its current version), so a change that is behind the library never\n// undoes the library's newer values. Edits to the same token that agree are applied once; edits that disagree are a\n// conflict the designer settles (\"Use <change>'s\"). Pure: no fetch, no DOM. Studio (Changes, the library views) and\n// the admin's Bridge toolbar both run it.\n\nimport { emptyTokenFile, flattenTokens, parseTokenFile, serializeTokenFile, type TokenDocument } from './dtcg-codec';\nimport { takeMine } from './token-merge';\nimport { pathId } from './token-set';\nimport { EXT_ID, type FlatToken } from './types';\n\n/** What one change brings: its token files where it started and now, and the token files it edits. */\nexport interface CombineSource {\n number: number;\n /** Token file texts where the change started (relative to the tokens root). Undefined: the file did not exist. */\n base: Record<string, string | undefined>;\n /** Token file texts in the change now. Undefined: the change removes the file. */\n head: Record<string, string | undefined>;\n /** Token files the change edits, relative to the tokens root. */\n files: string[];\n}\n\nexport interface CombineEdit {\n /** `<file>#<token id>`: the same token in the same file across changes. */\n key: string;\n file: string;\n /** The token's path in the change (its old path when the change removes it). */\n path: string;\n change: number;\n /** The change's version of the token; undefined when the change removes it. */\n token: FlatToken | undefined;\n}\n\nexport interface ChangeEdits {\n number: number;\n edits: CombineEdit[];\n /** Files that could not be read (not JSON). */\n problems: string[];\n}\n\nconst idOf = (f: FlatToken) => {\n const id = f.extensions?.[EXT_ID];\n return typeof id === 'string' && id ? id : pathId(f.path);\n};\n\nfunction tokensOf(file: string, text: string | undefined, problems: string[], label: string): Map<string, FlatToken> {\n const out = new Map<string, FlatToken>();\n if (text === undefined) return out;\n try {\n for (const t of flattenTokens(parseTokenFile(file, text))) out.set(idOf(t), t);\n } catch (err) {\n problems.push(`${file} (${label}) is not valid JSON: ${(err as Error).message}`);\n }\n return out;\n}\n\n/** What a token is, for comparing two versions of it: its path, type, value and description. */\nconst shape = (t: FlatToken | undefined) => (t ? JSON.stringify([t.path, t.type ?? null, t.value, t.description ?? null]) : 'removed');\n/** What a token shows, for comparing two changes' edits: removed, or its type and value. */\nconst look = (t: FlatToken | undefined) => (t ? JSON.stringify([t.path, t.type ?? null, t.value]) : 'removed');\n\n/** The token edits of one change: every token whose version differs between where the change started and now. */\nexport function changeEdits(src: CombineSource): ChangeEdits {\n const problems: string[] = [];\n const edits: CombineEdit[] = [];\n for (const file of [...new Set(src.files)].sort()) {\n const before = tokensOf(file, src.base[file], problems, 'start');\n const after = tokensOf(file, src.head[file], problems, `change ${src.number}`);\n for (const id of new Set([...before.keys(), ...after.keys()])) {\n const a = before.get(id);\n const b = after.get(id);\n if (shape(a) === shape(b)) continue;\n edits.push({ key: `${file}#${id}`, file, path: (b ?? a)!.path, change: src.number, token: b });\n }\n }\n return { number: src.number, edits, problems };\n}\n\n/** One value a conflicting token can take, and the changes that set it. */\nexport interface CombineOption {\n changes: number[];\n token: FlatToken | undefined;\n}\n\n/** A token two or more changes set differently: the designer picks one change's value. */\nexport interface CombineConflict {\n key: string;\n file: string;\n path: string;\n /** Distinct values, in the order of the changes. */\n options: CombineOption[];\n}\n\n/** The pick of each conflict: the change whose value the combination uses. */\nexport type CombinePicks = Record<string, number>;\n\nexport interface Combination {\n /** Every token file of the latest library, with the combined edits applied (unchanged files as they are). */\n files: Record<string, string>;\n /** The changes combined, in order. */\n included: number[];\n /** Token values the combination edits (one per token and file: a token edited in light and dark counts twice). */\n edits: number;\n /** Tokens the combination edits, by name. */\n tokens: number;\n conflicts: CombineConflict[];\n /** Conflicts without a pick that counts: left at the library's value ('skip') or given the first change's ('first'). */\n missing: CombineConflict[];\n /** Token path -> the changes whose value the combination uses for it. */\n from: Record<string, number[]>;\n problems: string[];\n}\n\n/** Edits grouped by token, in the order of the changes. */\nfunction byToken(changes: ChangeEdits[]): Map<string, CombineEdit[]> {\n const out = new Map<string, CombineEdit[]>();\n for (const c of changes) for (const e of c.edits) out.set(e.key, [...(out.get(e.key) ?? []), e]);\n return out;\n}\n\nfunction optionsOf(edits: CombineEdit[]): CombineOption[] {\n const out: { look: string; option: CombineOption }[] = [];\n for (const e of edits) {\n const l = look(e.token);\n const hit = out.find((o) => o.look === l);\n if (hit) hit.option.changes.push(e.change);\n else out.push({ look: l, option: { changes: [e.change], token: e.token } });\n }\n return out.map((o) => o.option);\n}\n\n/** Tokens that two or more of these changes set differently. */\nexport function combineConflicts(changes: ChangeEdits[]): CombineConflict[] {\n const out: CombineConflict[] = [];\n for (const [key, edits] of byToken(changes)) {\n const options = optionsOf(edits);\n if (options.length > 1) out.push({ key, file: edits[0]!.file, path: edits[0]!.path, options });\n }\n return out;\n}\n\n/** The option a pick selects, or null when the picked change is not among them (not picked, or switched off). */\nexport function pickedOption(c: CombineConflict, picks: CombinePicks): CombineOption | null {\n const n = picks[c.key];\n return n === undefined ? null : (c.options.find((o) => o.changes.includes(n)) ?? null);\n}\n\n/** Conflicts that still need a pick. */\nexport const unpicked = (conflicts: CombineConflict[], picks: CombinePicks) => conflicts.filter((c) => !pickedOption(c, picks));\n\n/**\n * The latest library plus the edits of the included changes (all of them by default, in their order). A conflict\n * uses the picked change's value. Without a pick that counts, `unpicked: 'skip'` (Studio, before opening) leaves the\n * token at the library's value and lists it in `missing`; `'first'` (the toolbar, when a picked change is switched\n * off) uses the first included change's value and still lists it.\n */\nexport function combineChanges(latest: Record<string, string>, changes: ChangeEdits[], picks: CombinePicks = {}, opts: { include?: number[]; unpicked?: 'skip' | 'first' } = {}): Combination {\n const on = opts.include ? changes.filter((c) => opts.include!.includes(c.number)) : changes;\n const problems = on.flatMap((c) => c.problems);\n const groups = byToken(on);\n const conflicts: CombineConflict[] = [];\n const missing: CombineConflict[] = [];\n const from: Record<string, number[]> = {};\n const docs = new Map<string, TokenDocument>();\n const docOf = (file: string): TokenDocument | null => {\n if (docs.has(file)) return docs.get(file)!;\n const text = latest[file];\n let doc: TokenDocument;\n try {\n doc = text === undefined ? emptyTokenFile(file) : parseTokenFile(file, text);\n } catch (err) {\n problems.push(`${file} (latest library) is not valid JSON: ${(err as Error).message}`);\n return null;\n }\n docs.set(file, doc);\n return doc;\n };\n for (const [key, edits] of groups) {\n const options = optionsOf(edits);\n let use: CombineOption | null = options[0]!;\n if (options.length > 1) {\n const conflict: CombineConflict = { key, file: edits[0]!.file, path: edits[0]!.path, options };\n conflicts.push(conflict);\n use = pickedOption(conflict, picks);\n if (!use) {\n missing.push(conflict);\n use = opts.unpicked === 'first' ? options[0]! : null;\n }\n }\n if (!use) continue;\n const doc = docOf(edits[0]!.file);\n if (!doc) continue;\n const existing = flattenTokens(doc).find((t) => idOf(t) === key.slice(key.indexOf('#') + 1));\n // A removal removes the library's token; an edit replaces it (or adds it when the library does not have it).\n takeMine(doc, use.token, existing);\n const path = use.token?.path ?? edits[0]!.path;\n from[path] = [...new Set([...(from[path] ?? []), ...use.changes])];\n }\n const files: Record<string, string> = { ...latest };\n for (const [file, doc] of docs) {\n if (latest[file] === undefined && flattenTokens(doc).length === 0) continue;\n files[file] = serializeTokenFile(doc);\n }\n const tokens = new Set([...groups.values()].map((e) => e[0]!.path)).size;\n return { files, included: on.map((c) => c.number), edits: groups.size, tokens, conflicts, missing, from, problems };\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Picks in an address: `118:semantic/light.tokens.json#path:color.bg.default~120:...`. The change number first, then\n// the conflict key; entries joined by \"~\" (keys hold \":\" and \"#\", never \"~\").\n\nexport function encodePicks(picks: CombinePicks): string {\n return Object.entries(picks)\n .filter(([, n]) => Number.isSafeInteger(n) && n > 0)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, n]) => `${n}:${key}`)\n .join('~');\n}\n\nexport function decodePicks(raw: string | null | undefined): CombinePicks {\n const out: CombinePicks = {};\n for (const part of (raw ?? '').split('~')) {\n const i = part.indexOf(':');\n if (i < 1) continue;\n const n = Number(part.slice(0, i));\n const key = part.slice(i + 1);\n if (/^\\d{1,7}$/.test(part.slice(0, i)) && n > 0 && key.includes('#')) out[key] = n;\n }\n return out;\n}\n","// CSS custom properties that paint a token set over another one: the live preview of a token draft (Studio Tokens),\n// a change shown in Studio Components, and several changes tried together in the admin's Bridge toolbar. Pure.\nimport { resolve, type ResolveContext } from './resolver';\nimport type { TokenSet } from './token-set';\nimport { formatValue, parseColor, rgbaToHex } from './values';\n\n/** CSS value of a resolved DTCG value, the way tokens.css writes it. */\nexport function cssOf(type: string, value: unknown): string | undefined {\n if (value === undefined) return undefined;\n if (type === 'color') {\n const hex = value && typeof value === 'object' ? (value as { hex?: unknown }).hex : undefined;\n const c = parseColor(value);\n if (!c) return undefined;\n if (c.a < 1) return `rgb(${Math.round(c.r * 255)} ${Math.round(c.g * 255)} ${Math.round(c.b * 255)} / ${c.a})`;\n return typeof hex === 'string' ? hex.toLowerCase() : rgbaToHex(c);\n }\n return formatValue(type, value);\n}\n\nexport const cssVarOf = (path: string) => `--${path.replace(/\\./g, '-')}`;\n\n/**\n * CSS custom properties to set on a scope so it renders `proposed` instead of `head`: every token whose resolved value\n * differs in that context. Setting resolved values (not var() references) keeps chains correct even when the original\n * variable is declared on an ancestor.\n */\nexport function previewOverrides(head: TokenSet, proposed: TokenSet, ctx: ResolveContext): Record<string, string> {\n const out: Record<string, string> = {};\n const hctx = { ...ctx, overrides: head.overrideIndex };\n const pctx = { ...ctx, overrides: proposed.overrideIndex };\n for (const t of proposed.byPath.values()) {\n const a = resolve(head.byPath, t.path, hctx);\n const b = resolve(proposed.byPath, t.path, pctx);\n const css = cssOf(t.type, b.value);\n if (css !== undefined && JSON.stringify(a.value) !== JSON.stringify(b.value)) out[cssVarOf(t.path)] = css;\n }\n return out;\n}\n","// Apply accepted token changes onto main's files. Only files whose text actually changes are\n// returned, and inside them only the edited tokens change (layout, key order, other tools'\n// $extensions and untouched values are preserved byte for byte).\n\nimport {\n type TokenDocument,\n emptyTokenFile,\n moveToken,\n parseTokenFile,\n readTokenAt,\n removeToken,\n serializeTokenFile,\n upsertToken,\n} from './dtcg-codec';\nimport { idExtensionFor } from './id-map';\nimport { defaultScopes, effectiveScopes, sameScopes } from './scopes';\nimport { type TokenSet, defaultFile, modeFile } from './token-set';\nimport { EXT_ID, EXT_SCOPES, type LogicalToken, isMultiMode } from './types';\nimport { valuesEqual } from './values';\n\nexport interface AcceptedChange {\n /** Desired state; undefined removes the token. */\n target: LogicalToken | undefined;\n /** State on main (head) before the change; undefined for additions. */\n current: LogicalToken | undefined;\n}\n\nexport interface ComposeResult {\n /** Changed files only: path relative to the tokens directory -> new text. */\n files: Record<string, string>;\n /** Every token file after the change (changed and unchanged), for validation. */\n allFiles: Record<string, string>;\n}\n\nconst modesOf = (t: LogicalToken) => Object.keys(t.values);\n\nexport function composeFiles(head: TokenSet, originals: Record<string, string>, changes: AcceptedChange[]): ComposeResult {\n const docs = new Map<string, TokenDocument>();\n const doc = (file: string): TokenDocument => {\n let d = docs.get(file);\n if (!d) {\n const text = originals[file];\n d = text === undefined ? emptyTokenFile(file) : parseTokenFile(file, text);\n docs.set(file, d);\n }\n return d;\n };\n // Each value goes back to the file of its tier and mode: brands/<brand>, semantic/<theme>,\n // density/<density>, or the single file of a primitive, base or component token.\n const fileFor = (t: LogicalToken, mode: string, current?: LogicalToken) =>\n current?.files[mode] ??\n t.files[mode] ??\n (isMultiMode(t.tier) ? modeFile(head.layout, t.tier, mode) : undefined) ??\n defaultFile(t.tier, t.path, head.options.dirs);\n\n for (const { target, current } of changes) {\n if (!target) {\n if (current) for (const mode of modesOf(current)) removeToken(doc(fileFor(current, mode)), current.path);\n continue;\n }\n const renamed = !!current && current.path !== target.path;\n if (current) {\n for (const mode of modesOf(current)) {\n const d = doc(fileFor(current, mode));\n if (target.values[mode] === undefined) removeToken(d, current.path);\n else if (renamed) moveToken(d, current.path, target.path);\n }\n }\n\n const targetScopes = effectiveScopes(target);\n const scopesExt = sameScopes(targetScopes, defaultScopes(target.path, target.type, target.tier)) ? undefined : targetScopes;\n const scopesChanged = !current || !sameScopes(targetScopes, effectiveScopes(current));\n const descChanged = (target.description ?? '').trim() !== (current?.description ?? '').trim();\n\n for (const mode of modesOf(target)) {\n const d = doc(fileFor(target, mode, current));\n const existing = readTokenAt(d, target.path);\n const currentValue = current?.values[mode];\n // Keep main's exact spelling when the value is equal (Figma returns float noise).\n const value = currentValue !== undefined && valuesEqual(target.type, target.values[mode], currentValue) ? currentValue : target.values[mode];\n const extensions: Record<string, unknown> = {};\n if (scopesChanged) extensions[EXT_SCOPES] = scopesExt;\n if (renamed || !existing) extensions[EXT_ID] = idExtensionFor(target);\n upsertToken(d, target.path, {\n type: target.type,\n value,\n description: descChanged || !existing ? target.description : existing.description,\n extensions,\n });\n }\n }\n\n const files: Record<string, string> = {};\n const allFiles: Record<string, string> = { ...originals };\n for (const [file, d] of docs) {\n const text = serializeTokenFile(d);\n allFiles[file] = text;\n if (text !== originals[file]) files[file] = text;\n }\n return { files, allFiles };\n}\n","// Library protection: Bridge is the only way into the default branch. Whatever writes (Claude Code, Claude Design,\n// a developer, the MCP server), the change lands on a branch and reaches the default branch through a reviewed pull\n// request. GitHub enforces it with a repository ruleset on the default branch; this module builds that ruleset and\n// reads whether the default branch is protected, from rulesets and from classic branch protection.\n//\n// Pure: no fetch, no DOM. The GitHub reads live in github-client.ts (listRulesets, getRuleset, getBranchProtection,\n// listCheckRuns); Studio, the CLI and the MCP server share these functions.\n\n/** A ruleset rule as GitHub returns and accepts it. */\nexport interface RulesetRule {\n type: string;\n parameters?: Record<string, unknown>;\n}\n\nexport interface RulesetBypassActor {\n actor_id: number | null;\n actor_type: 'RepositoryRole' | 'Team' | 'Integration' | 'OrganizationAdmin' | 'DeployKey';\n bypass_mode: 'always' | 'pull_request';\n}\n\n/** A repository ruleset (GET /repos/{o}/{r}/rulesets/{id}). The list endpoint leaves out `rules`. */\nexport interface Ruleset {\n id?: number;\n name: string;\n target?: 'branch' | 'tag' | 'push' | string;\n enforcement: 'active' | 'evaluate' | 'disabled' | string;\n conditions?: { ref_name?: { include?: string[]; exclude?: string[] } } | null;\n rules?: RulesetRule[];\n bypass_actors?: RulesetBypassActor[];\n /** Where the ruleset is edited on GitHub. */\n html_url?: string;\n _links?: { html?: { href?: string } };\n}\n\n/** The body of POST /repos/{o}/{r}/rulesets. */\nexport interface RulesetPayload {\n name: string;\n target: 'branch';\n enforcement: 'active';\n conditions: { ref_name: { include: string[]; exclude: string[] } };\n rules: RulesetRule[];\n bypass_actors: RulesetBypassActor[];\n}\n\n/**\n * Classic branch protection (GET /repos/{o}/{r}/branches/{b}/protection), the fields Bridge reads.\n * `null` means the branch has none; `undefined` means it could not be read (no token, no admin access).\n */\nexport interface ClassicProtection {\n required_pull_request_reviews?: { required_approving_review_count?: number } | null;\n required_status_checks?: { contexts?: string[]; checks?: { context: string }[] } | null;\n allow_force_pushes?: { enabled: boolean } | null;\n allow_deletions?: { enabled: boolean } | null;\n}\n\n/** What protecting the library takes, in the order Studio names them. */\nexport type ProtectionPart = 'review' | 'checks' | 'history' | 'deletion';\nexport const PROTECTION_PARTS: readonly ProtectionPart[] = ['review', 'checks', 'history', 'deletion'];\n\nexport type ProtectionKind = 'protected' | 'partial' | 'unprotected' | 'unknown';\n\nexport interface ProtectionState {\n kind: ProtectionKind;\n /** Parts not enforced on the default branch (empty when protected; every part when unprotected or unknown). */\n missing: ProtectionPart[];\n /** The Bridge ruleset (by name), when one exists, active or not: \"Complete protection\" updates it in place. */\n bridgeRulesetId?: number;\n /** Where to see the rule that protects the branch on GitHub, when one does. */\n url?: string;\n}\n\n/** The name Bridge gives its ruleset. Bridge finds it again by this name. */\nexport const protectionRulesetName = (defaultBranch: string) => `Protect the library (${defaultBranch})`;\n\n/** GitHub's built-in repository role id for \"Admin\", used in bypass_actors. */\nexport const ADMIN_ROLE_ID = 5;\n\nexport interface ProtectionOptions {\n /** Check names that must pass before a merge (see requiredCheckNames). Empty: no checks rule. */\n checks: string[];\n /** Approvals a pull request needs. Never below 1. */\n approvals: number;\n /** Let repository admins merge a pull request without its approvals (the owner override). */\n adminBypass: boolean;\n}\n\n/**\n * The ruleset that protects the library. Choices:\n * - Target `~DEFAULT_BRANCH`, not a branch name: it follows a rename of the default branch.\n * - `deletion` and `non_fast_forward`: nobody deletes the default branch or rewrites its history.\n * - `pull_request` with at least 1 approval: every change goes through a reviewed pull request, direct pushes are\n * refused whoever pushes. Stale approvals are dismissed on a new push, so what was approved is what merges.\n * Code owner review and \"approval of the most recent push\" stay off: CODEOWNERS often holds placeholders, and a\n * team of two must still be able to ship.\n * - `required_status_checks`: the CI jobs that ran on recent pull requests must pass. Not strict (the branch does\n * not have to be up to date), which keeps merges from queueing behind each other.\n * - Bypass: repository admins in `pull_request` mode only. They keep the owner override (merge a pull request\n * whose approvals are missing) but cannot push to the default branch either.\n */\nexport function protectionRuleset(config: { repo?: { defaultBranch?: string } | undefined } | null | undefined, opts: ProtectionOptions): RulesetPayload {\n const branch = config?.repo?.defaultBranch ?? 'main';\n const approvals = Math.max(1, Math.floor(Number.isFinite(opts.approvals) ? opts.approvals : 1));\n const checks = [...new Set(opts.checks.map((c) => c.trim()).filter(Boolean))];\n const rules: RulesetRule[] = [\n { type: 'deletion' },\n { type: 'non_fast_forward' },\n {\n type: 'pull_request',\n parameters: {\n required_approving_review_count: approvals,\n dismiss_stale_reviews_on_push: true,\n require_code_owner_review: false,\n require_last_push_approval: false,\n required_review_thread_resolution: false,\n },\n },\n ];\n if (checks.length) {\n rules.push({\n type: 'required_status_checks',\n parameters: {\n strict_required_status_checks_policy: false,\n required_status_checks: checks.map((context) => ({ context })),\n },\n });\n }\n return {\n name: protectionRulesetName(branch),\n target: 'branch',\n enforcement: 'active',\n conditions: { ref_name: { include: ['~DEFAULT_BRANCH'], exclude: [] } },\n rules,\n bypass_actors: opts.adminBypass ? [{ actor_id: ADMIN_ROLE_ID, actor_type: 'RepositoryRole', bypass_mode: 'pull_request' }] : [],\n };\n}\n\n/** Minimal check run shape (github-client CheckRun fits). `app` is the GitHub App slug when known. */\nexport interface CheckRunLike {\n name: string;\n status?: string;\n conclusion: string | null;\n app?: string | undefined;\n}\n\nconst isVercel = (r: CheckRunLike) => /vercel/i.test(r.app ?? '') || /^vercel\\b/i.test(r.name);\nconst ran = (r: CheckRunLike) => r.conclusion !== 'skipped' && r.conclusion !== 'cancelled' && r.conclusion !== 'stale';\n\n/**\n * The check names to require, read from the repository's own CI, never hardcoded: the check runs of the default\n * branch's latest commit, without Vercel (deploy previews, not tests) and without skipped ones. When the head of a\n * recent pull request is given, only checks that also ran there are kept: a job that runs on pushes to the default\n * branch only (a release job) never reports on a pull request, and requiring it would block every merge.\n */\nexport function requiredCheckNames(defaultBranchRuns: CheckRunLike[], pullRequestRuns?: CheckRunLike[]): string[] {\n const names = [...new Set(defaultBranchRuns.filter((r) => !isVercel(r) && ran(r)).map((r) => r.name))];\n if (!pullRequestRuns?.length) return names;\n const onPulls = new Set(pullRequestRuns.filter((r) => !isVercel(r)).map((r) => r.name));\n return names.filter((n) => onPulls.has(n));\n}\n\n/** Converts a ref pattern (fnmatch: `*` within a segment, `**` across) to a RegExp. */\nfunction refPattern(pattern: string): RegExp {\n const src = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*\\*/g, '\\u0000')\n .replace(/\\*/g, '[^/]*')\n .replace(/\\?/g, '[^/]')\n .replace(/\\u0000/g, '.*');\n return new RegExp(`^${src}$`);\n}\n\n/** True when a branch ruleset's conditions cover the default branch. */\nexport function rulesetTargetsDefault(ruleset: Ruleset, defaultBranch: string): boolean {\n if (ruleset.target && ruleset.target !== 'branch') return false;\n const ref = `refs/heads/${defaultBranch}`;\n const hit = (p: string) => p === '~ALL' || p === '~DEFAULT_BRANCH' || p === ref || p === defaultBranch || refPattern(p.startsWith('refs/') ? p : `refs/heads/${p}`).test(ref);\n const cond = ruleset.conditions?.ref_name;\n // A repository ruleset with no ref condition applies to nothing; GitHub requires one.\n if (!cond) return false;\n if ((cond.exclude ?? []).some(hit)) return false;\n return (cond.include ?? []).some(hit);\n}\n\nconst count = (v: unknown) => (typeof v === 'number' ? v : 0);\n\n/** The parts one ruleset enforces (active rulesets only; \"evaluate\" only reports). */\nfunction rulesetParts(ruleset: Ruleset): Set<ProtectionPart> {\n const parts = new Set<ProtectionPart>();\n if (ruleset.enforcement !== 'active') return parts;\n for (const rule of ruleset.rules ?? []) {\n if (rule.type === 'deletion') parts.add('deletion');\n if (rule.type === 'non_fast_forward') parts.add('history');\n if (rule.type === 'pull_request' && count(rule.parameters?.required_approving_review_count) >= 1) parts.add('review');\n if (rule.type === 'required_status_checks' && Array.isArray(rule.parameters?.required_status_checks) && (rule.parameters.required_status_checks as unknown[]).length > 0) parts.add('checks');\n }\n return parts;\n}\n\n/** The parts classic branch protection enforces. Force pushes and deletions are refused unless allowed. */\nfunction classicParts(p: ClassicProtection): Set<ProtectionPart> {\n const parts = new Set<ProtectionPart>();\n if (count(p.required_pull_request_reviews?.required_approving_review_count) >= 1) parts.add('review');\n if (((p.required_status_checks?.contexts?.length ?? 0) || (p.required_status_checks?.checks?.length ?? 0)) > 0) parts.add('checks');\n if (!p.allow_force_pushes?.enabled) parts.add('history');\n if (!p.allow_deletions?.enabled) parts.add('deletion');\n return parts;\n}\n\nconst rulesetUrl = (r: Ruleset) => r.html_url ?? r._links?.html?.href;\n\n/**\n * Whether the default branch is protected, from full rulesets (with `rules`; null when they could not be read) and\n * classic branch protection (null when the branch has none, undefined when it could not be read).\n * - protected: review, checks, no history rewrite and no deletion are all enforced.\n * - partial: some of them are.\n * - unprotected: none of them, and both sources were read.\n * - unknown: nothing could be read, or nothing was found in one source while the other could not be read.\n */\nexport function protectionState(rulesets: Ruleset[] | null | undefined, branchProtection: ClassicProtection | null | undefined, defaultBranch: string): ProtectionState {\n const bridge = rulesets?.find((r) => r.name === protectionRulesetName(defaultBranch));\n const extra = bridge?.id !== undefined ? { bridgeRulesetId: bridge.id } : {};\n const covered = new Set<ProtectionPart>();\n let url: string | undefined;\n for (const r of rulesets ?? []) {\n if (!rulesetTargetsDefault(r, defaultBranch)) continue;\n const parts = rulesetParts(r);\n if (parts.size && !url) url = rulesetUrl(r);\n parts.forEach((p) => covered.add(p));\n }\n if (branchProtection) classicParts(branchProtection).forEach((p) => covered.add(p));\n const missing = PROTECTION_PARTS.filter((p) => !covered.has(p));\n const withUrl = url ? { url } : {};\n if (!missing.length) return { kind: 'protected', missing, ...extra, ...withUrl };\n const unreadable = rulesets == null || branchProtection === undefined;\n if (covered.size === 0) return { kind: unreadable ? 'unknown' : 'unprotected', missing, ...extra };\n return { kind: 'partial', missing, ...extra, ...withUrl };\n}\n\n/** Plain words for each part, for designers: no \"ruleset\", \"branch\" or \"force push\". */\nexport const PROTECTION_PART_PHRASE: Record<ProtectionPart, string> = {\n review: 'changes can skip review',\n checks: 'checks do not have to pass',\n history: 'past changes can be rewritten',\n deletion: 'the library can be deleted',\n};\n\nconst joinAnd = (xs: string[]) => (xs.length <= 1 ? (xs[0] ?? '') : `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`);\n\n/** The one sentence Studio, the CLI and the MCP server show for a protection state. */\nexport function protectionSentence(state: ProtectionState): string {\n switch (state.kind) {\n case 'protected':\n return 'Protected: every change goes through review.';\n case 'unprotected':\n return 'Your library can be changed without review.';\n case 'partial': {\n const s = joinAnd(state.missing.map((p) => PROTECTION_PART_PHRASE[p]));\n return `Partly protected: ${s}.`;\n }\n default:\n return 'Protection status unknown: GitHub did not let this token read it.';\n }\n}\n","// Minimal GitHub REST client over fetch. The token is passed in; nothing is read from the\n// environment. Talks to api.github.com (the Figma plugin manifest allows nothing else) and, for\n// token-less reads of public repos, raw.githubusercontent.com, which has no hourly API limit.\n// Bulk reads go through the git trees and blobs endpoints; single files can use the contents API.\n//\n// Writes refuse protected branches (main, master and whatever the caller adds) whatever the caller\n// asks: the client is the last guard between an agent and the default branch.\n\nimport { type BridgeConfig, CONFIG_FILE, ConfigError, DEFAULT_TOKEN_PATHS, loadConfig } from './config';\nimport { assertSafeBranch, DEFAULT_PROTECTED_BRANCHES, ProtectedBranchError } from './governance';\nimport type { ClassicProtection, Ruleset, RulesetPayload } from './protection';\n\n/**\n * What an auth failure means for the token:\n * - \"rejected\": GitHub refused the token itself (401). It was revoked, regenerated or has expired; every call\n * with it will fail until it is replaced.\n * - \"missing-permission\": the token works but lacks a permission this call needs (403 \"Resource not accessible\n * by personal access token\", or a permission GitHub names in X-Accepted-GitHub-Permissions).\n * Undefined for everything else, including rate limits and a missing token.\n */\nexport type GitHubAuthState = 'rejected' | 'missing-permission';\n\n/** Fine-grained token permission names, as GitHub spells them (issues, pull_requests, contents...). */\nexport type GitHubPermission = string;\n\nexport interface GitHubErrorInfo {\n auth?: GitHubAuthState | undefined;\n /** The permission the call needed, when GitHub or the endpoint tells (only with auth \"missing-permission\"). */\n permission?: GitHubPermission | undefined;\n}\n\nexport class GitHubError extends Error {\n /** Set when the failure is about the token: rejected (401) or missing a permission (403). */\n readonly auth: GitHubAuthState | undefined;\n /** With auth \"missing-permission\": the permission the call needed, when known. */\n readonly permission: GitHubPermission | undefined;\n\n constructor(\n readonly status: number,\n message: string,\n readonly detail?: string,\n info: GitHubErrorInfo = {},\n ) {\n super(message);\n this.name = 'GitHubError';\n this.auth = info.auth;\n this.permission = info.permission;\n }\n}\n\n/** True when `err` says GitHub refused the token itself (revoked, regenerated or expired). */\nexport const isTokenRejected = (err: unknown): boolean => err instanceof GitHubError && err.auth === 'rejected';\n\n/** True when `err` says the token works but lacks a permission for that call. */\nexport const isMissingPermission = (err: unknown): boolean => err instanceof GitHubError && err.auth === 'missing-permission';\n\nconst PERMISSION_LABELS: Record<string, string> = {\n issues: 'Issues',\n pull_requests: 'Pull requests',\n contents: 'Contents',\n checks: 'Checks',\n statuses: 'Commit statuses',\n metadata: 'Metadata',\n actions: 'Actions',\n deployments: 'Deployments',\n workflows: 'Workflows',\n administration: 'Administration',\n};\n\n/** \"pull_requests\" -> \"Pull requests\", as GitHub labels it on the token page. */\nexport function permissionLabel(permission: GitHubPermission): string {\n return PERMISSION_LABELS[permission] ?? permission.replace(/_/g, ' ').replace(/^./, (c) => c.toUpperCase());\n}\n\n/** Where a fine-grained token's permissions are edited. */\nexport const TOKEN_SETTINGS_URL = 'https://github.com/settings/personal-access-tokens';\n\n/** The one sentence for a token GitHub no longer accepts. */\nexport const TOKEN_REJECTED_MESSAGE = 'Your GitHub token stopped working. It was revoked, regenerated or has expired: replace it with a new one.';\n\n/**\n * \"This token cannot create issues. Add Issues: Read and write on GitHub.\" `action` is a verb phrase\n * (\"create issues\"); without it the sentence names only the permission.\n */\nexport function missingPermissionMessage(permission: GitHubPermission | undefined, action?: string): string {\n const what = action ? `This token cannot ${action}.` : 'This token is missing a permission for this.';\n if (!permission) return `${what} Check its repository permissions on GitHub (Contents and Pull requests need Read and write).`;\n return `${what} Add ${permissionLabel(permission)}: Read and write on GitHub.`;\n}\n\n/**\n * The permission a refused call needed. GitHub names it in X-Accepted-GitHub-Permissions (\"issues=write\",\n * alternatives split by \";\"); otherwise the endpoint says it (/issues, /pulls, /contents, /git...).\n */\nexport function requiredPermission(path: string, acceptedHeader?: string | null): GitHubPermission | undefined {\n if (acceptedHeader) {\n const first = acceptedHeader.split(';')[0]!.split(',').map((p) => p.trim().split('=')[0]!.trim()).filter((p) => p && p !== 'metadata');\n if (first.length) return first[0];\n }\n const p = path.replace(/[?#].*$/, '');\n if (/\\/repos\\/[^/]+\\/[^/]+\\/(issues|labels|milestones)(\\/|$)/.test(p)) return 'issues';\n if (/\\/repos\\/[^/]+\\/[^/]+\\/pulls(\\/|$)/.test(p)) return 'pull_requests';\n if (/\\/repos\\/[^/]+\\/[^/]+\\/(rulesets(\\/|$)|branches\\/.+\\/protection$)/.test(p)) return 'administration';\n if (/\\/repos\\/[^/]+\\/[^/]+\\/(contents|git|commits|branches|merges)(\\/|$)/.test(p)) return 'contents';\n if (/\\/repos\\/[^/]+\\/[^/]+\\/(check-runs|check-suites)(\\/|$)/.test(p)) return 'checks';\n if (/\\/repos\\/[^/]+\\/[^/]+\\/statuses(\\/|$)/.test(p)) return 'statuses';\n if (/\\/repos\\/[^/]+\\/[^/]+\\/deployments(\\/|$)/.test(p)) return 'deployments';\n if (/\\/repos\\/[^/]+\\/[^/]+\\/actions(\\/|$)/.test(p)) return 'actions';\n return undefined;\n}\n\nconst PERMISSION_DENIED = /not accessible by (personal access token|integration)|must have (admin|push|write) (rights|access)|write access to repository not granted|permission to .* denied/i;\n\n/**\n * Classifies a GitHub error response for the token. 401 with a token sent = rejected. 403 (not a rate limit,\n * not archived) where GitHub names a permission or says the resource is not accessible = missing permission.\n */\nexport function classifyAuth(\n status: number,\n detail: string,\n opts: { path?: string; acceptedPermissions?: string | null; withToken?: boolean } = {},\n): GitHubErrorInfo {\n if (status === 401 && opts.withToken !== false) return { auth: 'rejected' };\n if (status !== 403 || /rate limit|archived/i.test(detail)) return {};\n if (opts.acceptedPermissions || PERMISSION_DENIED.test(detail)) {\n return { auth: 'missing-permission', permission: requiredPermission(opts.path ?? '', opts.acceptedPermissions) };\n }\n return {};\n}\n\nexport interface RepoInfo {\n fullName: string;\n defaultBranch: string;\n private: boolean;\n permissions: { admin?: boolean; push?: boolean; pull?: boolean } | undefined;\n}\n\nexport interface TreeEntry {\n path: string;\n type: 'blob' | 'tree' | 'commit';\n sha: string;\n mode: string;\n}\n\nexport interface CompareResult {\n status: string;\n aheadBy: number;\n behindBy: number;\n files: { filename: string; status: string }[];\n}\n\nexport interface PullRequest {\n number: number;\n url: string;\n title: string;\n draft: boolean;\n headRef: string;\n}\n\nexport interface Review {\n id: number;\n user: string | undefined;\n state: string;\n body: string;\n submittedAt?: string | undefined;\n}\n\nexport interface PullRequestSummary {\n number: number;\n title: string;\n /** \"open\", \"closed\" or \"merged\". */\n state: string;\n draft: boolean;\n author: string;\n headRef: string;\n headSha: string;\n baseRef: string;\n labels: string[];\n url: string;\n updatedAt: string;\n /** Description, when the list endpoint returns it (component change requests read \"Closes #n\" from it). */\n body?: string | undefined;\n}\n\nexport interface ClientOptions {\n /** API base, for GitHub Enterprise or tests. */\n apiUrl?: string;\n /** Raw file host used for token-less reads. */\n rawUrl?: string;\n /** Branches no write may target. Default main and master; the repo's default branch belongs here too. */\n protectedBranches?: string[];\n /** When set, branches this client creates must start with it (agents use \"bridge/\"). */\n branchPrefix?: string;\n /**\n * How a person adds a token where this client runs, for the rate-limit message without one (\"set GITHUB_TOKEN in\n * the MCP server config\"). Default: \"add a GitHub token\".\n */\n tokenHint?: string;\n}\n\n/**\n * The sentence for GitHub's exhausted hourly limit. With a token, the token's own limit is used up: wait. Without one,\n * the shared limit for anonymous reads is (60 an hour per address): say how to get a higher one.\n */\nexport function rateLimitMessage(x: { withToken: boolean; resetsAt?: Date; tokenHint?: string }): string {\n const when = x.resetsAt ? ` It resets at ${x.resetsAt.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}.` : '';\n if (x.withToken) return `GitHub's hourly request limit for this token is used up.${when} Try again after that.`;\n const hint = x.tokenHint ?? 'add a GitHub token';\n return `GitHub's hourly limit for requests without a token (60 an hour) is used up.${when} To keep going now, ${hint}: a token gets 5,000 requests an hour.`;\n}\n\n/** A file in a new commit: text content, or null to delete it. */\nexport interface CommitFile {\n path: string;\n content: string | null;\n}\n\nexport interface CheckRun {\n id: number;\n name: string;\n status: string;\n conclusion: string | null;\n url: string | undefined;\n /** Slug of the GitHub App that reported it (\"github-actions\", \"vercel\"), when GitHub says. */\n app?: string | undefined;\n}\n\nexport interface CommitSummary {\n sha: string;\n parents: string[];\n /** ISO date the commit landed (committer date). */\n date: string;\n /** GitHub login when known, else the git author name. */\n author: string;\n message: string;\n}\n\nexport interface PullRequestFile {\n filename: string;\n status: string;\n additions: number;\n deletions: number;\n}\n\nexport type FetchLike = (url: string, init?: { method?: string; headers?: Record<string, string>; body?: string }) => Promise<{\n ok: boolean;\n status: number;\n headers?: { get(name: string): string | null };\n json(): Promise<unknown>;\n text(): Promise<string>;\n}>;\n\nexport interface RetryPolicy {\n /** Attempts for idempotent calls (GET, and content-addressed blob/tree/commit creation). */\n attempts: number;\n /** First backoff in ms; doubles each retry. */\n baseDelayMs: number;\n sleep: (ms: number) => Promise<void>;\n}\n\nconst DEFAULT_RETRY: RetryPolicy = { attempts: 3, baseDelayMs: 600, sleep: (ms) => new Promise((r) => setTimeout(r, ms)) };\n\n/** Transient failures worth retrying: network errors, 5xx, and secondary rate limits. */\nconst isTransient = (status: number, detail: string) => status === 0 || status >= 500 || status === 429 || (status === 403 && /secondary rate limit/i.test(detail));\n\nconst API = 'https://api.github.com';\nconst RAW = 'https://raw.githubusercontent.com';\n\n/** \"owner/name\", a github.com URL or an SSH remote. */\nexport function parseRepo(repo: string): { owner: string; name: string } {\n const m = /^\\s*(?:https?:\\/\\/github\\.com\\/|git@github\\.com:)?([A-Za-z0-9-]+)\\/([A-Za-z0-9._-]+?)(?:\\.git)?\\/?\\s*$/.exec(repo);\n if (!m) throw new Error(`\"${repo}\" is not a repository. Use the form owner/name.`);\n return { owner: m[1]!, name: m[2]! };\n}\n\nexport function utf8ToBase64(text: string): string {\n const bytes = new TextEncoder().encode(text);\n let bin = '';\n for (const b of bytes) bin += String.fromCharCode(b);\n return btoa(bin);\n}\n\nexport function base64ToUtf8(b64: string): string {\n const bin = atob(b64.replace(/\\s/g, ''));\n const bytes = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);\n return new TextDecoder('utf-8').decode(bytes);\n}\n\nconst encodeRef = (ref: string) => ref.split('/').map(encodeURIComponent).join('/');\n\nexport class GitHubClient {\n readonly owner: string;\n readonly name: string;\n private readonly blobCache = new Map<string, string>();\n private readonly api: string;\n private readonly protectedBranches: string[];\n\n constructor(\n repo: string,\n private readonly token: string,\n private readonly fetchImpl: FetchLike = (url, init) => fetch(url, init),\n private readonly retry: RetryPolicy = DEFAULT_RETRY,\n private readonly options: ClientOptions = {},\n ) {\n const r = parseRepo(repo);\n this.owner = r.owner;\n this.name = r.name;\n this.api = (options.apiUrl ?? API).replace(/\\/$/, '');\n this.protectedBranches = options.protectedBranches ?? DEFAULT_PROTECTED_BRANCHES;\n }\n\n /** \"owner/name\". */\n get fullName() {\n return `${this.owner}/${this.name}`;\n }\n\n /** Whether a token was given (without one, every write is refused before any request). */\n get canWrite() {\n return Boolean(this.token);\n }\n\n /** Throws unless `branch` may be written: not protected, not the base, and with the agent prefix when set. */\n assertWritableBranch(branch: string, base?: string): void {\n try {\n assertSafeBranch(branch, { protectedBranches: this.protectedBranches, base, branchPrefix: this.options.branchPrefix });\n } catch (err) {\n if (err instanceof ProtectedBranchError) throw new GitHubError(403, err.message, 'protected-branch');\n throw err;\n }\n }\n\n private assertToken(what: string): void {\n if (!this.token) throw new GitHubError(401, `${what} needs a GitHub token (contents and pull requests, read and write, on this repository only). Without one Bridge is read-only.`, 'no-token');\n }\n\n private get repoPath() {\n return `/repos/${this.owner}/${this.name}`;\n }\n\n private async request<T>(method: string, path: string, body?: unknown, retryable = method === 'GET'): Promise<T> {\n const attempts = retryable ? Math.max(1, this.retry.attempts) : 1;\n for (let attempt = 1; ; attempt++) {\n try {\n return await this.once<T>(method, path, body);\n } catch (err) {\n const e = err as GitHubError;\n if (attempt >= attempts || !(e instanceof GitHubError) || !isTransient(e.status, e.detail ?? '')) throw err;\n await this.retry.sleep(this.retry.baseDelayMs * 2 ** (attempt - 1));\n }\n }\n }\n\n private async once<T>(method: string, path: string, body?: unknown): Promise<T> {\n const headers: Record<string, string> = {\n Accept: 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n };\n if (this.token) headers.Authorization = `Bearer ${this.token}`;\n if (body !== undefined) headers['Content-Type'] = 'application/json';\n let res: Awaited<ReturnType<FetchLike>>;\n try {\n res = await this.fetchImpl(`${this.api}${path}`, { method, headers, ...(body !== undefined ? { body: JSON.stringify(body) } : {}) });\n } catch (err) {\n throw new GitHubError(0, 'Could not reach GitHub. Check your connection, then try again.', (err as Error).message);\n }\n if (res.status === 204) return undefined as T;\n if (!res.ok) {\n let detail = '';\n try {\n const data = (await res.json()) as { message?: string; errors?: ({ message?: string } | string)[] };\n detail = [data.message, ...(data.errors ?? []).map((e) => (typeof e === 'string' ? e : e.message))].filter(Boolean).join(' ');\n } catch {\n detail = '';\n }\n const remaining = res.headers?.get('x-ratelimit-remaining');\n const reset = res.headers?.get('x-ratelimit-reset');\n if ((res.status === 403 || res.status === 429) && remaining === '0') {\n const resetsAt = reset ? new Date(Number(reset) * 1000) : undefined;\n throw new GitHubError(429, rateLimitMessage({ withToken: Boolean(this.token), resetsAt, tokenHint: this.options.tokenHint }), detail);\n }\n const info = classifyAuth(res.status, detail, {\n path,\n acceptedPermissions: res.headers?.get('x-accepted-github-permissions'),\n withToken: Boolean(this.token),\n });\n throw new GitHubError(res.status, friendlyMessage(res.status, detail, info), detail, info);\n }\n return (await res.json()) as T;\n }\n\n async getRepo(): Promise<RepoInfo> {\n const r = await this.request<{ full_name: string; default_branch: string; private: boolean; permissions?: RepoInfo['permissions'] }>(\n 'GET',\n this.repoPath,\n );\n return { fullName: r.full_name, defaultBranch: r.default_branch, private: r.private, permissions: r.permissions };\n }\n\n /** Commit sha a branch points to, or undefined when the branch does not exist. */\n async getBranchSha(branch: string): Promise<string | undefined> {\n try {\n const r = await this.request<{ object: { sha: string } }>('GET', `${this.repoPath}/git/ref/heads/${encodeRef(branch)}`);\n return r.object.sha;\n } catch (err) {\n if (err instanceof GitHubError && err.status === 404) return undefined;\n throw err;\n }\n }\n\n async getCommitTree(commitSha: string): Promise<string> {\n const r = await this.request<{ tree: { sha: string } }>('GET', `${this.repoPath}/git/commits/${commitSha}`);\n return r.tree.sha;\n }\n\n async getTree(treeSha: string, recursive = true): Promise<{ entries: TreeEntry[]; truncated: boolean }> {\n const r = await this.request<{ tree: TreeEntry[]; truncated: boolean }>(\n 'GET',\n `${this.repoPath}/git/trees/${treeSha}${recursive ? '?recursive=1' : ''}`,\n );\n return { entries: r.tree, truncated: r.truncated };\n }\n\n async getBlobText(sha: string): Promise<string> {\n const cached = this.blobCache.get(sha);\n if (cached !== undefined) return cached;\n const r = await this.request<{ content: string; encoding: string }>('GET', `${this.repoPath}/git/blobs/${sha}`);\n const text = r.encoding === 'base64' ? base64ToUtf8(r.content) : r.content;\n this.blobCache.set(sha, text);\n return text;\n }\n\n async compare(base: string, head: string): Promise<CompareResult> {\n const r = await this.request<{ status: string; ahead_by: number; behind_by: number; files?: { filename: string; status: string }[] }>(\n 'GET',\n `${this.repoPath}/compare/${base}...${head}`,\n );\n return { status: r.status, aheadBy: r.ahead_by, behindBy: r.behind_by, files: (r.files ?? []).map((f) => ({ filename: f.filename, status: f.status })) };\n }\n\n // --- History (read only) ----------------------------------------------------------------------\n\n /** Commits on a ref, newest first, optionally only those touching `path` (a file or directory). */\n async listCommits(opts: { sha?: string; path?: string; perPage?: number; page?: number } = {}): Promise<CommitSummary[]> {\n const q = new URLSearchParams();\n if (opts.sha) q.set('sha', opts.sha);\n if (opts.path) q.set('path', opts.path);\n q.set('per_page', String(Math.min(100, opts.perPage ?? 30)));\n if (opts.page) q.set('page', String(opts.page));\n const r = await this.request<Record<string, any>[]>('GET', `${this.repoPath}/commits?${q}`);\n return r.map(toCommitSummary);\n }\n\n /** One commit: message, author, date and parents. */\n async getCommitInfo(sha: string): Promise<CommitSummary> {\n return toCommitSummary(await this.request<Record<string, any>>('GET', `${this.repoPath}/commits/${encodeRef(sha)}`));\n }\n\n /** Pull requests a commit belongs to (merged ones first): how a commit on main finds its PR. */\n async listPullRequestsForCommit(sha: string): Promise<(PullRequestSummary & { body: string; mergedAt?: string; mergeCommitSha?: string })[]> {\n const r = await this.request<Record<string, any>[]>('GET', `${this.repoPath}/commits/${encodeRef(sha)}/pulls`);\n return r\n .map((p) => ({ ...toSummary(p), body: p.body ?? '', ...(p.merged_at ? { mergedAt: p.merged_at as string } : {}), ...(p.merge_commit_sha ? { mergeCommitSha: p.merge_commit_sha as string } : {}) }))\n .sort((a, b) => Number(Boolean(b.mergedAt)) - Number(Boolean(a.mergedAt)));\n }\n\n /** Tags with the commit they point to, newest first as GitHub lists them. */\n async listTags(perPage = 30): Promise<{ name: string; sha: string }[]> {\n const r = await this.request<{ name: string; commit: { sha: string } }[]>('GET', `${this.repoPath}/tags?per_page=${Math.min(100, perPage)}`);\n return r.map((t) => ({ name: t.name, sha: t.commit.sha }));\n }\n\n async createBlob(content: string): Promise<string> {\n // Blobs, trees and commits are content-addressed: retrying a create is harmless.\n const r = await this.request<{ sha: string }>('POST', `${this.repoPath}/git/blobs`, { content, encoding: 'utf-8' }, true);\n return r.sha;\n }\n\n /** A tree on top of `baseTree`. Each file gives a blob `sha`, inline `content`, or `sha: null` to delete. */\n async createTree(baseTree: string, files: ({ path: string; sha: string | null } | { path: string; content: string })[]): Promise<string> {\n const r = await this.request<{ sha: string }>('POST', `${this.repoPath}/git/trees`, {\n base_tree: baseTree,\n tree: files.map((f) => ({ path: f.path, mode: '100644', type: 'blob', ...('content' in f ? { content: f.content } : { sha: f.sha }) })),\n }, true);\n return r.sha;\n }\n\n async createCommit(message: string, tree: string, parents: string[]): Promise<string> {\n const r = await this.request<{ sha: string }>('POST', `${this.repoPath}/git/commits`, { message, tree, parents }, true);\n return r.sha;\n }\n\n /** Create a new branch. Refuses protected branches; GitHub refuses existing ones, so nothing is overwritten. */\n async createBranch(branch: string, sha: string): Promise<void> {\n this.assertWritableBranch(branch);\n await this.request('POST', `${this.repoPath}/git/refs`, { ref: `refs/heads/${branch}`, sha });\n }\n\n /** Fast-forward a branch. Never forces: a concurrent push makes this fail instead of losing work. */\n async updateBranch(branch: string, sha: string): Promise<void> {\n this.assertWritableBranch(branch);\n await this.request('PATCH', `${this.repoPath}/git/refs/heads/${encodeRef(branch)}`, { sha, force: false });\n }\n\n /**\n * One commit with `files` on top of `base`, on the new branch `branch`. The branch is created, never\n * moved, so an existing branch is never overwritten. Refuses protected branches and the base itself.\n */\n async commitToNewBranch(input: { base: string; branch: string; message: string; files: CommitFile[] }): Promise<{ sha: string; branch: string }> {\n this.assertToken('Creating a branch');\n this.assertWritableBranch(input.branch, input.base);\n const baseSha = await this.getBranchSha(input.base);\n if (!baseSha) throw new GitHubError(404, `Base branch \"${input.base}\" not found.`);\n const baseTree = await this.getCommitTree(baseSha);\n const tree = await this.createTree(baseTree, input.files.map((f) => (f.content === null ? { path: f.path, sha: null } : { path: f.path, content: f.content })));\n const sha = await this.createCommit(input.message, tree, [baseSha]);\n await this.createBranch(input.branch, sha);\n return { sha, branch: input.branch };\n }\n\n /** The same client (token, fetch, retry, protected branches) with another required branch prefix (`explore/`). */\n withBranchPrefix(branchPrefix: string | undefined): GitHubClient {\n return new GitHubClient(this.fullName, this.token, this.fetchImpl, this.retry, { ...this.options, protectedBranches: this.protectedBranches, branchPrefix });\n }\n\n /**\n * One commit with `files` on top of an existing branch, fast-forwarded (never forced). Refuses protected\n * branches and, with a branch prefix, branches without it: explorations take token edits this way.\n */\n async commitToBranch(input: { branch: string; message: string; files: CommitFile[] }): Promise<{ sha: string; branch: string }> {\n this.assertToken('Committing to a branch');\n this.assertWritableBranch(input.branch);\n const head = await this.getBranchSha(input.branch);\n if (!head) throw new GitHubError(404, `Branch \"${input.branch}\" not found. Start it first.`);\n const baseTree = await this.getCommitTree(head);\n const tree = await this.createTree(baseTree, input.files.map((f) => (f.content === null ? { path: f.path, sha: null } : { path: f.path, content: f.content })));\n const sha = await this.createCommit(input.message, tree, [head]);\n await this.updateBranch(input.branch, sha);\n return { sha, branch: input.branch };\n }\n\n /**\n * Marks a draft pull request ready for review. REST cannot unset `draft`, so this is the GraphQL mutation\n * markPullRequestReadyForReview, with the same token (pull requests: write).\n */\n async markReadyForReview(n: number): Promise<void> {\n this.assertToken('Marking a pull request ready for review');\n const pr = await this.request<{ node_id?: string; draft?: boolean }>('GET', `${this.repoPath}/pulls/${n}`);\n if (pr.draft === false) return;\n if (!pr.node_id) throw new GitHubError(422, `Pull request #${n} has no node id: mark it ready for review on GitHub.`);\n const r = await this.request<{ data?: unknown; errors?: { message?: string }[] }>('POST', '/graphql', {\n query: 'mutation($id: ID!) { markPullRequestReadyForReview(input: { pullRequestId: $id }) { pullRequest { number isDraft } } }',\n variables: { id: pr.node_id },\n });\n if (r?.errors?.length) {\n const detail = r.errors.map((e) => e.message).filter(Boolean).join(' ');\n throw new GitHubError(422, `GitHub refused to mark #${n} ready for review${detail ? `: ${detail}` : '.'} Use \"Ready for review\" on GitHub instead.`, detail);\n }\n }\n\n /**\n * Turns an open pull request back into a draft: the GraphQL mutation convertPullRequestToDraft (REST cannot set\n * `draft` either), same token. No-op when it is already a draft.\n */\n async convertToDraft(n: number): Promise<void> {\n this.assertToken('Turning a pull request back into a draft');\n const pr = await this.request<{ node_id?: string; draft?: boolean; state?: string }>('GET', `${this.repoPath}/pulls/${n}`);\n if (pr.draft === true) return;\n if (pr.state && pr.state !== 'open') throw new GitHubError(422, `Pull request #${n} is ${pr.state}: only an open one can go back to draft.`);\n if (!pr.node_id) throw new GitHubError(422, `Pull request #${n} has no node id: convert it to draft on GitHub.`);\n const r = await this.request<{ data?: unknown; errors?: { message?: string }[] }>('POST', '/graphql', {\n query: 'mutation($id: ID!) { convertPullRequestToDraft(input: { pullRequestId: $id }) { pullRequest { number isDraft } } }',\n variables: { id: pr.node_id },\n });\n if (r?.errors?.length) {\n const detail = r.errors.map((e) => e.message).filter(Boolean).join(' ');\n throw new GitHubError(422, `GitHub refused to turn #${n} back into a draft${detail ? `: ${detail}` : '.'} Use \"Convert to draft\" on GitHub instead.`, detail);\n }\n }\n\n async createPullRequest(input: { title: string; head: string; base: string; body: string; draft: boolean }): Promise<PullRequest> {\n this.assertWritableBranch(input.head, input.base);\n const r = await this.request<{ number: number; html_url: string; title: string; draft?: boolean; head: { ref: string } }>(\n 'POST',\n `${this.repoPath}/pulls`,\n input,\n );\n return { number: r.number, url: r.html_url, title: r.title, draft: !!r.draft, headRef: r.head.ref };\n }\n\n async findOpenPullRequest(branch: string): Promise<PullRequest | undefined> {\n const r = await this.request<{ number: number; html_url: string; title: string; draft?: boolean; head: { ref: string } }[]>(\n 'GET',\n `${this.repoPath}/pulls?state=open&head=${encodeURIComponent(`${this.owner}:${branch}`)}`,\n );\n const pr = r[0];\n return pr ? { number: pr.number, url: pr.html_url, title: pr.title, draft: !!pr.draft, headRef: pr.head.ref } : undefined;\n }\n\n /** Best effort: labels need the repo to allow it; failure is not fatal. */\n async addLabels(issueNumber: number, labels: string[]): Promise<boolean> {\n try {\n await this.request('POST', `${this.repoPath}/issues/${issueNumber}/labels`, { labels });\n return true;\n } catch {\n return false;\n }\n }\n\n async addComment(issueNumber: number, body: string): Promise<void> {\n await this.request('POST', `${this.repoPath}/issues/${issueNumber}/comments`, { body });\n }\n\n /** Comments on an issue or pull request, oldest first (first 100: the sticky preview comment is posted early). */\n async listIssueComments(issueNumber: number): Promise<{ id: number; body: string; author: string; updatedAt: string }[]> {\n const r = await this.request<{ id: number; body?: string | null; user?: { login: string } | null; updated_at: string }[]>('GET', `${this.repoPath}/issues/${issueNumber}/comments?per_page=100`);\n return r.map((c) => ({ id: c.id, body: c.body ?? '', author: c.user?.login ?? 'unknown', updatedAt: c.updated_at }));\n }\n\n // --- Issues (component change requests) ---------------------------------------------------\n\n async createIssue(input: { title: string; body: string; labels?: string[]; assignees?: string[] }): Promise<IssueSummary> {\n const r = await this.request<RawIssue>('POST', `${this.repoPath}/issues`, {\n title: input.title,\n body: input.body,\n ...(input.labels?.length ? { labels: input.labels } : {}),\n ...(input.assignees?.length ? { assignees: input.assignees } : {}),\n });\n return toIssue(r);\n }\n\n /** Issues (not pull requests) with a label, newest first. */\n async listIssues(opts: { label?: string; state?: 'open' | 'closed' | 'all'; perPage?: number } = {}): Promise<IssueSummary[]> {\n const q = new URLSearchParams({ state: opts.state ?? 'all', per_page: String(opts.perPage ?? 50), sort: 'created', direction: 'desc' });\n if (opts.label) q.set('labels', opts.label);\n const r = await this.request<RawIssue[]>('GET', `${this.repoPath}/issues?${q}`);\n return r.filter((i) => !i.pull_request).map(toIssue);\n }\n\n async getIssue(n: number): Promise<IssueSummary> {\n return toIssue(await this.request<RawIssue>('GET', `${this.repoPath}/issues/${n}`));\n }\n\n /** Edits an issue: its body, or closes it with a reason (\"not_planned\" for a declined request). */\n async updateIssue(n: number, patch: { body?: string; state?: 'open' | 'closed'; state_reason?: 'completed' | 'not_planned' | 'reopened' }): Promise<IssueSummary> {\n this.assertToken('Editing an issue');\n return toIssue(await this.request<RawIssue>('PATCH', `${this.repoPath}/issues/${n}`, patch));\n }\n\n /** Adds people to an issue's assignees (GitHub ignores logins that cannot be assigned: the result says who is). */\n async addAssignees(n: number, logins: string[]): Promise<string[]> {\n this.assertToken('Assigning an issue');\n const r = await this.request<{ assignees?: { login: string }[] | null }>('POST', `${this.repoPath}/issues/${n}/assignees`, { assignees: logins });\n return (r.assignees ?? []).map((a) => a.login);\n }\n\n /** People with at least `permission` on the repository (reading the list needs push access). First 100. */\n async listCollaborators(permission: 'pull' | 'triage' | 'push' | 'maintain' | 'admin' = 'push'): Promise<{ login: string; avatarUrl: string }[]> {\n const r = await this.request<{ login: string; avatar_url?: string }[]>('GET', `${this.repoPath}/collaborators?permission=${permission}&per_page=100`);\n return r.map((c) => ({ login: c.login, avatarUrl: c.avatar_url ?? '' }));\n }\n\n /** Whether a token is sent with each request (TeamReader). */\n get hasToken(): boolean {\n return Boolean(this.token);\n }\n\n /** Every page of a list endpoint (per_page 100), up to `maxPages`. */\n private async paginate<T>(path: string, maxPages = 20): Promise<T[]> {\n const out: T[] = [];\n const sep = path.includes('?') ? '&' : '?';\n for (let page = 1; page <= maxPages; page++) {\n const r = await this.request<T[]>('GET', `${path}${sep}per_page=100&page=${page}`);\n out.push(...r);\n if (r.length < 100) break;\n }\n return out;\n }\n\n /** Every member login of an organization team (needs read:org, or Members: Read on a fine-grained token). */\n async listTeamMembers(org: string, slug: string): Promise<string[]> {\n const r = await this.paginate<{ login: string }>(`/orgs/${encodeURIComponent(org)}/teams/${encodeURIComponent(slug)}/members`);\n return r.map((m) => m.login);\n }\n\n /** A user's membership of a team: \"active\", \"pending\", or null when GitHub says they are not a member (404). */\n async getTeamMembership(org: string, slug: string, login: string): Promise<'active' | 'pending' | null> {\n try {\n const r = await this.request<{ state: string }>('GET', `/orgs/${encodeURIComponent(org)}/teams/${encodeURIComponent(slug)}/memberships/${encodeURIComponent(login)}`);\n return r.state === 'active' ? 'active' : 'pending';\n } catch (err) {\n if (err instanceof GitHubError && err.status === 404) return null;\n throw err;\n }\n }\n\n /** \"User\" or \"Organization\" for a login, null when GitHub does not know it. */\n async getAccountType(login: string): Promise<'User' | 'Organization' | null> {\n try {\n const r = await this.request<{ type?: string }>('GET', `/users/${encodeURIComponent(login)}`);\n return r.type === 'Organization' ? 'Organization' : r.type === 'User' ? 'User' : null;\n } catch (err) {\n if (err instanceof GitHubError && err.status === 404) return null;\n throw err;\n }\n }\n\n /** The organization's teams this token can see. */\n async listOrgTeams(org: string): Promise<{ slug: string; name: string }[]> {\n const r = await this.paginate<{ slug: string; name: string }>(`/orgs/${encodeURIComponent(org)}/teams`);\n return r.map((t) => ({ slug: t.slug, name: t.name }));\n }\n\n /** Create or update a binary file (base64 content) on a branch, e.g. a Figma export attached to a request. */\n async putBase64File(input: { path: string; base64: string; branch: string; message: string }): Promise<string> {\n this.assertWritableBranch(input.branch);\n const r = await this.request<{ commit: { sha: string } }>('PUT', `${this.repoPath}/contents/${encodeRef(input.path)}`, {\n message: input.message,\n content: input.base64,\n branch: input.branch,\n });\n return r.commit.sha;\n }\n\n // --- Contents API: single files -----------------------------------------------------------\n\n /** Text of one file at a ref (branch, tag or sha), or undefined when it does not exist. */\n async getFileText(path: string, ref?: string): Promise<string | undefined> {\n try {\n const q = ref ? `?ref=${encodeURIComponent(ref)}` : '';\n const r = await this.request<{ content?: string; encoding?: string; sha: string; type: string }>('GET', `${this.repoPath}/contents/${encodeRef(path)}${q}`);\n if (r.type !== 'file') return undefined;\n if (r.encoding === 'base64' && r.content !== undefined) return base64ToUtf8(r.content);\n return r.content;\n } catch (err) {\n if (err instanceof GitHubError && err.status === 404) return undefined;\n throw err;\n }\n }\n\n /**\n * Text and blob sha of one file at a ref, or undefined when it does not exist. The sha is what an update or a\n * delete must send back (optimistic concurrency: GitHub answers 409 when the file changed since).\n */\n async getFile(path: string, ref?: string): Promise<{ text: string; sha: string } | undefined> {\n try {\n const q = ref ? `?ref=${encodeURIComponent(ref)}` : '';\n const r = await this.request<{ content?: string; encoding?: string; sha: string; type: string }>('GET', `${this.repoPath}/contents/${encodeRef(path)}${q}`);\n if (r.type !== 'file') return undefined;\n const text = r.encoding === 'base64' && r.content !== undefined ? base64ToUtf8(r.content) : (r.content ?? '');\n return { text, sha: r.sha };\n } catch (err) {\n if (err instanceof GitHubError && err.status === 404) return undefined;\n throw err;\n }\n }\n\n /**\n * Base64 content of a binary file at a ref (an image), or undefined when it does not exist or is too large for the\n * contents API to inline (over 1 MB).\n */\n async getFileBase64(path: string, ref?: string): Promise<{ base64: string; size: number } | undefined> {\n try {\n const q = ref ? `?ref=${encodeURIComponent(ref)}` : '';\n const r = await this.request<{ content?: string; encoding?: string; size?: number; type: string }>('GET', `${this.repoPath}/contents/${encodeRef(path)}${q}`);\n if (r.type !== 'file' || r.encoding !== 'base64' || !r.content) return undefined;\n return { base64: r.content.replace(/\\s+/g, ''), size: r.size ?? 0 };\n } catch (err) {\n if (err instanceof GitHubError && err.status === 404) return undefined;\n throw err;\n }\n }\n\n /** Entries of one folder at a ref (contents API), or an empty list when the folder does not exist. */\n async listDirectory(path: string, ref?: string): Promise<{ name: string; path: string; type: string; sha: string; size: number }[]> {\n try {\n const q = ref ? `?ref=${encodeURIComponent(ref)}` : '';\n const r = await this.request<unknown>('GET', `${this.repoPath}/contents/${encodeRef(path)}${q}`);\n if (!Array.isArray(r)) return [];\n return (r as { name: string; path: string; type: string; sha: string; size?: number }[]).map((e) => ({ name: e.name, path: e.path, type: e.type, sha: e.sha, size: e.size ?? 0 }));\n } catch (err) {\n if (err instanceof GitHubError && err.status === 404) return [];\n throw err;\n }\n }\n\n /** Deletes one file on a branch in its own commit (contents API). `sha` is the file's blob sha. */\n async deleteFile(input: { path: string; branch: string; message: string; sha: string }): Promise<string> {\n this.assertToken('Deleting a file');\n this.assertWritableBranch(input.branch);\n const r = await this.request<{ commit: { sha: string } }>('DELETE', `${this.repoPath}/contents/${encodeRef(input.path)}`, {\n message: input.message,\n branch: input.branch,\n sha: input.sha,\n });\n return r.commit.sha;\n }\n\n /** Create or update one file on a branch in its own commit (contents API). Returns the commit sha. */\n async putFile(input: { path: string; content: string; branch: string; message: string; sha?: string | undefined }): Promise<string> {\n this.assertWritableBranch(input.branch);\n const r = await this.request<{ commit: { sha: string } }>('PUT', `${this.repoPath}/contents/${encodeRef(input.path)}`, {\n message: input.message,\n content: utf8ToBase64(input.content),\n branch: input.branch,\n ...(input.sha ? { sha: input.sha } : {}),\n });\n return r.commit.sha;\n }\n\n /**\n * Text of a file at a ref, or undefined. Without a token, public repos are read from the raw host (no\n * hourly API limit); with one, through the contents API (private repos work).\n */\n async readFile(path: string, ref: string): Promise<string | undefined> {\n if (this.token) return this.getFileText(path, ref);\n const url = `${(this.options.rawUrl ?? RAW).replace(/\\/$/, '')}/${this.owner}/${this.name}/${encodeRef(ref)}/${encodeRef(path)}`;\n let res: Awaited<ReturnType<FetchLike>>;\n try {\n res = await this.fetchImpl(url, {});\n } catch (err) {\n throw new GitHubError(0, 'Could not reach GitHub. Check your connection, then try again.', (err as Error).message);\n }\n if (res.status === 404) return undefined;\n if (!res.ok) throw new GitHubError(res.status, friendlyMessage(res.status, ''), `raw ${path}@${ref}`);\n return res.text();\n }\n\n /** The repository's default branch. */\n async getDefaultBranch(): Promise<string> {\n return (await this.getRepo()).defaultBranch;\n }\n\n /** Every file path at a ref (branch, tag or sha), one API call. */\n async listFiles(ref: string): Promise<string[]> {\n const r = await this.request<{ tree: { path: string; type: string }[]; truncated: boolean }>('GET', `${this.repoPath}/git/trees/${encodeRef(ref)}?recursive=1`);\n if (r.truncated) throw new GitHubError(413, 'The repository tree is too large to read in one request.');\n return r.tree.filter((e) => e.type === 'blob').map((e) => e.path);\n }\n\n // --- Pull requests, reviews, checks ---------------------------------------------------------\n\n async listPullRequests(state: 'open' | 'closed' | 'all' = 'open'): Promise<PullRequestSummary[]> {\n const r = await this.request<Record<string, any>[]>('GET', `${this.repoPath}/pulls?state=${state}&per_page=50&sort=updated&direction=desc`);\n return r.map(toSummary);\n }\n\n /** Commit statuses and check runs of a commit, folded into one state. */\n async getChecks(sha: string): Promise<{ state: 'success' | 'failure' | 'pending' | 'none'; checks: { name: string; status: string; conclusion: string | null }[] }> {\n const [combined, runs] = await Promise.all([\n this.request<{ statuses: { context: string; state: string }[] }>('GET', `${this.repoPath}/commits/${encodeRef(sha)}/status`).catch(() => ({ statuses: [] })),\n this.listCheckRuns(sha).catch(() => [] as CheckRun[]),\n ]);\n const checks = [\n ...runs.map((c) => ({ name: c.name, status: c.status, conclusion: c.conclusion })),\n ...combined.statuses.map((s) => ({ name: s.context, status: s.state === 'pending' ? 'in_progress' : 'completed', conclusion: s.state === 'pending' ? null : s.state })),\n ];\n const failing = checks.some((c) => c.conclusion && !['success', 'neutral', 'skipped'].includes(c.conclusion));\n const pending = checks.some((c) => c.status !== 'completed');\n return { state: !checks.length ? 'none' : failing ? 'failure' : pending ? 'pending' : 'success', checks };\n }\n\n /** Commit statuses of a commit, newest first (Vercel reports each project as \"Vercel – <project>\"). */\n async listCommitStatuses(sha: string): Promise<{ context: string; state: string; target_url: string | null; description: string | null }[]> {\n const r = await this.request<{ context: string; state: string; target_url?: string | null; description?: string | null }[]>('GET', `${this.repoPath}/commits/${encodeRef(sha)}/statuses?per_page=100`);\n return r.map((s) => ({ context: s.context, state: s.state, target_url: s.target_url ?? null, description: s.description ?? null }));\n }\n\n /**\n * GitHub deployments of a commit with their latest status (environment \"Preview – <project>\", environment_url the\n * preview). Latest per environment only, so it costs one read plus one per environment.\n */\n async listDeployments(sha: string): Promise<{ id: number; environment: string; state: string | null; environmentUrl: string | null }[]> {\n const list = await this.request<{ id: number; environment: string; created_at?: string }[]>('GET', `${this.repoPath}/deployments?sha=${encodeURIComponent(sha)}&per_page=30`);\n const latest = new Map<string, { id: number; environment: string }>();\n for (const d of list) if (!latest.has(d.environment)) latest.set(d.environment, d);\n return Promise.all(\n [...latest.values()].map(async (d) => {\n const st = await this.request<{ state: string; environment_url?: string | null; target_url?: string | null }[]>('GET', `${this.repoPath}/deployments/${d.id}/statuses?per_page=1`).catch(() => []);\n const s = st[0];\n return { id: d.id, environment: d.environment, state: s?.state ?? null, environmentUrl: s?.environment_url || null };\n }),\n );\n }\n\n async getPullRequest(n: number): Promise<PullRequest & PullRequestSummary & { body: string; mergeable: boolean | null; requestedReviewers: string[] }> {\n const r = await this.request<Record<string, any>>('GET', `${this.repoPath}/pulls/${n}`);\n return { ...toSummary(r), body: r.body ?? '', mergeable: r.mergeable ?? null, requestedReviewers: ((r.requested_reviewers ?? []) as { login: string }[]).map((x) => x.login) };\n }\n\n async listPullRequestFiles(n: number): Promise<PullRequestFile[]> {\n const r = await this.request<{ filename: string; status: string; additions: number; deletions: number }[]>('GET', `${this.repoPath}/pulls/${n}/files?per_page=100`);\n return r.map((f) => ({ filename: f.filename, status: f.status, additions: f.additions, deletions: f.deletions }));\n }\n\n async updatePullRequest(n: number, patch: { title?: string; body?: string; state?: 'open' | 'closed' }): Promise<void> {\n await this.request('PATCH', `${this.repoPath}/pulls/${n}`, patch);\n }\n\n async listReviews(n: number): Promise<Review[]> {\n const r = await this.request<{ id: number; user?: { login: string }; state: string; body: string | null; submitted_at?: string }[]>('GET', `${this.repoPath}/pulls/${n}/reviews`);\n return r.map((x) => ({ id: x.id, user: x.user?.login, state: x.state, body: x.body ?? '', ...(x.submitted_at ? { submittedAt: x.submitted_at } : {}) }));\n }\n\n /** Submit a review. `COMMENT` works for any collaborator; approving your own PR is refused by GitHub. */\n async createReview(n: number, input: { event: 'COMMENT' | 'APPROVE' | 'REQUEST_CHANGES'; body: string }): Promise<Review> {\n this.assertToken('Reviewing a pull request');\n const r = await this.request<{ id: number; user?: { login: string }; state: string; body: string | null }>('POST', `${this.repoPath}/pulls/${n}/reviews`, input);\n return { id: r.id, user: r.user?.login, state: r.state, body: r.body ?? '' };\n }\n\n async listCheckRuns(ref: string): Promise<CheckRun[]> {\n const r = await this.request<{ check_runs: { id: number; name: string; status: string; conclusion: string | null; html_url?: string; app?: { slug?: string } | null }[] }>(\n 'GET',\n `${this.repoPath}/commits/${encodeRef(ref)}/check-runs`,\n );\n return r.check_runs.map((c) => ({ id: c.id, name: c.name, status: c.status, conclusion: c.conclusion, url: c.html_url, ...(c.app?.slug ? { app: c.app.slug } : {}) }));\n }\n\n /** Rulesets that apply to the repository, without their rules (GET /rulesets; read access is enough). */\n async listRulesets(): Promise<Ruleset[]> {\n const r = await this.request<(Ruleset & { _links?: { html?: { href?: string } } })[]>('GET', `${this.repoPath}/rulesets?includes_parents=true&per_page=100`);\n return r.map(withRulesetUrl);\n }\n\n /** One ruleset with its rules. */\n async getRuleset(id: number): Promise<Ruleset> {\n return withRulesetUrl(await this.request<Ruleset>('GET', `${this.repoPath}/rulesets/${id}`));\n }\n\n /** Creates a repository ruleset. Needs admin on the repo (fine-grained token: Administration read and write). */\n async createRuleset(payload: RulesetPayload): Promise<Ruleset> {\n this.assertToken('Protecting the library');\n return withRulesetUrl(await this.request<Ruleset>('POST', `${this.repoPath}/rulesets`, payload));\n }\n\n /** Replaces a repository ruleset (same permissions as createRuleset). */\n async updateRuleset(id: number, payload: RulesetPayload): Promise<Ruleset> {\n this.assertToken('Protecting the library');\n return withRulesetUrl(await this.request<Ruleset>('PUT', `${this.repoPath}/rulesets/${id}`, payload));\n }\n\n /**\n * Classic branch protection of `branch`: the settings, null when the branch has none (404), undefined when this\n * token cannot read them (403: the endpoint needs admin). On a 403 the public branch summary still tells\n * whether the branch is protected at all: `protected: false` means there is nothing to read, so null.\n */\n async getBranchProtection(branch: string): Promise<ClassicProtection | null | undefined> {\n try {\n return await this.request<ClassicProtection>('GET', `${this.repoPath}/branches/${encodeRef(branch)}/protection`);\n } catch (err) {\n if (!(err instanceof GitHubError)) throw err;\n if (err.status === 404) return null;\n if (err.status === 403 || err.status === 401) {\n const b = await this.request<{ protected?: boolean }>('GET', `${this.repoPath}/branches/${encodeRef(branch)}`).catch(() => undefined);\n return b?.protected === false ? null : undefined;\n }\n throw err;\n }\n }\n\n /** Create a check run (needs a GitHub App token; personal tokens are refused by GitHub). */\n async createCheckRun(input: {\n name: string;\n headSha: string;\n status?: 'queued' | 'in_progress' | 'completed';\n conclusion?: 'success' | 'failure' | 'neutral' | 'cancelled' | 'skipped' | 'timed_out' | 'action_required';\n output?: { title: string; summary: string; text?: string };\n }): Promise<CheckRun> {\n const r = await this.request<{ id: number; name: string; status: string; conclusion: string | null; html_url?: string }>('POST', `${this.repoPath}/check-runs`, {\n name: input.name,\n head_sha: input.headSha,\n ...(input.status ? { status: input.status } : {}),\n ...(input.conclusion ? { conclusion: input.conclusion } : {}),\n ...(input.output ? { output: input.output } : {}),\n });\n return { id: r.id, name: r.name, status: r.status, conclusion: r.conclusion, url: r.html_url };\n }\n\n async removeLabel(issueNumber: number, label: string): Promise<void> {\n await this.request('DELETE', `${this.repoPath}/issues/${issueNumber}/labels/${encodeURIComponent(label)}`);\n }\n\n // --- branch actions shared by Studio, the MCP server and the CLI (branch-actions.ts) ---\n\n /** The account the token belongs to (GET /user). Needs a token. */\n async getViewer(): Promise<{ login: string }> {\n this.assertToken('Reading who you are on GitHub');\n const r = await this.request<{ login: string }>('GET', '/user');\n return { login: r.login };\n }\n\n /** The repository's merge settings and the viewer's permissions (unknown settings count as allowed). */\n async getMergeSettings(): Promise<{ allow_squash_merge?: boolean; allow_merge_commit?: boolean; allow_rebase_merge?: boolean; permissions?: { admin?: boolean; maintain?: boolean; push?: boolean } }> {\n return this.request('GET', this.repoPath);\n }\n\n /**\n * Merges a pull request, only at `sha` (GitHub refuses when the branch moved meanwhile). The repository's branch\n * rules still apply: GitHub refuses a merge they block, whatever Bridge says.\n */\n async mergePullRequest(n: number, input: { method: 'squash' | 'merge' | 'rebase'; sha: string; commitMessage?: string | undefined }): Promise<{ sha: string; merged: boolean }> {\n this.assertToken('Merging a branch');\n const r = await this.request<{ sha: string; merged: boolean }>('PUT', `${this.repoPath}/pulls/${n}/merge`, {\n merge_method: input.method,\n sha: input.sha,\n ...(input.commitMessage !== undefined && input.method !== 'rebase' ? { commit_message: input.commitMessage } : {}),\n });\n return { sha: r?.sha ?? '', merged: r?.merged ?? true };\n }\n\n /** GitHub's \"Update branch\": merges the base into the pull request, only when its head is still `expectedHeadSha`. */\n async updatePullRequestBranch(n: number, expectedHeadSha: string): Promise<void> {\n this.assertToken('Updating a branch from main');\n await this.request('PUT', `${this.repoPath}/pulls/${n}/update-branch`, { expected_head_sha: expectedHeadSha });\n }\n\n /** Posts a comment on an issue or pull request and returns its id and link. */\n async createIssueComment(n: number, body: string): Promise<{ id: number; url: string }> {\n this.assertToken('Commenting');\n const r = await this.request<{ id: number; html_url: string }>('POST', `${this.repoPath}/issues/${n}/comments`, { body });\n return { id: r.id, url: r.html_url };\n }\n\n /** Replaces the text of a comment. */\n async updateIssueComment(id: number, body: string): Promise<void> {\n this.assertToken('Editing a comment');\n await this.request('PATCH', `${this.repoPath}/issues/comments/${id}`, { body });\n }\n\n /** Submits a review on a given commit (the head the reviewer saw); the body may be empty for an approval. */\n async submitReview(n: number, input: { event: 'COMMENT' | 'APPROVE' | 'REQUEST_CHANGES'; body?: string | undefined; commitId?: string | undefined }): Promise<Review> {\n this.assertToken('Reviewing a branch');\n const r = await this.request<{ id: number; user?: { login: string }; state: string; body: string | null }>('POST', `${this.repoPath}/pulls/${n}/reviews`, {\n event: input.event,\n ...(input.body ? { body: input.body } : {}),\n ...(input.commitId ? { commit_id: input.commitId } : {}),\n });\n return { id: r.id, user: r.user?.login, state: r.state, body: r.body ?? '' };\n }\n\n /** Line comments of a pull request (review threads), oldest first. */\n async listReviewComments(n: number): Promise<{ id: number; body: string; author: string; path: string; line: number | null; inReplyTo: number | null; url: string; createdAt: string }[]> {\n const r = await this.request<{ id: number; body?: string | null; user?: { login: string } | null; path: string; line?: number | null; in_reply_to_id?: number; html_url: string; created_at: string }[]>(\n 'GET',\n `${this.repoPath}/pulls/${n}/comments?per_page=100`,\n );\n return r.map((c) => ({ id: c.id, body: c.body ?? '', author: c.user?.login ?? 'unknown', path: c.path, line: c.line ?? null, inReplyTo: c.in_reply_to_id ?? null, url: c.html_url, createdAt: c.created_at }));\n }\n\n /** Asks these people to review a pull request. */\n async requestReviewers(n: number, logins: string[]): Promise<void> {\n this.assertToken('Asking for a review');\n await this.request('POST', `${this.repoPath}/pulls/${n}/requested_reviewers`, { reviewers: logins });\n }\n\n /** Takes these people off the requested reviewers. */\n async removeRequestedReviewers(n: number, logins: string[]): Promise<void> {\n this.assertToken('Changing the requested reviewers');\n await this.request('DELETE', `${this.repoPath}/pulls/${n}/requested_reviewers`, { reviewers: logins });\n }\n\n /** Replies in the thread of a line comment. */\n async replyToReviewComment(n: number, commentId: number, body: string): Promise<{ id: number; url: string }> {\n this.assertToken('Replying to a comment');\n const r = await this.request<{ id: number; html_url: string }>('POST', `${this.repoPath}/pulls/${n}/comments/${commentId}/replies`, { body });\n return { id: r.id, url: r.html_url };\n }\n\n /**\n * What `head` adds on top of `base`, with what library sync needs: the shared start (merge base), the base\n * commit and its tree, how far behind, and the files with their previous names.\n */\n async compareDetailed(base: string, head: string): Promise<{\n behindBy: number;\n aheadBy: number;\n mergeBase: string | null;\n baseSha: string | null;\n baseTree: string | null;\n files: { filename: string; status: string; previous_filename?: string | undefined }[];\n }> {\n const r = await this.request<{\n ahead_by: number;\n behind_by: number;\n merge_base_commit?: { sha?: string };\n base_commit?: { sha?: string; commit?: { tree?: { sha?: string } } };\n files?: { filename: string; status: string; previous_filename?: string }[];\n }>('GET', `${this.repoPath}/compare/${encodeRef(base)}...${encodeRef(head)}`);\n return {\n behindBy: r.behind_by,\n aheadBy: r.ahead_by,\n mergeBase: r.merge_base_commit?.sha ?? null,\n baseSha: r.base_commit?.sha ?? null,\n baseTree: r.base_commit?.commit?.tree?.sha ?? null,\n files: (r.files ?? []).map((f) => ({ filename: f.filename, status: f.status, ...(f.previous_filename ? { previous_filename: f.previous_filename } : {}) })),\n };\n }\n\n /** A tree on top of `baseTree` from entries with their own file mode (blob sha, inline content, or sha null to delete). */\n async createTreeEntries(baseTree: string, entries: ({ path: string; mode: string; sha: string | null } | { path: string; mode: string; content: string })[]): Promise<string> {\n const r = await this.request<{ sha: string }>('POST', `${this.repoPath}/git/trees`, { base_tree: baseTree, tree: entries.map((e) => ({ ...e, type: 'blob' })) }, true);\n return r.sha;\n }\n}\n\nfunction toCommitSummary(c: Record<string, any>): CommitSummary {\n return {\n sha: c.sha,\n parents: (c.parents ?? []).map((p: { sha: string }) => p.sha),\n date: c.commit?.committer?.date ?? c.commit?.author?.date ?? '',\n author: c.author?.login ?? c.commit?.author?.name ?? 'unknown',\n message: c.commit?.message ?? '',\n };\n}\n\nfunction toSummary(r: Record<string, any>): PullRequestSummary & PullRequest {\n return {\n number: r.number,\n title: r.title,\n state: r.merged_at || r.merged ? 'merged' : r.state,\n draft: Boolean(r.draft),\n author: r.user?.login ?? 'unknown',\n headRef: r.head?.ref,\n headSha: r.head?.sha,\n baseRef: r.base?.ref,\n labels: (r.labels ?? []).map((l: { name: string }) => l.name),\n url: r.html_url,\n updatedAt: r.updated_at,\n ...(typeof r.body === 'string' ? { body: r.body } : {}),\n };\n}\n\nexport function friendlyMessage(status: number, detail: string, info: GitHubErrorInfo = {}): string {\n if (info.auth === 'rejected') return TOKEN_REJECTED_MESSAGE;\n if (info.auth === 'missing-permission') return missingPermissionMessage(info.permission);\n switch (status) {\n case 401:\n return 'GitHub rejected the token. It may be expired or mistyped: create a new one and save it in Settings.';\n case 403:\n if (/rate limit/i.test(detail)) return 'GitHub is limiting requests right now. Wait a minute, then try again.';\n if (/archived/i.test(detail)) return 'This repository is archived and read-only.';\n return 'The token does not have permission for this. It needs \"Contents: read and write\" and \"Pull requests: read and write\" on this repository.';\n case 404:\n return 'Repository, branch or file not found, or the token cannot see this repository.';\n case 409:\n return 'GitHub reported a conflict (the branch moved while saving). Scan again, then retry.';\n case 429:\n return 'GitHub is limiting requests right now. Wait a minute, then try again.';\n case 422:\n return `GitHub refused the request${detail ? `: ${detail}` : '.'}`;\n default:\n return `GitHub error ${status}${detail ? `: ${detail}` : ''}`;\n }\n}\n\nexport interface RepoFiles {\n commitSha: string;\n treeSha: string;\n /** Token files relative to the tokens root. */\n files: Record<string, string>;\n /** Contents of the contrast checks file (tokens.contrastChecks in the config), when present. */\n contrastChecks: string | undefined;\n /** bridge.config.json at the repository root, parsed; undefined when the repo has none. */\n config: BridgeConfig | undefined;\n /** bridge.config.json as written, for minimal-diff edits (a new brand); undefined when the repo has none. */\n configText?: string | undefined;\n /** Tokens root actually used (from the config when present, else the fallback). */\n tokensPath: string;\n /** Problems reading the config (it is then ignored and the fallback is used). */\n warnings: string[];\n}\n\n/**\n * Read every *.tokens.json under the tokens root, plus the contrast checks file, at a commit.\n * The tokens root and the checks file come from bridge.config.json at the repository root when it\n * exists; otherwise from `fallbackTokensPath` and the default layout.\n */\nexport async function loadRepoFiles(client: GitHubClient, commitSha: string, fallbackTokensPath: string): Promise<RepoFiles> {\n const treeSha = await client.getCommitTree(commitSha);\n const { entries, truncated } = await client.getTree(treeSha, true);\n if (truncated) throw new Error('The repository tree is too large to read in one request.');\n const warnings: string[] = [];\n let config: BridgeConfig | undefined;\n let configText: string | undefined;\n const configEntry = entries.find((e) => e.type === 'blob' && e.path === CONFIG_FILE);\n if (configEntry) {\n try {\n configText = await client.getBlobText(configEntry.sha);\n config = loadConfig(configText);\n } catch (err) {\n warnings.push(err instanceof ConfigError ? `${err.message}. Using ${fallbackTokensPath} instead.` : `${CONFIG_FILE} could not be read.`);\n }\n }\n const tokensPath = (config?.tokens.root ?? fallbackTokensPath).replace(/^\\/+|\\/+$/g, '');\n const checksFile = config?.tokens.contrastChecks ?? DEFAULT_TOKEN_PATHS.contrastChecks;\n const prefix = tokensPath + '/';\n const wanted = entries.filter(\n (e) => e.type === 'blob' && e.path.startsWith(prefix) && (e.path.endsWith('.tokens.json') || e.path === prefix + checksFile),\n );\n if (!wanted.some((e) => e.path.endsWith('.tokens.json'))) throw new Error(`No *.tokens.json files found under ${tokensPath} at ${commitSha.slice(0, 7)}.`);\n const files: Record<string, string> = {};\n let contrastChecks: string | undefined;\n // Small concurrency limit: friendly to rate limits, still quick for a handful of files.\n const queue = [...wanted];\n const worker = async () => {\n for (let e = queue.shift(); e; e = queue.shift()) {\n const text = await client.getBlobText(e.sha);\n const rel = e.path.slice(prefix.length);\n if (rel === checksFile) contrastChecks = text;\n else files[rel] = text;\n }\n };\n await Promise.all([worker(), worker(), worker(), worker()]);\n return { commitSha, treeSha, files, contrastChecks, config, ...(config ? { configText } : {}), tokensPath, warnings };\n}\n\n/** Lifts the ruleset's GitHub page (`_links.html.href`) to `html_url`. */\nfunction withRulesetUrl(r: Ruleset): Ruleset {\n const href = r._links?.html?.href;\n return href && !r.html_url ? { ...r, html_url: href } : r;\n}\n\nexport interface IssueSummary {\n number: number;\n title: string;\n body: string;\n url: string;\n state: 'open' | 'closed';\n stateReason: string | null;\n labels: string[];\n author: string;\n createdAt: string;\n updatedAt: string;\n}\n\ninterface RawIssue {\n number: number;\n title: string;\n body: string | null;\n html_url: string;\n state: 'open' | 'closed';\n state_reason?: string | null;\n labels: (string | { name?: string })[];\n user?: { login?: string } | null;\n created_at: string;\n updated_at: string;\n pull_request?: unknown;\n}\n\nfunction toIssue(r: RawIssue): IssueSummary {\n return {\n number: r.number,\n title: r.title,\n body: r.body ?? '',\n url: r.html_url,\n state: r.state,\n stateReason: r.state_reason ?? null,\n labels: r.labels.map((l) => (typeof l === 'string' ? l : (l.name ?? ''))).filter(Boolean),\n author: r.user?.login ?? '',\n createdAt: r.created_at,\n updatedAt: r.updated_at,\n };\n}\n","// Library protection over the GitHub client: read the state of the default branch, read the checks to require,\n// and create (or complete) the Bridge ruleset. Studio, the CLI and the MCP server call these.\n\nimport { GitHubError, type GitHubClient } from './github-client';\nimport { type ProtectionOptions, protectionRuleset, type ProtectionState, protectionState, requiredCheckNames, type Ruleset } from './protection';\n\n/**\n * The protection of `defaultBranch`. Rulesets are listed (read access is enough), then read one by one for their\n * rules; classic branch protection is read too. Whatever cannot be read counts as unknown, never as unprotected.\n */\nexport async function loadProtection(client: GitHubClient, defaultBranch: string): Promise<ProtectionState> {\n const rulesets = await client\n .listRulesets()\n // Disabled rulesets enforce nothing: kept as listed (the Bridge one is still found by name, to update it).\n .then((list) => Promise.all(list.map((r) => (r.enforcement === 'disabled' || r.id === undefined ? r : client.getRuleset(r.id)))))\n // Any failure (no access, a repo GitHub hides behind a 404, rate limit) leaves the state unknown.\n .catch((): Ruleset[] | null => null);\n const classic = await client.getBranchProtection(defaultBranch).catch(() => undefined);\n return protectionState(rulesets, classic, defaultBranch);\n}\n\n/** The checks to require: the default branch's latest check runs, kept to those the last merged pull request ran. */\nexport async function loadRequiredChecks(client: GitHubClient, defaultBranch: string): Promise<string[]> {\n const onDefault = await client.listCheckRuns(defaultBranch).catch(() => []);\n const merged = await client\n .listPullRequests('closed')\n .then((prs) => prs.find((p) => p.state === 'merged' && p.baseRef === defaultBranch))\n .catch(() => undefined);\n const onPull = merged?.headSha ? await client.listCheckRuns(merged.headSha).catch(() => []) : [];\n return requiredCheckNames(onDefault, onPull);\n}\n\n/**\n * Turns protection on: creates the Bridge ruleset, or replaces it when one with its name exists (Complete\n * protection). Needs a token with admin on the repository; GitHub's refusal is thrown as a GitHubError.\n */\nexport async function protectLibrary(\n client: GitHubClient,\n defaultBranch: string,\n opts: Partial<ProtectionOptions> & { state?: ProtectionState } = {},\n): Promise<Ruleset> {\n const checks = opts.checks ?? (await loadRequiredChecks(client, defaultBranch));\n const payload = protectionRuleset({ repo: { defaultBranch } }, { checks, approvals: opts.approvals ?? 1, adminBypass: opts.adminBypass ?? true });\n const id = opts.state?.bridgeRulesetId;\n return id !== undefined ? client.updateRuleset(id, payload) : client.createRuleset(payload);\n}\n\n/** GitHub's message when the plan does not allow rulesets on a private repository. */\nconst PLAN_REFUSED = /upgrade to github (pro|team)|make this repository public|not available for private repositories/i;\n\n/** True when GitHub refused the ruleset because of the repository's plan, not the token. */\nexport const isPlanRefusal = (err: unknown) => err instanceof GitHubError && (err.status === 403 || err.status === 422) && PLAN_REFUSED.test(`${err.detail ?? ''} ${err.message}`);\n\n/** Where rulesets are managed on GitHub. */\nexport const rulesSettingsUrl = (owner: string, repo: string) => `https://github.com/${owner}/${repo}/settings/rules`;\n\n/**\n * The one sentence for a refused \"Protect the library\": the plan, the token's permission, or admin access.\n * Null for any other failure (the caller shows GitHub's message).\n */\nexport function protectRefusal(err: unknown): string | null {\n if (!(err instanceof GitHubError)) return null;\n if (isPlanRefusal(err)) return \"GitHub's plan for this private repository does not include protection rules. Upgrade the plan or make the repository public, then try again.\";\n // \"Must have admin rights\": the person is not an admin, whatever the token allows.\n if (/admin rights/i.test(`${err.detail ?? ''}`)) return 'Only a repository admin can protect the library. Ask an admin, or set it up in GitHub settings.';\n if (err.auth === 'missing-permission') return 'This token cannot change the protection. Add Administration: Read and write to the token on GitHub, then try again.';\n if (err.status === 403 || err.status === 404) return 'Only a repository admin can protect the library. Ask an admin, or set it up in GitHub settings.';\n return null;\n}\n","// Usage index: which CSS custom properties each component module reads, and which other components it renders.\n// Pure text scanning (no CSS or TypeScript parser), so it runs in Node, the browser and the Figma sandbox alike.\n// Used by visual impact analysis to go from changed tokens and files to the components (and stories) to look at.\n\nexport interface UsageFile {\n /** Repo-relative path with forward slashes. */\n path: string;\n text: string;\n}\n\nexport interface UsageModule {\n /** Component folder name, e.g. \"Button\". */\n id: string;\n dir: string;\n files: string[];\n /** CSS custom properties read with var(), sorted. Includes locally defined ones. */\n vars: string[];\n /** Other components this one imports from its source (stories and tests excluded), sorted. */\n imports: string[];\n /** Components that only its stories import (e.g. a Button inside an Alert story), sorted. */\n storyImports: string[];\n}\n\nexport interface UsageIndex {\n componentsDir: string;\n modules: Record<string, UsageModule>;\n /** CSS custom property -> modules that read it. */\n byVar: Record<string, string[]>;\n /** CSS custom properties read by files outside the component folders (global styles, theme). */\n globalVars: Record<string, string[]>;\n}\n\nconst VAR_RE = /var\\(\\s*(--[A-Za-z0-9_-]+)/g;\nconst IMPORT_RE = /(?:import|export)\\s[^'\"]*?from\\s*['\"]([^'\"]+)['\"]|import\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g;\n\n/** CSS custom properties read with `var(--x)` in a stylesheet or a style string, in order of first use. */\nexport function cssVarsIn(text: string): string[] {\n const out = new Set<string>();\n for (const m of text.matchAll(VAR_RE)) out.add(m[1]!);\n return [...out];\n}\n\n/** Module specifiers a TS/JS file imports or re-exports. */\nexport function importsIn(text: string): string[] {\n const out = new Set<string>();\n for (const m of text.matchAll(IMPORT_RE)) out.add((m[1] ?? m[2])!);\n return [...out];\n}\n\nconst norm = (p: string) => p.replace(/\\\\/g, '/').replace(/\\/+$/, '');\nconst isStory = (p: string) => /\\.stories\\.[cm]?[jt]sx?$/.test(p);\nconst isTest = (p: string) => /\\.(test|spec)\\.[cm]?[jt]sx?$/.test(p);\nconst isCss = (p: string) => /\\.(css|scss|less)$/.test(p);\nconst isScript = (p: string) => /\\.[cm]?[jt]sx?$/.test(p);\n\n/** Resolves a relative specifier from a file to the component folder it lands in, if any. */\nfunction componentOf(from: string, spec: string, componentsDir: string): string | null {\n if (!spec.startsWith('.')) return null;\n const parts = from.split('/').slice(0, -1);\n for (const seg of spec.split('/')) {\n if (seg === '.' || seg === '') continue;\n if (seg === '..') parts.pop();\n else parts.push(seg);\n }\n const abs = parts.join('/');\n if (!abs.startsWith(`${componentsDir}/`)) return null;\n return abs.slice(componentsDir.length + 1).split('/')[0] || null;\n}\n\n/** The component folder a repo path belongs to, or null when it is outside `componentsDir`. */\nexport function componentForPath(path: string, componentsDir: string): string | null {\n const dir = norm(componentsDir);\n const p = norm(path);\n if (!p.startsWith(`${dir}/`)) return null;\n const rest = p.slice(dir.length + 1).split('/');\n return rest.length >= 2 ? rest[0]! : null;\n}\n\n/**\n * Builds the index from the files of a component library. `componentsDir` holds one folder per component\n * (`<dir>/<Name>/...`); every other file is \"global\" (styles, theme, story helpers) and only its CSS\n * variables are recorded.\n */\nexport function buildUsageIndex(files: UsageFile[], componentsDir: string): UsageIndex {\n const dir = norm(componentsDir);\n const modules: Record<string, UsageModule> = {};\n const vars = new Map<string, Set<string>>();\n const imports = new Map<string, Set<string>>();\n const storyImports = new Map<string, Set<string>>();\n const globalVars: Record<string, string[]> = {};\n const get = (m: Map<string, Set<string>>, k: string) => m.get(k) ?? m.set(k, new Set()).get(k)!;\n\n for (const f of files) {\n const path = norm(f.path);\n const id = componentForPath(path, dir);\n if (!id) {\n if (isCss(path)) {\n const v = cssVarsIn(f.text);\n if (v.length) globalVars[path] = v.sort();\n }\n continue;\n }\n const mod = (modules[id] ??= { id, dir: `${dir}/${id}`, files: [], vars: [], imports: [], storyImports: [] });\n mod.files.push(path);\n if (isTest(path)) continue;\n // Inline styles in TSX can read variables too (style={{ color: 'var(--x)' }}).\n for (const v of cssVarsIn(f.text)) get(vars, id).add(v);\n if (!isScript(path)) continue;\n for (const spec of importsIn(f.text)) {\n const dep = componentOf(path, spec, dir);\n if (!dep || dep === id) continue;\n get(isStory(path) ? storyImports : imports, id).add(dep);\n }\n }\n\n const byVar: Record<string, string[]> = {};\n for (const mod of Object.values(modules)) {\n mod.files.sort();\n mod.vars = [...(vars.get(mod.id) ?? [])].sort();\n mod.imports = [...(imports.get(mod.id) ?? [])].sort();\n mod.storyImports = [...(storyImports.get(mod.id) ?? [])].filter((d) => !mod.imports.includes(d)).sort();\n for (const v of mod.vars) (byVar[v] ??= []).push(mod.id);\n }\n for (const k of Object.keys(byVar)) byVar[k]!.sort();\n return { componentsDir: dir, modules, byVar, globalVars };\n}\n\nexport interface ImpactedModule {\n id: string;\n /** Why: \"uses --color-feedback-danger-solid\", \"file changed: ...\", \"renders Button\". */\n reasons: string[];\n /** True when reached only through another component it renders. */\n indirect: boolean;\n}\n\nexport interface ModuleImpact {\n modules: ImpactedModule[];\n /** Global stylesheets that read a changed variable. */\n globalHits: { file: string; vars: string[] }[];\n}\n\n/**\n * Components affected by changed CSS variables and changed files, closed over \"renders\": when Button changes,\n * every component that imports Button changes too.\n */\nexport function impactedModules(index: UsageIndex, input: { vars?: string[]; files?: string[] }): ModuleImpact {\n const reasons = new Map<string, { reasons: string[]; indirect: boolean }>();\n const add = (id: string, reason: string, indirect: boolean) => {\n const r = reasons.get(id);\n if (r) {\n if (!r.reasons.includes(reason)) r.reasons.push(reason);\n r.indirect &&= indirect;\n } else reasons.set(id, { reasons: [reason], indirect });\n };\n const changedVars = new Set(input.vars ?? []);\n for (const v of changedVars) for (const id of index.byVar[v] ?? []) add(id, `uses ${v}`, false);\n for (const f of input.files ?? []) {\n const id = componentForPath(f, index.componentsDir);\n if (id && index.modules[id]) add(id, `file changed: ${norm(f)}`, false);\n }\n // Reverse \"renders\" edges, breadth first so the closest reason is listed first.\n const renderedBy = new Map<string, string[]>();\n for (const m of Object.values(index.modules)) for (const d of m.imports) (renderedBy.get(d) ?? renderedBy.set(d, []).get(d)!).push(m.id);\n const queue = [...reasons.keys()];\n while (queue.length) {\n const id = queue.shift()!;\n for (const parent of renderedBy.get(id) ?? []) {\n const known = reasons.has(parent);\n add(parent, `renders ${id}`, true);\n if (!known) queue.push(parent);\n }\n }\n const globalHits = Object.entries(index.globalVars)\n .map(([file, vs]) => ({ file, vars: vs.filter((v) => changedVars.has(v)) }))\n .filter((g) => g.vars.length > 0);\n const modules = [...reasons.entries()].map(([id, r]) => ({ id, reasons: r.reasons, indirect: r.indirect })).sort((a, b) => Number(a.indirect) - Number(b.indirect) || a.id.localeCompare(b.id));\n return { modules, globalHits };\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Token usage: which tokens are in use. One definition for every surface (Overview, Checks, the token explorer).\n\nexport interface UsageToken {\n path: string;\n /** CSS custom property the token builds to, e.g. \"--color-bg-default\". */\n cssVar: string;\n /** Token paths this token resolves through, in any mode (its alias chains). May include the token itself. */\n refs: readonly string[];\n}\n\nexport interface TokenReads {\n /** CSS custom property -> components that read it (UsageIndex.byVar). */\n byVar?: Record<string, readonly string[]>;\n /** Global stylesheet -> CSS custom properties it reads (UsageIndex.globalVars): base styles, app shell, theme. */\n globalVars?: Record<string, readonly string[]>;\n}\n\nexport interface TokenUsage {\n /** Paths of every token in use. */\n used: Set<string>;\n /** Paths read directly with var(), by a component or a global stylesheet. */\n direct: Set<string>;\n}\n\n/**\n * A token is in use when a component stylesheet or a global stylesheet (base styles, the app shell) reads its\n * variable, or when a token in use aliases it, at any depth and in any mode. Everything else is unused.\n */\nexport function tokenUsage(tokens: readonly UsageToken[], reads: TokenReads): TokenUsage {\n const readVars = new Set<string>();\n for (const [v, mods] of Object.entries(reads.byVar ?? {})) if (mods.length) readVars.add(v);\n for (const vars of Object.values(reads.globalVars ?? {})) for (const v of vars) readVars.add(v);\n const byPath = new Map(tokens.map((t) => [t.path, t]));\n const direct = new Set(tokens.filter((t) => readVars.has(t.cssVar)).map((t) => t.path));\n const used = new Set<string>();\n const queue = [...direct];\n while (queue.length) {\n const p = queue.pop()!;\n if (used.has(p)) continue;\n used.add(p);\n for (const r of byPath.get(p)?.refs ?? []) if (!used.has(r) && byPath.has(r)) queue.push(r);\n }\n return { used, direct };\n}\n","// History from GitHub over REST, in the browser or Node: commits that touched the tokens root on a ref,\n// the pull request each one belongs to, token files at each side of the change (blobs cached by sha, so\n// files that did not change are read once), changesets the change added, tags and the CHANGELOG.\n\nimport type { BridgeConfig } from './config';\nimport type { GitHubClient, TreeEntry } from './github-client';\nimport { type HistoryBackend, type HistoryCommit, type HistoryReport, buildReport, collectHistory, mergeReleases, packageDirCandidates, parseChangelog, releasesFromTags } from './history';\nimport { selectTokenFiles } from './layered';\n\nexport function gitHubHistoryBackend(client: GitHubClient, config: BridgeConfig, opts: { concurrency?: number } = {}): HistoryBackend & { tree(sha: string): Promise<TreeEntry[]> } {\n const trees = new Map<string, Promise<TreeEntry[]>>();\n const tree = (sha: string) => {\n let t = trees.get(sha);\n if (!t) {\n t = client.getCommitTree(sha).then((ts) => client.getTree(ts, true)).then((r) => r.entries);\n trees.set(sha, t);\n }\n return t;\n };\n const root = config.tokens.root.replace(/\\/$/, '');\n const prefix = root === '.' || !root ? '' : `${root}/`;\n const limit = Math.max(1, opts.concurrency ?? 4);\n const pool = async <T, R>(items: T[], fn: (x: T) => Promise<R>): Promise<R[]> => {\n const out: R[] = new Array(items.length);\n let i = 0;\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {\n for (let k = i++; k < items.length; k = i++) out[k] = await fn(items[k]!);\n }));\n return out;\n };\n\n return {\n tree,\n async listCommits({ ref, paths, limit: max }) {\n const commits: HistoryCommit[] = [];\n for (let page = 1; commits.length < max && page <= 10; page++) {\n const batch = await client.listCommits({ sha: ref, path: paths[0], perPage: Math.min(100, max), page });\n for (const c of batch) {\n const [subject, ...rest] = c.message.split('\\n');\n commits.push({ sha: c.sha, parents: c.parents, date: c.date, author: c.author, subject: subject ?? '', body: rest.join('\\n').trim() });\n }\n if (batch.length < Math.min(100, max)) break;\n }\n const list = commits.slice(0, max);\n // The pull request of each commit. A branch commit of a merged PR is replaced by the PR's merge commit,\n // so the entry diffs the whole PR as it landed.\n const merges = new Map<string, Promise<HistoryCommit | undefined>>();\n const enriched = await pool(list, async (c) => {\n const prs = await client.listPullRequestsForCommit(c.sha).catch(() => []);\n const pr = prs.find((p) => p.mergedAt && p.baseRef === ref) ?? prs.find((p) => p.mergedAt);\n if (!pr) return c;\n const prInfo = { number: pr.number, title: pr.title, url: pr.url, author: pr.author, ...(pr.mergedAt ? { mergedAt: pr.mergedAt } : {}), body: pr.body };\n if (pr.mergeCommitSha && pr.mergeCommitSha !== c.sha) {\n let m = merges.get(pr.mergeCommitSha);\n if (!m) {\n m = client.getCommitInfo(pr.mergeCommitSha).then(\n (info) => {\n const [subject, ...rest] = info.message.split('\\n');\n return { sha: info.sha, parents: info.parents, date: pr.mergedAt ?? info.date, author: info.author, subject: subject ?? '', body: rest.join('\\n').trim() };\n },\n () => undefined,\n );\n merges.set(pr.mergeCommitSha, m);\n }\n const merge = await m;\n if (merge) return { ...merge, pr: prInfo };\n }\n return { ...c, ...(pr.mergedAt ? { date: pr.mergedAt } : {}), pr: prInfo };\n });\n return enriched;\n },\n async tokenFiles(sha) {\n const entries = await tree(sha);\n const blobs = entries.filter((e) => e.type === 'blob' && e.path.startsWith(prefix));\n const picked = new Set(selectTokenFiles(config, blobs.map((e) => e.path)));\n const wanted = blobs.filter((e) => picked.has(prefix ? e.path.slice(prefix.length) : e.path));\n const texts = await pool(wanted, async (e) => [prefix ? e.path.slice(prefix.length) : e.path, await client.getBlobText(e.sha)] as const);\n return new Map(texts);\n },\n async changesetPaths(sha) {\n const dir = config.changesets?.dir.replace(/\\/$/, '');\n if (!dir) return [];\n return (await tree(sha)).filter((e) => e.type === 'blob' && e.path.startsWith(`${dir}/`)).map((e) => e.path);\n },\n async readFile(sha, path) {\n const e = (await tree(sha)).find((x) => x.type === 'blob' && x.path === path);\n return e ? client.getBlobText(e.sha) : null;\n },\n };\n}\n\n/** The whole history report for a GitHub repo: entries, releases (tags and CHANGELOG), timeline. */\nexport async function loadGitHubHistory(client: GitHubClient, config: BridgeConfig, opts: { ref?: string; limit?: number; onProgress?: (done: number, total: number) => void } = {}): Promise<HistoryReport> {\n const ref = opts.ref ?? config.repo?.defaultBranch ?? (await client.getDefaultBranch());\n const limit = opts.limit ?? 30;\n const backend = gitHubHistoryBackend(client, config);\n let listed = 0;\n const counted: HistoryBackend = { ...backend, listCommits: async (o) => {\n const r = await backend.listCommits(o);\n listed = r.length;\n return r;\n } };\n const entries = await collectHistory(config, counted, { ref, limit, ...(opts.onProgress ? { onProgress: opts.onProgress } : {}) });\n const head = await client.getBranchSha(ref).catch(() => undefined);\n let changelog: ReturnType<typeof parseChangelog> = [];\n let currentVersion: string | undefined;\n if (head) {\n const files = await backend.tree(head).catch(() => [] as TreeEntry[]);\n for (const dir of packageDirCandidates(config)) {\n const p = (f: string) => (dir ? `${dir}/${f}` : f);\n const cl = files.find((e) => e.path === p('CHANGELOG.md'));\n const pkg = files.find((e) => e.path === p('package.json'));\n if (!cl && !pkg) continue;\n if (cl) changelog = parseChangelog(await client.getBlobText(cl.sha));\n if (pkg) {\n try {\n const json = JSON.parse(await client.getBlobText(pkg.sha)) as { name?: string; version?: string };\n if (!config.changesets || json.name === config.changesets.package) currentVersion = json.version;\n } catch {\n /* not JSON: no version */\n }\n }\n break;\n }\n }\n const tagList = await client.listTags(30).catch(() => []);\n const tagReleases = releasesFromTags(tagList, config.changesets?.package);\n // Tag dates cost one request each: only the ten newest.\n await Promise.all(\n tagReleases.slice(0, 10).map(async (r) => {\n if (!r.sha) return;\n const info = await client.getCommitInfo(r.sha).catch(() => undefined);\n if (info?.date) r.date = info.date;\n }),\n );\n const releases = mergeReleases(changelog, tagReleases);\n return buildReport({ source: 'github', label: `${client.fullName}@${ref}`, ref, entries, releases, ...(currentVersion ? { currentVersion } : {}), truncated: listed >= limit });\n}\n","// Demo history: fixture entries built backwards from the CURRENT token files, so a revert or a restore\n// planned on them runs against the real base branch. For showing the History UI on a repo with little\n// history. Every entry is flagged `demo`, has no PR link, and the report says `demo: true`: surfaces show\n// it only behind an explicit, labelled toggle and never as real history.\n\nimport type { BridgeConfig } from './config';\nimport { type HistoryEntry, type HistoryReport, buildHistoryEntry, buildReport } from './history';\nimport { LayeredTokenSet } from './layered';\nimport { type TokenEdit, applyTokenEdits } from './token-edits';\n\ninterface DemoStep {\n pr: number;\n title: string;\n why: string;\n author: string;\n date: string;\n /** The values BEFORE this step; the values after it are whatever the next state holds. */\n before: TokenEdit[];\n}\n\nconst STEPS: DemoStep[] = [\n { pr: 101, title: 'Darken muted text for small sizes', why: 'Muted captions at 12px read too light on subtle surfaces in usability tests.', author: 'demo-designer', date: '2026-07-08T09:30:00Z', before: [{ op: 'set', path: 'color.text.muted', file: 'semantic/light.tokens.json', value: '{palette.neutral.500}' }] },\n { pr: 102, title: 'Rounder buttons', why: 'Buttons move to the control radius so they match inputs and selects.', author: 'demo-engineer', date: '2026-07-21T14:10:00Z', before: [{ op: 'set', path: 'button.radius', file: 'components/button.tokens.json', value: '{radius.inset}' }] },\n { pr: 104, title: 'Clarify the alert radius description', why: 'The description now says why alerts use the container radius.', author: 'demo-engineer', date: '2026-08-19T08:00:00Z', before: [{ op: 'set', path: 'alert.radius', file: 'components/feedback.tokens.json', description: 'Alert corner radius.' }] },\n { pr: 106, title: 'Muted text one step lighter', why: 'Muted text competed with body text in dense tables; one step lighter still passes 4.5:1.', author: 'demo-designer', date: '2026-09-30T16:45:00Z', before: [{ op: 'set', path: 'color.text.muted', file: 'semantic/light.tokens.json', value: '{palette.neutral.700}' }] },\n];\n\nexport const DEMO_RELEASES = [\n { version: '1.1.0', date: '2026-07-25T12:00:00Z' },\n { version: '1.2.0', date: '2026-08-25T12:00:00Z' },\n];\n\n/** Demo history over the current files. Steps whose tokens this repo does not have are left out. */\nexport function demoHistory(config: BridgeConfig, current: Map<string, string>): HistoryReport {\n const states: Map<string, string>[] = [current];\n const kept: DemoStep[] = [];\n for (const step of [...STEPS].reverse()) {\n try {\n const prev = applyTokenEdits(new LayeredTokenSet(config, states[0]!), step.before).files;\n states.unshift(prev);\n kept.unshift(step);\n } catch {\n /* this repo has no such token: skip the step */\n }\n }\n const entries: HistoryEntry[] = [];\n kept.forEach((step, i) => {\n const e = buildHistoryEntry({\n config,\n commit: { sha: `demo${String(step.pr).padStart(36, '0')}`, parents: [`demo${String(step.pr - 1).padStart(36, '0')}`], date: step.date, author: step.author, subject: step.title, body: step.why, pr: { number: step.pr, title: step.title, author: step.author, mergedAt: step.date, body: step.why } },\n before: states[i]!,\n after: states[i + 1]!,\n demo: true,\n });\n if (e) entries.push(e);\n });\n return { ...buildReport({ source: 'demo', label: 'Demo history (fixture data)', ref: 'demo', entries, releases: DEMO_RELEASES, truncated: false }), demo: true };\n}\n","// Real branch preview URLs read from GitHub: the deployments and commit statuses of the head commit and the Vercel\n// bot comment on the pull request, resolved by `resolveBranchPreviews` (previews.ts). Shared by the plugin, Studio,\n// the MCP server and the CLI, so none of them shows a guessed URL. See docs/PREVIEWS.md.\n\nimport type { BridgeConfig } from './config';\nimport type { GitHubClient } from './github-client';\nimport { resolveBranchPreviews, type BranchPreview, type PreviewApps } from './previews';\n\nexport interface BranchPreviewOptions {\n /** Branch and head commit when the caller knows them (skips reading the pull request). */\n branch?: string | undefined;\n sha?: string | undefined;\n /** The pull request's comments when the caller already read them (skips one read). */\n comments?: { body?: string | null | undefined }[] | undefined;\n}\n\n/**\n * The preview of each app configured in `previews.apps` for a pull request (by number) or a commit (by sha): the URL\n * Vercel reports (deployments, then commit statuses, then its PR comment), the template only when Vercel cannot have\n * shortened it, and whether the build of that commit is ready. A failed read leaves that source out, never throws for it.\n */\nexport async function branchPreviewUrls(gh: GitHubClient, ref: number | string, config: Pick<BridgeConfig, 'previews'> | { previews?: { apps?: PreviewApps | undefined } | undefined } | undefined, opts: BranchPreviewOptions = {}): Promise<BranchPreview[]> {\n const apps: PreviewApps = config?.previews?.apps ?? {};\n if (!Object.values(apps).some(Boolean)) return [];\n let pr: number | undefined;\n let branch = opts.branch;\n let sha = opts.sha;\n if (typeof ref === 'number') {\n pr = ref;\n if (!branch || !sha) {\n const p = await gh.getPullRequest(ref);\n branch ??= p.headRef;\n sha ??= p.headSha;\n }\n } else {\n sha = ref;\n if (!branch || !opts.comments) {\n const open = (await gh.listPullRequestsForCommit(ref).catch(() => [])).find((p) => p.state === 'open');\n if (open) {\n pr = open.number;\n branch ??= open.headRef;\n }\n }\n }\n const [comments, statuses, deployments] = await Promise.all([\n opts.comments ? Promise.resolve(opts.comments) : pr !== undefined ? gh.listIssueComments(pr).catch(() => []) : Promise.resolve([]),\n sha ? gh.listCommitStatuses(sha).catch(() => []) : Promise.resolve([]),\n sha ? gh.listDeployments(sha).catch(() => []) : Promise.resolve([]),\n ]);\n return resolveBranchPreviews(apps, { branch: branch ?? '', ...(pr !== undefined ? { pr } : {}), ...(sha ? { sha } : {}) }, { comments, statuses, deployments });\n}\n","// The Bridge ramp engine: OKLCH color ramps on one shared lightness ladder (docs/DESIGN-LANGUAGE.md, section 4).\n// Pure and dependency-free, written as plain JavaScript so two very different callers run the same code:\n// packages/tokens/scripts/ramps.mjs regenerates src/primitives/color.tokens.json (plain Node, no build)\n// @bridge-ds/core planNewBrand generates the palette of a new brand (plugin, docs site, CLI, MCP)\n// Types live next to it in ramps.d.ts. Change the algorithm here and both stay in step.\n\n/** Ramp steps, lightest first. */\nexport const STEPS = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];\n\n/** OKLCH lightness of every step: the same step has the same perceived lightness whatever the hue. */\nexport const LIGHTNESS = { 50: 0.975, 100: 0.952, 200: 0.912, 300: 0.85, 400: 0.735, 500: 0.63, 600: 0.53, 700: 0.445, 800: 0.36, 900: 0.27, 950: 0.205 };\n\n/** Chroma bell: share of the peak chroma per step, peaking around 500 and 600. */\nexport const BELL = { 50: 0.12, 100: 0.22, 200: 0.4, 300: 0.62, 400: 0.85, 500: 1, 600: 1, 700: 0.92, 800: 0.8, 900: 0.62, 950: 0.5 };\n\n/** Bridge's ink anchors (Line, Ink secondary, Ink): pinned in the bridge neutral by scripts/ramps.mjs. */\nexport const NEUTRAL_ANCHORS = { 200: '#E3E8EE', 600: '#5B6672', 900: '#15202B' };\n\n/** How far a pinned brand hex may sit from its ladder step before the ramp stops reading as one family. */\nexport const PIN_TOLERANCE = 0.04;\n\n/** Chroma curve of a colored ramp (primary, status, accents). */\nexport const bellChroma = (peak) => (s) => peak * BELL[s];\n\n/** Chroma curve of a neutral ramp (ink, slate): nearly grey at the light end, a visible hue at the dark end. */\nexport const neutralChroma =\n (scale = 1, low = 0.004, base = 0.01, slope = 0.022) =>\n (s) =>\n (s <= 100 ? low : base + slope * (s / 950)) * scale;\n\nexport function oklchToLinear(L, C, h) {\n const hr = (h * Math.PI) / 180;\n const a = C * Math.cos(hr);\n const b = C * Math.sin(hr);\n const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;\n const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;\n const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;\n return [\n 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,\n -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,\n -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,\n ];\n}\n\nconst encode = (x) => {\n const c = Math.min(1, Math.max(0, x));\n return c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055;\n};\nconst decode = (x) => (x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4);\n\n/** sRGB (0..1 components) of an OKLCH color, gamut-mapped by lowering chroma until it fits. */\nexport function oklch(L, C, h) {\n let c = C;\n let lin = oklchToLinear(L, c, h);\n for (let i = 0; i < 60 && !lin.every((x) => x >= -0.0005 && x <= 1.0005); i++) {\n c *= 0.95;\n lin = oklchToLinear(L, c, h);\n }\n return lin.map(encode);\n}\n\n/** OKLCH of an sRGB color (0..1 components). Hue is 0 for greys. */\nexport function toOklch(rgb) {\n const [r, g, b] = rgb.map(decode);\n const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);\n const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);\n const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);\n const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s;\n const A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;\n const B = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;\n const C = Math.sqrt(A * A + B * B);\n const h = C < 1e-6 ? 0 : ((Math.atan2(B, A) * 180) / Math.PI + 360) % 360;\n return { L, C, h };\n}\n\nexport const isHex = (s) => typeof s === 'string' && /^#[0-9a-f]{6}$/i.test(s.trim());\nexport const fromHex = (hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255);\nexport const round3 = (x) => Math.round(x * 1000) / 1000;\nexport const toHex = (rgb) => '#' + rgb.map((x) => Math.round(x * 255).toString(16).padStart(2, '0')).join('');\n\n/** DTCG 2025.10 color value in the house form: { colorSpace, components, hex, alpha? }. */\nexport function dtcgColor(rgb, alpha) {\n const v = { colorSpace: 'srgb', components: rgb.map(round3), hex: toHex(rgb) };\n if (alpha !== undefined) v.alpha = alpha;\n return v;\n}\n\n/**\n * One ramp: step -> sRGB. `chroma(step)` and `offset(step)` shape it; `pins` replace steps with exact brand hexes,\n * so named brand colors survive regeneration.\n */\nexport function generateRamp({ hue, chroma, offset = () => 0, pins = {} }) {\n const out = {};\n for (const s of STEPS) {\n const pin = pins[s];\n out[s] = pin ? fromHex(pin) : oklch(LIGHTNESS[s] + offset(s), chroma(s), hue);\n }\n return out;\n}\n\n/** Ladder step whose lightness is closest to an sRGB color. */\nexport function nearestStep(rgb) {\n const { L } = toOklch(rgb);\n let best = STEPS[0];\n for (const s of STEPS) if (Math.abs(LIGHTNESS[s] - L) < Math.abs(LIGHTNESS[best] - L)) best = s;\n return best;\n}\n\n/**\n * A colored ramp anchored on a brand hex: hue from the hex, peak chroma so the curve passes through it, and the\n * hex pinned at `pinStep` (or at its nearest step). `distance` is how far the hex sits from the ladder lightness\n * of the pinned step; above PIN_TOLERANCE the ramp is no longer monotonic around the pin.\n */\nexport function anchoredRamp(hex, pinStep) {\n const rgb = fromHex(hex);\n const { L, C, h } = toOklch(rgb);\n const step = pinStep ?? nearestStep(rgb);\n const peak = Math.min(0.24, Math.max(0.02, C / BELL[step]));\n return { hue: h, peak, step, distance: Math.abs(L - LIGHTNESS[step]), ramp: generateRamp({ hue: h, chroma: bellChroma(peak), pins: { [step]: hex.toUpperCase() } }) };\n}\n\n/**\n * Lightness offsets of a generated neutral: the steps text and lines use sit exactly where Bridge's ink anchors\n * sit, so muted text (600) keeps its contrast on zones and subtle backgrounds in every new brand.\n */\nexport function neutralOffset() {\n const off = {};\n for (const [s, hex] of Object.entries(NEUTRAL_ANCHORS)) off[s] = toOklch(fromHex(hex)).L - LIGHTNESS[s];\n return (s) => off[s] ?? 0;\n}\n\n/** A neutral ramp tinted by a hex: hue from the hex, chroma scaled by how tinted it is (0 for a pure grey). */\nexport function tintedNeutral(hex) {\n const rgb = fromHex(hex);\n const { C, h } = toOklch(rgb);\n const ref = neutralChroma()(nearestStep(rgb));\n const scale = C < 0.004 ? 0 : Math.min(2.5, C / ref);\n return { hue: h, scale, ramp: generateRamp({ hue: h, chroma: neutralChroma(scale), offset: neutralOffset() }) };\n}\n","// New brands: one planner shared by the CLI (`bridge brand create`), the MCP server (bridge_plan_brand,\n// bridge_propose_brand), the Figma plugin (a new mode in the Brand collection) and the docs site Studio.\n//\n// A brand only re-points palette roles, radius roles, font roles and typography families (docs/DESIGN-LANGUAGE.md,\n// \"Second brand\"). planNewBrand copies a starting brand (or the default brand's structure for \"blank\"), fills\n// the primary, accent, link and neutral palette roles with ramps from the shared ramp engine (ramps.js, the\n// code packages/tokens/scripts/ramps.mjs runs), copies the starting brand's theme overrides when it has any,\n// adds the slug to modes.brand in bridge.config.json and runs the contrast gate for the new brand in every theme.\n// Nothing is written: the result lists files, contrast, validation, risk tier and a PR body; each surface decides\n// where the files go (a local branch, a remote pull request), never to the default branch.\n\nimport { CONFIG_FILE, type BridgeConfig, loadConfig, tokensPath, toConfigJson } from './config';\nimport { formatChangeset } from './changeset';\nimport { type Combo, type LayerIssue, LayeredTokenSet, validateLayered } from './layered';\nimport { type LayeredContrastResult, checkLayeredPair } from './layered-review';\nimport { RISK_LABELS, type RiskResult, classifyRisk } from './risk';\nimport { type Step, LIGHTNESS, PIN_TOLERANCE, STEPS, anchoredRamp, bellChroma, dtcgColor, fromHex, generateRamp, isHex, neutralChroma, neutralOffset, tintedNeutral, toOklch } from './ramps';\nimport { coerceValue } from './token-edits';\nimport { type ContrastPair, parseContrastChecks } from './wcag';\n\n// --- inputs -----------------------------------------------------------------------------------------------\n\n/** A ramp anchor: a \"#rrggbb\" brand color (pinned in the ramp) or an OKLCH hue in degrees (0..360). */\nexport type HueInput = string | number;\n\nexport interface BrandRadiusInput {\n /** px, on the radius scale (0, 2, 4, 6, 10, 12, 16, 20). */\n inset?: number;\n control?: number;\n container?: number;\n overlay?: number;\n}\n\nexport interface BrandFontsInput {\n /** Display and headings (typography display, h1, h2). A curated font id, see BRAND_FONTS. */\n heading?: string;\n /** Body, UI and captions (typography h3, body, ui, caption). */\n text?: string;\n}\n\nexport interface NewBrandInput {\n /** Lowercase letters, digits and single dashes, 2 to 24 characters: \"acme\", \"north-star\". */\n slug: string;\n /** Display name. Default: the slug in title case. */\n name?: string;\n /** Existing brand to start from, or \"blank\" (the default brand's structure, neutral type and no overrides). */\n from: string;\n /** Primary ramp (also accent and link unless set in `colors`). A hex is pinned at the step primary actions use. */\n primaryHue?: HueInput;\n /** Neutral ramp: text, lines, canvases. A hex tints it with its hue; a pure grey gives a pure grey ramp. */\n neutralHue?: HueInput;\n /** \"More colors\": separate ramps for accent (signal, focus ring) and link. */\n colors?: { accent?: HueInput; link?: HueInput };\n radius?: BrandRadiusInput;\n fonts?: BrandFontsInput;\n /** Exact values for brand tokens, by path (palette.primary.600, radius.control...): hex, \"12px\", \"{alias}\" or DTCG. */\n overrides?: Record<string, unknown>;\n}\n\n/** What the planner reads: the repo's config, its token files (relative to tokens.root) and contrast pairs. */\nexport interface BrandSource {\n config: BridgeConfig;\n /** bridge.config.json as written; edited with a minimal diff. Without it the canonical form is written. */\n configText?: string | undefined;\n files: Map<string, string> | Record<string, string>;\n /** contrast.checks.json text. */\n contrastText?: string | undefined;\n}\n\n// --- curated choices --------------------------------------------------------------------------------------\n\nexport interface BrandFont {\n id: string;\n label: string;\n /** Primitive token the role aliases. */\n token: string;\n /** Where it reads well: headings only (a display serif) or both. */\n use: 'heading' | 'both';\n}\n\n/** The short list the Studio offers. Every font here is self-hosted by @bridge-ds/tokens/fonts.css. */\nexport const BRAND_FONTS: BrandFont[] = [\n { id: 'fraunces', label: 'Fraunces', token: 'font.family.fraunces', use: 'heading' },\n { id: 'instrument-sans', label: 'Instrument Sans', token: 'font.family.instrument-sans', use: 'both' },\n { id: 'plex-sans', label: 'IBM Plex Sans', token: 'font.family.plex-sans', use: 'both' },\n { id: 'system', label: 'System UI', token: 'font.family.system', use: 'both' },\n];\n\nexport interface RadiusPreset {\n id: string;\n label: string;\n hint: string;\n radius: Required<BrandRadiusInput>;\n}\n\nexport const RADIUS_PRESETS: RadiusPreset[] = [\n { id: 'soft', label: 'Soft', hint: 'Rounded, like Bridge', radius: { inset: 6, control: 12, container: 20, overlay: 20 } },\n { id: 'balanced', label: 'Balanced', hint: 'Tighter, like Ocean', radius: { inset: 4, control: 10, container: 16, overlay: 20 } },\n { id: 'crisp', label: 'Crisp', hint: 'Near square corners', radius: { inset: 2, control: 4, container: 6, overlay: 10 } },\n];\n\nconst HEADING_ROLES = ['display', 'h1', 'h2'];\nconst TEXT_ROLES = ['h3', 'body', 'ui', 'caption'];\nconst RADIUS_ROLES = ['inset', 'control', 'container', 'overlay'] as const;\nconst RESERVED = new Set(['default', 'base', 'all', 'none', 'new', 'blank', 'primitives', 'semantic', 'components', 'density']);\nexport const BRAND_SLUG_RE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\nconst DEFAULT_PRIMARY_CHROMA = 0.14;\n\n// --- outputs ----------------------------------------------------------------------------------------------\n\nexport interface PlannedFile {\n /** Repo-relative path. */\n path: string;\n action: 'create' | 'modify';\n content: string;\n}\n\nexport interface BrandIssue {\n level: 'error' | 'warning';\n code: string;\n message: string;\n path?: string;\n file?: string;\n}\n\nexport interface BrandSwatch {\n step: number;\n hex: string;\n}\n\nexport interface BrandContrastSummary {\n /** Pairs checked for the new brand, every theme. */\n checks: number;\n passing: number;\n failing: LayeredContrastResult[];\n /** Every result for the new brand, for tables. */\n results: LayeredContrastResult[];\n themes: string[];\n}\n\nexport interface NewBrandPlan {\n ok: boolean;\n slug: string;\n name: string;\n from: string;\n title: string;\n /** Suggested branch name (governance.branchPrefix + brand-<slug>). */\n branch: string;\n files: PlannedFile[];\n /** Token files after the change, relative to tokens.root (feed it to brandPreviewVariables or a LayeredTokenSet). */\n tokenFiles: Record<string, string>;\n /** bridge.config.json after the change, as text. */\n configText: string;\n /** Primary, neutral (and accent, link when they differ) ramps of the new brand, resolved. */\n ramps: Record<string, BrandSwatch[]>;\n /** Step of the primary ramp that primary actions use in the light theme (where a hex primary is pinned). */\n actionStep: number;\n contrast: BrandContrastSummary;\n /** Slug, input and DTCG problems. Errors block a proposal. */\n issues: BrandIssue[];\n risk: RiskResult & { bump: 'minor' };\n changeset?: { path: string; content: string } | undefined;\n}\n\n// --- helpers ----------------------------------------------------------------------------------------------\n\ntype Json = Record<string, unknown>;\nconst isObj = (x: unknown): x is Json => !!x && typeof x === 'object' && !Array.isArray(x);\nconst fileMap = (f: BrandSource['files']) => (f instanceof Map ? new Map(f) : new Map(Object.entries(f)));\nexport const brandDisplayName = (slug: string) => slug.split('-').filter(Boolean).map((w) => w[0]!.toUpperCase() + w.slice(1)).join(' ');\n\n/** The layer patterns brands use: the brand file and the optional brand x theme overrides. */\nfunction brandLayers(config: BridgeConfig): { brand?: string; override?: string; overrideAxis?: string } {\n const out: { brand?: string; override?: string; overrideAxis?: string } = {};\n for (const l of config.tokens.layers) {\n const ph = (l.files.match(/\\{([^}]+)\\}/g) ?? []).map((p) => p.slice(1, -1));\n if (!ph.includes('brand')) continue;\n if (ph.length === 1 && !out.brand) out.brand = l.files;\n else if (ph.length === 2 && !out.override) {\n out.override = l.files;\n out.overrideAxis = ph.find((p) => p !== 'brand');\n }\n }\n return out;\n}\nconst fill = (pattern: string, combo: Combo) => pattern.replace(/\\{([^}]+)\\}/g, (_, k: string) => combo[k] ?? `{${k}}`);\n\nfunction setAt(doc: Json, path: string, node: Json) {\n const keys = path.split('.');\n let cur = doc;\n for (const k of keys.slice(0, -1)) {\n if (!isObj(cur[k])) cur[k] = {};\n cur = cur[k] as Json;\n }\n const last = keys[keys.length - 1]!;\n const prev = isObj(cur[last]) ? (cur[last] as Json) : {};\n cur[last] = { ...prev, ...node };\n}\nfunction getAt(doc: Json, path: string): Json | undefined {\n let cur: unknown = doc;\n for (const k of path.split('.')) cur = isObj(cur) ? cur[k] : undefined;\n return isObj(cur) ? cur : undefined;\n}\n/** $type of a token in a doc, inherited from its groups. */\nfunction typeAt(doc: Json, path: string): string | undefined {\n let cur: unknown = doc;\n let type: string | undefined;\n for (const k of path.split('.')) {\n if (!isObj(cur)) return type;\n if (typeof cur.$type === 'string') type = cur.$type;\n cur = cur[k];\n }\n return isObj(cur) && typeof cur.$type === 'string' ? cur.$type : type;\n}\n\n/** Ramp for a hue input: a hex is pinned (at `pinStep`), a number is generated with the default chroma. */\nfunction rampFor(input: HueInput, pinStep: Step | undefined, kind: 'color' | 'neutral'): { ramp: Record<number, number[]>; issue?: BrandIssue; anchor: string } {\n if (typeof input === 'number' || (typeof input === 'string' && /^\\d+(\\.\\d+)?$/.test(input.trim()))) {\n const hue = ((Number(input) % 360) + 360) % 360;\n const ramp = kind === 'neutral' ? generateRamp({ hue, chroma: neutralChroma(), offset: neutralOffset() }) : generateRamp({ hue, chroma: bellChroma(DEFAULT_PRIMARY_CHROMA) });\n return { ramp, anchor: `OKLCH hue ${Math.round(hue)}` };\n }\n const hex = String(input).trim();\n if (!isHex(hex)) throw new Error(`\"${hex}\" is not a color. Use #rrggbb or a hue in degrees (0 to 360).`);\n if (kind === 'neutral') {\n const n = tintedNeutral(hex);\n return { ramp: n.ramp, anchor: `${hex.toUpperCase()} (hue ${Math.round(n.hue)})` };\n }\n const a = anchoredRamp(hex, pinStep);\n const issue: BrandIssue | undefined =\n a.distance > PIN_TOLERANCE\n ? {\n level: 'warning',\n code: 'pin-off-ladder',\n message: `${hex.toUpperCase()} is ${a.distance > 0.12 ? 'much ' : ''}${toOklch(fromHex(hex)).L > LIGHTNESS[a.step] ? 'lighter' : 'darker'} than the ${a.step} step it is pinned to, so the ramp around it will not read as one family. Primary actions use this step: pick a ${a.step >= 600 ? 'deeper' : 'lighter'} color.`,\n }\n : undefined;\n return { ramp: a.ramp, anchor: `${hex.toUpperCase()} pinned at ${a.step}`, ...(issue ? { issue } : {}) };\n}\n\n/** Points a palette role at a primitive ramp: palette.<role>.<step> -> {color.<ramp>.<step>} (two tiers, never literals). */\nfunction aliasRamp(doc: Json, role: string, ramp: string, description: string) {\n const group = getAt(doc, `palette.${role}`);\n if (!group) return;\n for (const s of STEPS) {\n if (!(String(s) in group)) continue;\n setAt(doc, `palette.${role}.${s}`, { $value: `{color.${ramp}.${s}}` });\n }\n group.$description = description;\n}\n\n/** Primitive ramps a new brand adds: ramp name -> description and DTCG color per step. */\ntype PrimitiveRamps = Map<string, { description: string; steps: Map<number, unknown> }>;\n\n/** Inserts `slug` into modes.brand.values (or modes.brands) with a minimal text change. */\nexport function addBrandToConfigText(text: string, slug: string): string {\n const canonical = /(\"brand\"\\s*:\\s*\\{\\s*\"values\"\\s*:\\s*\\[)([^\\]]*)(\\])/;\n const flat = /(\"brands\"\\s*:\\s*\\[)([^\\]]*)(\\])/;\n for (const re of [canonical, flat]) {\n const m = re.exec(text);\n if (!m) continue;\n const items = m[2]!.trim();\n const sep = items.includes('\\n') ? `,${/\\n(\\s*)\"/.exec(m[2]!)?.[0]?.replace(/\"$/, '') ?? ' '}` : ', ';\n return text.slice(0, m.index) + m[1] + (items ? `${m[2]!.replace(/\\s*$/, '')}${sep}\"${slug}\"` : `\"${slug}\"`) + (m[2]!.match(/\\s*$/)?.[0] ?? '') + m[3] + text.slice(m.index + m[0].length);\n }\n throw new Error('bridge.config.json has no modes.brand.values list to add the brand to.');\n}\n\n// --- listing ----------------------------------------------------------------------------------------------\n\nexport interface BrandSummary {\n slug: string;\n name: string;\n default: boolean;\n file: string;\n description?: string;\n /** Resolved color.action.primary.bg in the default theme, when the repo has it. */\n primary?: string;\n /** Theme override files the brand has. */\n overrides: string[];\n}\n\nexport function listBrands(source: BrandSource): BrandSummary[] {\n const { config } = source;\n const files = fileMap(source.files);\n const set = new LayeredTokenSet(config, files);\n const layers = brandLayers(config);\n const brandAxis = config.axes.brand;\n if (!brandAxis || !layers.brand) return [];\n return brandAxis.values.map((slug) => {\n const file = fill(layers.brand!, { brand: slug });\n let doc: Json = {};\n try {\n doc = JSON.parse(files.get(file) ?? '{}') as Json;\n } catch {\n /* reported by validation */\n }\n const meta = isObj(doc.$extensions) && isObj(doc.$extensions['dev.bridge.brand']) ? (doc.$extensions['dev.bridge.brand'] as Json) : {};\n const combo = set.normalizeCombo({ brand: slug });\n const primary = set.resolve('color.action.primary.bg', combo);\n const overrides = layers.override ? (config.axes[layers.overrideAxis!]?.values ?? []).map((v) => fill(layers.override!, { brand: slug, [layers.overrideAxis!]: v })).filter((f) => files.has(f)) : [];\n return {\n slug,\n name: typeof meta.name === 'string' ? meta.name : brandDisplayName(slug),\n default: slug === brandAxis.default,\n file: tokensPath(config, file),\n ...(typeof doc.$description === 'string' ? { description: doc.$description } : {}),\n ...(primary.css && !primary.error ? { primary: primary.css } : {}),\n overrides: overrides.map((f) => tokensPath(config, f)),\n };\n });\n}\n\n// --- planning ---------------------------------------------------------------------------------------------\n\n/** Problems with a slug before anything is generated (the Studio uses it as you type). */\nexport function checkBrandSlug(config: BridgeConfig, files: BrandSource['files'], slug: string): BrandIssue[] {\n const out: BrandIssue[] = [];\n const s = slug.trim();\n if (!s) return [{ level: 'error', code: 'slug-empty', message: 'Give the brand a name.' }];\n if (s.length < 2 || s.length > 24 || !BRAND_SLUG_RE.test(s)) out.push({ level: 'error', code: 'slug-format', message: 'Use 2 to 24 lowercase letters, digits and single dashes, starting with a letter: \"acme\" or \"north-star\".' });\n const taken = Object.values(config.axes).flatMap((a) => a.values);\n if (config.axes.brand?.values.includes(s)) out.push({ level: 'error', code: 'slug-taken', message: `A brand called \"${s}\" already exists. Pick another name or edit that brand.` });\n else if (taken.includes(s) || RESERVED.has(s)) out.push({ level: 'error', code: 'slug-reserved', message: `\"${s}\" is a reserved mode name. Pick another name.` });\n const layer = brandLayers(config).brand;\n const map = fileMap(files);\n if (layer && !config.axes.brand?.values.includes(s) && map.has(fill(layer, { brand: s }))) out.push({ level: 'error', code: 'slug-file-exists', message: `${tokensPath(config, fill(layer, { brand: s }))} already exists. Pick another name or add it to bridge.config.json.` });\n return out;\n}\n\nexport function planNewBrand(source: BrandSource, input: NewBrandInput): NewBrandPlan {\n const { config } = source;\n const files = fileMap(source.files);\n const issues: BrandIssue[] = [];\n const slug = input.slug.trim();\n const name = input.name?.trim() || brandDisplayName(slug);\n const layers = brandLayers(config);\n const brandAxis = config.axes.brand;\n if (!brandAxis || !layers.brand) throw new Error('This repo has no brand mode: bridge.config.json needs modes.brand and a tokens layer with {brand}.');\n issues.push(...checkBrandSlug(config, files, slug));\n\n const from = input.from?.trim() || brandAxis.default;\n const blank = from === 'blank';\n if (!blank && !brandAxis.values.includes(from)) throw new Error(`Unknown brand \"${from}\" to start from. Brands: ${brandAxis.values.join(', ')} (or \"blank\").`);\n const template = blank ? brandAxis.default : from;\n const templateFile = fill(layers.brand, { brand: template });\n const templateText = files.get(templateFile);\n if (!templateText) throw new Error(`${tokensPath(config, templateFile)} is missing.`);\n const doc = JSON.parse(templateText) as Json;\n const before = new LayeredTokenSet(config, files);\n\n // Step that primary actions use in the light (default) theme of the starting brand: a hex primary is pinned there.\n const chain = before.resolve('color.action.primary.bg', before.normalizeCombo({ brand: template })).chain;\n const actionStep = Number(/^palette\\.primary\\.(\\d+)$/.exec(chain.find((c) => /^palette\\.primary\\.\\d+$/.test(c)) ?? '')?.[1] ?? 600) as Step;\n\n const anchors: Record<string, string> = {};\n const safeRamp = (role: string, hue: HueInput, kind: 'color' | 'neutral', pin?: Step) => {\n try {\n const r = rampFor(hue, pin, kind);\n if (r.issue) issues.push({ ...r.issue, path: `palette.${role}` });\n anchors[role] = r.anchor;\n return r.ramp;\n } catch (e) {\n issues.push({ level: 'error', code: 'invalid-color', message: (e as Error).message, path: `palette.${role}` });\n return undefined;\n }\n };\n // Generated ramps become primitives (color.<slug>-<role>.<step>); the brand file only aliases them.\n const prims: PrimitiveRamps = new Map();\n const addRamp = (role: string, ramp: Record<number, number[]>, description: string) => {\n const steps = new Map<number, unknown>(STEPS.map((st) => [st, dtcgColor(ramp[st]!)]));\n prims.set(`${slug}-${role}`, { description, steps });\n return `${slug}-${role}`;\n };\n if (input.primaryHue !== undefined && input.primaryHue !== '') {\n const ramp = safeRamp('primary', input.primaryHue, 'color', actionStep);\n if (ramp) {\n const r = addRamp('primary', ramp, `${name} primary. Generated by Bridge from ${anchors.primary}.`);\n aliasRamp(doc, 'primary', r, `${name} primary.`);\n if (input.colors?.accent === undefined) aliasRamp(doc, 'accent', r, `${name} accent: the primary ramp.`);\n if (input.colors?.link === undefined) aliasRamp(doc, 'link', r, `${name} links: the primary ramp.`);\n }\n }\n for (const role of ['accent', 'link'] as const) {\n const hue = input.colors?.[role];\n if (hue === undefined || hue === '') continue;\n const ramp = safeRamp(role, hue, 'color');\n if (ramp) aliasRamp(doc, role, addRamp(role, ramp, `${name} ${role}. Generated by Bridge from ${anchors[role]}.`), `${name} ${role}.`);\n }\n if (input.neutralHue !== undefined && input.neutralHue !== '') {\n const ramp = safeRamp('neutral', input.neutralHue, 'neutral');\n if (ramp) aliasRamp(doc, 'neutral', addRamp('neutral', ramp, `${name} neutral. Generated by Bridge from ${anchors.neutral}.`), `${name} neutral.`);\n }\n\n // Radius roles: aliases of the radius scale.\n const scale = new Map<number, string>();\n for (const [path, defs] of before.view(before.defaultCombo)) {\n const m = /^radius\\.([\\w-]+)$/.exec(path);\n const v = defs[defs.length - 1]!.value;\n if (m && isObj(v) && typeof v.value === 'number' && v.unit === 'px' && !getAt(doc, path)) scale.set(v.value, m[1]!);\n }\n const radius = input.radius ?? (blank ? RADIUS_PRESETS[0]!.radius : undefined);\n if (radius) {\n for (const role of RADIUS_ROLES) {\n const px = radius[role];\n if (px === undefined) continue;\n const step = scale.get(px);\n if (!step) issues.push({ level: 'error', code: 'radius-off-scale', message: `radius.${role} ${px}px is not on the radius scale (${[...scale.keys()].filter((x) => x < 9999).sort((a, b) => a - b).join(', ')} px).`, path: `radius.${role}` });\n else if (getAt(doc, `radius.${role}`)) setAt(doc, `radius.${role}`, { $value: `{radius.${step}}` });\n }\n }\n\n // Font roles and typography families.\n const fonts = input.fonts ?? (blank ? { heading: 'instrument-sans', text: 'instrument-sans' } : undefined);\n const fontToken = (id: string | undefined, role: string) => {\n if (!id) return undefined;\n const f = BRAND_FONTS.find((x) => x.id === id || x.token === id);\n const token = f?.token ?? (id.startsWith('font.family.') ? id : `font.family.${id}`);\n if (!before.view(before.defaultCombo).has(token) || ['font.family.sans', 'font.family.display', 'font.family.mono'].includes(token)) {\n issues.push({ level: 'error', code: 'unknown-font', message: `\"${id}\" is not a font this repo self-hosts. Pick one of: ${BRAND_FONTS.map((x) => x.label).join(', ')}.`, path: `font.family.${role}` });\n return undefined;\n }\n return token;\n };\n const heading = fontToken(fonts?.heading, 'display');\n const text = fontToken(fonts?.text, 'sans');\n if (heading && getAt(doc, 'font.family.display')) setAt(doc, 'font.family.display', { $value: `{${heading}}` });\n if (text && getAt(doc, 'font.family.sans')) setAt(doc, 'font.family.sans', { $value: `{${text}}` });\n for (const r of HEADING_ROLES) if (heading && getAt(doc, `typography.${r}.family`)) setAt(doc, `typography.${r}.family`, { $value: `{${heading}}` });\n for (const r of TEXT_ROLES) if (text && getAt(doc, `typography.${r}.family`)) setAt(doc, `typography.${r}.family`, { $value: `{${text}}` });\n\n // Exact values (the Figma plugin sends every variable of the new mode).\n for (const [path, raw] of Object.entries(input.overrides ?? {})) {\n const node = getAt(doc, path);\n if (!node || !('$value' in node)) {\n issues.push({ level: 'error', code: 'unknown-token', message: `${path} is not a token of the ${template} brand file, so a new brand cannot set it.`, path });\n continue;\n }\n setAt(doc, path, { $value: coerceValue(raw, typeAt(doc, path), node.$value) });\n }\n\n // Exact colors (Figma values, overrides) are hoisted too: a literal palette color becomes the primitive\n // color.<slug>-<role>.<step> and the role aliases it, so brand files never hold literal values.\n const palette = getAt(doc, 'palette');\n for (const [role, group] of Object.entries(palette ?? {})) {\n if (role.startsWith('$') || !isObj(group)) continue;\n for (const [step, node] of Object.entries(group)) {\n if (step.startsWith('$') || !isObj(node) || !('$value' in node) || typeof node.$value === 'string') continue;\n const ramp = `${slug}-${role}`;\n const entry = prims.get(ramp) ?? { description: `${name} ${role}. Exact values set when the brand was created.`, steps: new Map<number, unknown>() };\n entry.steps.set(Number(step), node.$value);\n prims.set(ramp, entry);\n setAt(doc, `palette.${role}.${step}`, { $value: `{color.${ramp}.${step}}` });\n }\n }\n const primDir = config.tokens.tiers.primitive?.[0]?.replace(/\\/$/, '') ?? config.tokens.primitives;\n const primFile = `${primDir}/${slug}.tokens.json`;\n if (prims.size && files.has(primFile)) issues.push({ level: 'error', code: 'slug-file-exists', message: `${tokensPath(config, primFile)} already exists. Pick another name.` });\n for (const r of prims.keys()) if (before.allPaths().some((p) => p.startsWith(`color.${r}.`))) issues.push({ level: 'error', code: 'ramp-exists', message: `A primitive ramp color.${r} already exists. Pick another name.` });\n\n doc.$description = `${name}: created with Bridge, started from ${blank ? 'a blank brand' : brandDisplayName(from)}.`;\n doc.$extensions = { ...(isObj(doc.$extensions) ? doc.$extensions : {}), 'dev.bridge.brand': { name, from, ...(Object.keys(anchors).length ? { anchors } : {}) } };\n // Keep $description and $extensions on top, like the hand-written brand files.\n const { $description, $extensions, ...rest } = doc;\n const brandFile = fill(layers.brand, { brand: slug });\n const nextFiles = new Map(files);\n const created: string[] = [];\n if (prims.size) {\n const color: Json = { $type: 'color' };\n for (const [r, { description, steps }] of prims) {\n const ramp: Json = { $description: description };\n for (const st of [...steps.keys()].sort((a, b) => a - b)) ramp[String(st)] = { $value: steps.get(st) };\n color[r] = ramp;\n }\n const prim = { $description: `${name} brand ramps, generated by Bridge (@bridge-ds/core ramp engine). Never used by components directly: brands/${slug}.tokens.json maps them to palette roles.`, color };\n nextFiles.set(primFile, `${JSON.stringify(prim, null, 2)}\\n`);\n created.push(primFile);\n }\n created.push(brandFile);\n nextFiles.set(brandFile, `${JSON.stringify({ $description, $extensions, ...rest }, null, 2)}\\n`);\n\n // Theme overrides of the starting brand come along: they point at palette roles, so they follow the new ramps.\n if (!blank && layers.override && layers.overrideAxis) {\n for (const v of config.axes[layers.overrideAxis]?.values ?? []) {\n const src = fill(layers.override, { brand: from, [layers.overrideAxis]: v });\n const text = files.get(src);\n if (!text) continue;\n const o = JSON.parse(text) as Json;\n const out = { ...o, $description: `${name} overrides on top of semantic/${v}, copied from ${brandDisplayName(from)}.` };\n const dst = fill(layers.override, { brand: slug, [layers.overrideAxis]: v });\n nextFiles.set(dst, `${JSON.stringify(out, null, 2)}\\n`);\n created.push(dst);\n }\n }\n\n // bridge.config.json: modes.brand += slug.\n const baseConfigText = source.configText ?? `${JSON.stringify(toConfigJson(config), null, 2)}\\n`;\n let configText = baseConfigText;\n let nextConfig = config;\n try {\n configText = addBrandToConfigText(baseConfigText, slug);\n nextConfig = issues.some((i) => i.code.startsWith('slug-')) ? config : loadConfig(configText);\n } catch (e) {\n issues.push({ level: 'error', code: 'config', message: (e as Error).message });\n }\n\n // Validation (only problems the new brand brings) and the contrast gate for the new brand in every theme.\n const after = new LayeredTokenSet(nextConfig, nextFiles);\n const key = (i: LayerIssue) => `${i.code}|${i.path ?? ''}|${i.message}`;\n const known = new Set(validateLayered(before).map(key));\n const brandKey = `brand=${slug}`;\n for (const i of validateLayered(after)) {\n if (known.has(key(i))) continue;\n if (i.modes && !i.modes.some((m) => m.split(',').includes(brandKey)) && !created.includes(i.file ?? '')) continue;\n issues.push({ level: i.level, code: i.code, message: i.message, ...(i.path ? { path: i.path } : {}), ...(i.file ? { file: tokensPath(config, i.file) } : {}) });\n }\n const pairs: ContrastPair[] = parseContrastChecks(source.contrastText);\n const inGate = nextConfig.axes.brand?.values.includes(slug);\n const combos = inGate ? after.combos(nextConfig.contrast?.modes).filter((c) => c.brand === slug) : [];\n const results = combos.flatMap((c) => pairs.map((p) => checkLayeredPair(after, p, c)));\n const failing = results.filter((r) => !r.pass);\n const themes = [...new Set(combos.map((c) => c.theme).filter((t): t is string => !!t))];\n\n // Ramps, resolved (so Figma values and overrides show as they will ship).\n const ramps: Record<string, BrandSwatch[]> = {};\n if (inGate) {\n const combo = after.normalizeCombo({ brand: slug });\n const read = (role: string) =>\n STEPS.map((s) => ({ step: s, hex: after.resolve(`palette.${role}.${s}`, combo).css })).filter((x) => /^#[0-9a-f]{6}$/i.test(x.hex));\n ramps.primary = read('primary');\n ramps.neutral = read('neutral');\n for (const role of ['accent', 'link']) {\n const r = read(role);\n if (JSON.stringify(r) !== JSON.stringify(ramps.primary)) ramps[role] = r;\n }\n }\n\n // Tier: every token of the new files is an addition, bridge.config.json is a guardrail. Tier 3, minor.\n const addedTokens = after.defs.filter((d) => created.includes(d.file)).map((d) => ({ kind: 'added' as const, path: d.path }));\n const risk = classifyRisk({ tokenChanges: addedTokens, files: [{ path: CONFIG_FILE, status: 'modified' }], config });\n const planned: PlannedFile[] = [\n ...created.map((f) => ({ path: tokensPath(config, f), action: 'create' as const, content: nextFiles.get(f)! })),\n { path: CONFIG_FILE, action: 'modify', content: configText },\n ];\n const cs = config.changesets ?? (config.changeset ? { dir: '.changeset', package: config.changeset.package } : undefined);\n const changeset = cs\n ? {\n path: `${cs.dir}/bridge-brand-${slug}.md`,\n content: formatChangeset(cs.package, 'minor', `Add the ${name} brand (\\`${slug}\\`), started from ${blank ? 'a blank brand' : brandDisplayName(from)}.`, `- ${created.map((f) => `\\`${tokensPath(config, f)}\\``).join('\\n- ')}\\n- \\`${CONFIG_FILE}\\`: modes.brand gains \"${slug}\", so the token build and the contrast gate cover it.`),\n }\n : undefined;\n if (changeset) planned.push({ path: changeset.path, action: 'create', content: changeset.content });\n\n const errors = issues.filter((i) => i.level === 'error');\n return {\n ok: errors.length === 0 && failing.length === 0 && results.length > 0,\n slug,\n name,\n from,\n title: `Add the ${name} brand`,\n branch: `${config.governance.branchPrefix}brand-${slug || 'new'}`,\n files: planned,\n tokenFiles: Object.fromEntries(nextFiles),\n configText,\n ramps,\n actionStep,\n contrast: { checks: results.length, passing: results.length - failing.length, failing, results, themes },\n issues,\n risk: { ...risk, bump: 'minor' },\n changeset,\n };\n}\n\n/** CSS variables of a planned brand in one theme (every semantic and component token), for live previews. */\nexport function brandPreviewVariables(source: BrandSource, plan: Pick<NewBrandPlan, 'slug' | 'tokenFiles' | 'configText'>, theme?: string): Record<string, string> {\n let config = source.config;\n try {\n config = loadConfig(plan.configText);\n } catch {\n /* keep the old config: the preview falls back to the default brand */\n }\n const set = new LayeredTokenSet(config, new Map(Object.entries(plan.tokenFiles)));\n let combo: Combo;\n try {\n combo = set.normalizeCombo({ brand: plan.slug, ...(theme ? { theme } : {}) });\n } catch {\n combo = set.normalizeCombo(theme ? { theme } : {});\n }\n const out: Record<string, string> = {};\n for (const path of set.view(combo).keys()) {\n const tier = set.tierOf(path);\n if (tier === 'primitive') continue;\n const r = set.resolve(path, combo);\n if (!r.error && r.css) out[set.cssVarName(path)] = r.css;\n }\n return out;\n}\n\n// --- PR body ----------------------------------------------------------------------------------------------\n\nconst code = (s: string) => `\\`${s}\\``;\n\n/** The \"New brand\" section: swatch ramps and the contrast summary. GitHub shows a chip next to `#rrggbb`. */\nexport function newBrandSection(plan: NewBrandPlan): string {\n const roles = Object.keys(plan.ramps);\n const rampTable = roles.length\n ? [\n `| Step | ${roles.map((r) => r[0]!.toUpperCase() + r.slice(1)).join(' | ')} |`,\n `| --- | ${roles.map(() => '---').join(' | ')} |`,\n ...STEPS.map((s) => `| ${s}${s === plan.actionStep ? ' (actions)' : ''} | ${roles.map((r) => code(plan.ramps[r]!.find((x) => x.step === s)?.hex ?? '')).join(' | ')} |`),\n ].join('\\n')\n : '_No ramps resolved._';\n const c = plan.contrast;\n const contrastLine = c.failing.length\n ? `**${c.failing.length} of ${c.checks} pairs fail** for ${plan.name} (${c.themes.join(' and ')}).`\n : `All ${c.checks} contrast checks pass for ${plan.name} in ${c.themes.join(' and ')}.`;\n const failRows = c.failing.slice(0, 20).map((r) => `| ${code(r.fg)} on ${code(r.bg)} | ${r.modes.split(',').find((m) => m.startsWith('theme='))?.slice(6) ?? r.modes} | ${r.ratio ?? 'n/a'} | ${r.min} |`);\n const tightest = [...c.results].filter((r) => r.pass && r.ratio !== null).sort((a, b) => a.ratio! - a.min - (b.ratio! - b.min)).slice(0, 3);\n return [\n '## New brand',\n '',\n `- Name: **${plan.name}** (${code(plan.slug)})`,\n `- Started from: ${plan.from === 'blank' ? 'a blank brand' : brandDisplayName(plan.from)}`,\n `- Primary actions use step ${plan.actionStep} of the primary ramp in the light theme.`,\n '',\n rampTable,\n '',\n '### Contrast',\n '',\n contrastLine,\n ...(failRows.length ? ['', '| Pair | Theme | Ratio | Min |', '| --- | --- | --- | --- |', ...failRows] : []),\n ...(tightest.length ? ['', `Tightest passing pairs: ${tightest.map((r) => `${code(r.fg)} on ${code(r.bg)} ${r.ratio}:1 (min ${r.min})`).join('; ')}.`] : []),\n ].join('\\n');\n}\n\nexport interface NewBrandBodyOptions {\n /** \"the bridge CLI\", \"Bridge MCP\", \"the Bridge Studio\", \"the DS Bridge Figma plugin\". */\n tool: string;\n author?: string;\n /** true when an AI agent proposed it. */\n agent?: boolean;\n /** Free text from the person proposing. */\n notes?: string;\n}\n\nexport function composeNewBrandBody(plan: NewBrandPlan, opts: NewBrandBodyOptions): string {\n const t = plan.risk.tier;\n const box = (n: 1 | 2 | 3) => `- ${n === t ? '[x]' : '[ ]'} ${RISK_LABELS[n]}`;\n const errors = plan.issues.filter((i) => i.level === 'error');\n const warnings = plan.issues.filter((i) => i.level === 'warning');\n return [\n '## What changed and why',\n '',\n `Adds the ${plan.name} brand. Components do not change: the brand re-points palette, radius and font roles, and the token build, the contrast gate and the docs pick it up from ${code('bridge.config.json')}.`,\n ...(opts.notes?.trim() ? ['', opts.notes.trim()] : []),\n '',\n `Proposed through ${opts.tool}${opts.author ? ` by ${opts.author}` : ''}.${opts.agent ? ' Agent-authored: a human design owner and tech owner review and merge.' : ''}`,\n '',\n newBrandSection(plan),\n '',\n '## Files',\n '',\n ...plan.files.map((f) => `- ${f.action === 'create' ? 'Create' : 'Modify'} ${code(f.path)}`),\n '',\n '## Risk tier',\n '',\n box(1),\n box(2),\n box(3),\n '',\n `- Brand added: ${plan.files.filter((f) => f.action === 'create' && f.path.endsWith('.tokens.json')).length} token file(s), every token new`,\n `- ${code('bridge.config.json')} is a guardrail file`,\n `- Semver bump: ${code(plan.risk.bump)} for ${code('@bridge-ds/tokens')}`,\n '',\n '## Checks',\n '',\n `- Token validation: ${errors.length ? `**${errors.length} error(s)**` : 'no errors'} (DTCG shapes, aliases, every mode)${warnings.length ? `, ${warnings.length} warning(s): ${warnings.map((w) => w.message).join(' ')}` : ''}`,\n `- Contrast gate for ${plan.name}: ${plan.contrast.failing.length ? `**${plan.contrast.failing.length} failing pair(s)**` : `all ${plan.contrast.checks} pairs pass`}`,\n '',\n '## Authored by',\n '',\n opts.agent ? '- [ ] Human' : '- [x] Human',\n opts.agent ? '- [x] AI agent (Claude), reviewed by a human before merge' : '- [ ] AI agent',\n '',\n '## Design review checklist',\n '',\n '- [ ] Checked in light and dark, with real components (Studio preview or Storybook brand switch)',\n '- [ ] Primary, zone and link colors read as one family',\n '- [ ] Changeset bump matches the tier',\n '',\n ].join('\\n');\n}\n","// Component docs drafts: the deterministic part of a component's documentation, computed from its code, and the\n// review state of prose an AI drafted. Shared by the Bridge docs editor, the MCP server (bridge_draft_docs), the\n// CLI (bridge docs draft) and the docs-draft GitHub Action, so a draft looks the same wherever it starts.\n//\n// What code can tell (deterministic, never invented): the props table from the TypeScript props, the tokens the\n// stylesheet reads, the anatomy from the CSS module classes, the contrast pairs those tokens take part in, and a\n// changelog line. What only a person (or an AI, then a person) can write: summary, when to use, do and don't,\n// accessibility and content guidelines. Prose an AI wrote carries \"draftedBy\": \"claude\" and \"needsReview\": true\n// until a reviewer accepts it.\n\nimport { type JsonEntry, type JsonNode, fromPlain, getEntry, parseJson, plainEqual, serializeJson, toPlain } from './json-ast';\n\nexport type DocsExampleNode = string | { c: string; p?: Record<string, unknown>; children?: DocsExampleNode[] };\n\nexport interface DocsGuidance {\n title: string;\n text: string;\n example?: DocsExampleNode;\n}\n\n/** The shape of <Name>.docs.json (same keys as Button.docs.json). */\nexport interface ComponentDocsJson {\n summary: string;\n category?: string;\n status?: 'stable' | 'beta' | 'deprecated';\n preview?: DocsExampleNode;\n whenToUse: string[];\n whenNotToUse: string[];\n dos: DocsGuidance[];\n donts: DocsGuidance[];\n accessibility: string[];\n contentGuidelines?: string[];\n anatomy?: Record<string, string>;\n /** Who wrote the prose when it was not a person in the editor. Only \"claude\" today. */\n draftedBy?: string;\n /**\n * The prose sections Claude drafted that wait for review, when a draft covered only some of them (in-place drafting\n * on the Library page, the docs-draft Action). Missing means the whole file. Accepting removes it.\n */\n draftedSections?: ProseKey[];\n /** True while drafted prose waits for a reviewer. Accepting sets it to false. */\n needsReview?: boolean;\n}\n\n/** Keys of docs.json in the order Button.docs.json lists them. The editor and the drafts follow this order. */\nexport const DOCS_KEYS = ['summary', 'preview', 'whenToUse', 'whenNotToUse', 'dos', 'donts', 'accessibility', 'contentGuidelines', 'anatomy'] as const;\nexport type DocsKey = (typeof DOCS_KEYS)[number];\n\n/** Prose keys: the ones code cannot fill. */\nexport const PROSE_KEYS = ['summary', 'whenToUse', 'whenNotToUse', 'dos', 'donts', 'accessibility', 'contentGuidelines'] as const;\nexport type ProseKey = (typeof PROSE_KEYS)[number];\n\nexport interface DocsPropInput {\n name: string;\n type: string;\n required: boolean;\n defaultValue?: string | undefined;\n description?: string | undefined;\n}\n\nexport interface DocsContrastInput {\n foreground: string;\n background: string;\n /** Lowest ratio over every brand and theme. */\n ratio: number;\n min: number;\n}\n\nexport interface DocsPrefillInput {\n /** PascalCase component name. */\n name: string;\n /** JSDoc of the component export, when there is one. */\n description?: string | undefined;\n props: DocsPropInput[];\n /** Native element whose attributes the component also accepts (button, span). */\n inherits?: string | undefined;\n /** CSS custom properties the stylesheet reads that are tokens, e.g. --color-text-default. */\n tokens: string[];\n /** Tokens it reads through another component's stylesheet, by that component (IconButton reads Button's). */\n inheritedTokens?: Record<string, string[]>;\n /** Class names of the CSS module, in source order. */\n cssClasses: string[];\n /** Contrast pairs from the contrast checks that involve the tokens it reads. */\n contrast?: DocsContrastInput[];\n /** The docs.json it has today, if any: existing prose is kept, only gaps are listed. */\n existing?: Partial<ComponentDocsJson> | null;\n /** What changed, when the pre-fill runs for a proposed change (\"token color.text.muted changed\"). */\n change?: string;\n}\n\nexport interface DocsPrefill {\n component: string;\n /** Markdown table: prop, type, default, description. Empty string when the component has no props. */\n propsTable: string;\n tokens: string[];\n inheritedTokens: Record<string, string[]>;\n /** Class name -> readable label, keeping labels a writer already set. */\n anatomy: Record<string, string>;\n contrastNotes: string[];\n changelogLine: string;\n /** Prose keys with no content yet. */\n missing: ProseKey[];\n /** docs.json with the deterministic parts filled and the existing prose kept. Empty prose stays empty. */\n draft: ComponentDocsJson;\n}\n\nconst ACRONYMS = new Set(['sm', 'md', 'lg', 'xl', 'xs']);\n\n/** Readable label for a CSS module class: iconOnly -> \"Icon only\", is-open -> \"Is open\", sm -> \"Size sm\". */\nexport function anatomyLabel(className: string): string {\n if (ACRONYMS.has(className)) return `Size ${className}`;\n const words = className\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/[-_]+/g, ' ')\n .trim()\n .toLowerCase();\n if (!words) return className;\n if (words === 'root') return 'Container';\n return words.charAt(0).toUpperCase() + words.slice(1);\n}\n\n/** Class names of a CSS module, in source order, without duplicates and without keyframes. */\nexport function cssModuleClasses(css: string): string[] {\n const clean = css.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '').replace(/@keyframes\\s+[\\w-]+\\s*\\{(?:[^{}]*\\{[^{}]*\\})*[^{}]*\\}/g, '');\n const out: string[] = [];\n for (const m of clean.matchAll(/\\.(-?[_a-zA-Z][\\w-]*)/g)) {\n // Skip decimals inside values (0.5) and file names: a class follows a selector boundary.\n const before = clean[m.index! - 1] ?? ' ';\n if (/[\\w)]/.test(before)) continue;\n if (!out.includes(m[1]!)) out.push(m[1]!);\n }\n return out;\n}\n\nconst cell = (s: string) => s.replace(/\\|/g, '\\\\|').replace(/\\n/g, ' ');\n\nexport function propsTable(name: string, props: DocsPropInput[], inherits?: string): string {\n if (!props.length) return inherits ? `${name} has no props of its own. It accepts every native <${inherits}> attribute.` : '';\n const rows = props.map((p) => `| \\`${p.name}\\`${p.required ? ' (required)' : ''} | \\`${cell(p.type)}\\` | ${p.defaultValue ? `\\`${cell(p.defaultValue)}\\`` : ''} | ${cell(p.description ?? '')} |`);\n const tail = inherits ? `\\n\\nAlso accepts every native <${inherits}> attribute.` : '';\n return ['| Prop | Type | Default | Description |', '| --- | --- | --- | --- |', ...rows].join('\\n') + tail;\n}\n\nconst isEmpty = (v: unknown) => v === undefined || v === null || (typeof v === 'string' && !v.trim()) || (Array.isArray(v) && v.length === 0);\n\n/** Prose keys with no content in a docs.json (missing or empty). */\nexport function missingProse(d: Partial<ComponentDocsJson> | null | undefined): ProseKey[] {\n return PROSE_KEYS.filter((k) => isEmpty(d?.[k]));\n}\n\n/** The deterministic pre-fill of a component's docs. Same input, same output: nothing is invented. */\nexport function prefillDocs(input: DocsPrefillInput): DocsPrefill {\n const existing = input.existing ?? null;\n const anatomy: Record<string, string> = {};\n for (const c of input.cssClasses) anatomy[c] = existing?.anatomy?.[c] ?? anatomyLabel(c);\n const contrastNotes = (input.contrast ?? [])\n .slice()\n .sort((a, b) => a.ratio - b.ratio)\n .map((p) => `${p.foreground} on ${p.background}: ${p.ratio.toFixed(2)}:1 at worst over every brand and theme, needs ${p.min}:1 (${p.ratio >= p.min ? 'passes' : 'fails'}).`);\n const missing = missingProse(existing);\n const changelogLine = input.change\n ? `${input.name}: ${input.change.replace(/\\.$/, '')}.`\n : missing.length === PROSE_KEYS.length\n ? `${input.name}: usage guidance added.`\n : `${input.name}: usage guidance updated.`;\n const draft: ComponentDocsJson = {\n summary: existing?.summary ?? input.description ?? '',\n ...(existing?.category ? { category: existing.category } : {}),\n ...(existing?.status ? { status: existing.status } : {}),\n ...(existing?.preview ? { preview: existing.preview } : {}),\n whenToUse: existing?.whenToUse ?? [],\n whenNotToUse: existing?.whenNotToUse ?? [],\n dos: existing?.dos ?? [],\n donts: existing?.donts ?? [],\n accessibility: existing?.accessibility ?? [],\n contentGuidelines: existing?.contentGuidelines ?? [],\n anatomy,\n ...(existing?.draftedBy ? { draftedBy: existing.draftedBy } : {}),\n ...(existing?.draftedSections?.length ? { draftedSections: existing.draftedSections } : {}),\n ...(existing?.needsReview !== undefined ? { needsReview: existing.needsReview } : {}),\n };\n return {\n component: input.name,\n propsTable: propsTable(input.name, input.props, input.inherits),\n tokens: [...new Set(input.tokens)].sort(),\n inheritedTokens: input.inheritedTokens ?? {},\n anatomy,\n contrastNotes,\n changelogLine,\n missing,\n draft,\n };\n}\n\nexport interface DocsConventions {\n /** AGENTS.md (or the part about docs.json). */\n agents?: string;\n /** The voice section of the design language. */\n voice?: string;\n /** A finished docs.json to copy the structure and tone from (Button.docs.json). */\n example?: string;\n /** The component source, so the prose stays true to the code. */\n source?: string;\n /** The component's CSS module: its states and parts, so the prose stays true to the look. */\n styles?: string;\n}\n\n/** What docsPrompt asks for. Without `keys`, the missing prose as a full docs.json (the docs-draft Action, bridge_draft_docs). */\nexport interface DocsPromptOptions {\n /** Only these sections, answered as an object holding only them. */\n keys?: readonly ProseKey[];\n /** Rewrite the sections even when they hold text. */\n rewrite?: boolean;\n /**\n * Written sections older than the component code, to check (among `keys`): Claude returns one only when something\n * in it is no longer true for the code, keeping the writer's wording elsewhere; an accurate one is left out.\n */\n check?: readonly ProseKey[];\n}\n\nconst SECTION_SHAPE: Record<ProseKey, string> = {\n summary: '\"summary\": \"one or two sentences\"',\n whenToUse: '\"whenToUse\": [\"...\"]',\n whenNotToUse: '\"whenNotToUse\": [\"...\"]',\n dos: '\"dos\": [{ \"title\": \"...\", \"text\": \"...\" }]',\n donts: '\"donts\": [{ \"title\": \"...\", \"text\": \"...\" }]',\n accessibility: '\"accessibility\": [\"...\"]',\n contentGuidelines: '\"contentGuidelines\": [\"...\"]',\n};\n\n/** The JSON shape of these sections, for a prompt: {\"summary\": \"...\", \"dos\": [{ \"title\", \"text\" }]}. */\nexport const docsSectionShapes = (keys: readonly ProseKey[]): string => `{ ${keys.map((k) => SECTION_SHAPE[k]).join(', ')} }`;\n\n/**\n * The prompt a model gets to write the prose of a docs.json: the pre-fill as facts, the conventions, and strict\n * rules (no invention, JSON only). Used by the GitHub Action and returned by bridge_draft_docs for the user's own\n * Claude.\n */\nexport function docsPrompt(prefill: DocsPrefill, conventions: DocsConventions = {}, options: DocsPromptOptions = {}): string {\n const facts = [\n `Component: ${prefill.component}`,\n prefill.propsTable ? `Props (parsed from TypeScript):\\n${prefill.propsTable}` : 'Props: none of its own.',\n `Tokens its stylesheet reads: ${prefill.tokens.join(', ') || 'none'}`,\n ...Object.entries(prefill.inheritedTokens).map(([from, list]) => `Tokens it reads through ${from}'s stylesheet: ${list.length}`),\n `Anatomy (CSS module classes): ${Object.entries(prefill.anatomy)\n .map(([k, v]) => `${k} = ${v}`)\n .join('; ') || 'none'}`,\n prefill.contrastNotes.length ? `Contrast checks:\\n- ${prefill.contrastNotes.join('\\n- ')}` : '',\n `Changelog line: ${prefill.changelogLine}`,\n ].filter(Boolean);\n const block = (title: string, text?: string) => (text?.trim() ? `<${title}>\\n${text.trim()}\\n</${title}>` : '');\n const keys = options.keys;\n const check = keys ? (options.check ?? []).filter((k) => keys.includes(k)) : [];\n const write = keys ? keys.filter((k) => !check.includes(k)) : [];\n const task = keys\n ? [\n ...(write.length ? [`${options.rewrite ? 'Rewrite' : 'Write'} these sections of ${prefill.component}.docs.json for the Bridge design system: ${write.join(', ')}.`] : []),\n ...(check.length\n ? [\n `Check these written sections of ${prefill.component}.docs.json against the current code: ${check.join(', ')}. The code changed after they were written.`,\n 'Return a checked section ONLY when something in it is no longer true for the code (a wrong or removed prop, a removed state or variant, changed behavior). Then return the whole section with only the untrue parts fixed, keeping the writer\\'s wording everywhere else.',\n 'Leave a checked section out of the answer when it is still accurate: a missing key means unchanged. Never return a checked section just to improve its style.',\n ]\n : []),\n ...(options.rewrite ? ['Rewrite each one from the facts and the source: keep what is true in the current text, drop what the code does not support.'] : []),\n ]\n : [`Write the missing prose of ${prefill.component}.docs.json for the Bridge design system.`];\n const shape = keys\n ? [\n `- ${check.length ? 'Return' : 'Write'} only these keys: ${keys.join(', ')}${check.length ? ` (the checked ones, ${check.join(', ')}, only when they need a fix)` : ''}. Never return anatomy, preview or any other key: code decides them.`,\n `- Answer with one JSON object holding only those keys, nothing else: ${docsSectionShapes(keys)}.`,\n ]\n : [\n `- Fill only these keys: ${prefill.missing.join(', ') || 'none (everything is written: improve nothing, return the draft as is)'}. Keep every other key exactly as given.`,\n '- Answer with the full docs.json as one JSON object, nothing else.',\n ];\n return [\n ...task,\n '',\n 'Rules:',\n '- Ground every sentence in the facts and the source below. Never invent props, variants, keyboard behavior or tokens that are not there.',\n '- Bridge voice: sentence case, plain words, verbs first, no em dashes, no marketing words.',\n '- Keep the keys and shapes of the example docs.json. dos and donts are { \"title\", \"text\" } objects; add an \"example\" only with components and props that exist.',\n ...shape,\n '',\n 'Facts computed from the code:',\n facts.join('\\n\\n'),\n '',\n `Current draft:\\n${JSON.stringify(prefill.draft, null, 2)}`,\n '',\n block('source', conventions.source),\n block('styles', conventions.styles),\n block('agents-md', conventions.agents),\n block('voice', conventions.voice),\n block('example-docs-json', conventions.example),\n ]\n .filter((x, i, all) => x !== '' || all[i - 1] !== '')\n .join('\\n');\n}\n\n/**\n * Marks prose as drafted by Claude and waiting for review. With `sections`, only those sections were drafted: they\n * join the ones already waiting (draftedSections, in the PROSE_KEYS order). Without, the whole file was.\n */\nexport function markClaudeDraft<T extends Partial<ComponentDocsJson>>(d: T, sections?: readonly ProseKey[]): T {\n if (!sections) {\n const { draftedSections: _all, ...rest } = d;\n return { ...rest, draftedBy: 'claude', needsReview: true } as T;\n }\n const waiting = d.needsReview === true ? (d.draftedSections ?? (d.draftedBy ? [...PROSE_KEYS] : [])) : [];\n const union = PROSE_KEYS.filter((k) => waiting.includes(k) || sections.includes(k));\n return { ...d, draftedBy: 'claude', needsReview: true, draftedSections: union };\n}\n\n/** Prose sections that wait for review: draftedSections, every prose key for a whole-file draft, none once accepted. */\nexport function sectionsNeedingReview(d: Partial<ComponentDocsJson> | null | undefined): ProseKey[] {\n if (!d || d.needsReview !== true) return [];\n return d.draftedSections ? PROSE_KEYS.filter((k) => d.draftedSections!.includes(k)) : [...PROSE_KEYS];\n}\n\n/** True when the docs hold AI-drafted prose nobody has reviewed yet. */\nexport const needsDocsReview = (d: Partial<ComponentDocsJson> | null | undefined): boolean => Boolean(d && d.needsReview === true);\n\n/** A reviewer accepts drafted prose: needsReview goes false, draftedBy stays as the record of who wrote it. */\nexport function acceptDocsDraft(d: ComponentDocsJson): ComponentDocsJson {\n const { draftedSections: _done, ...rest } = d;\n return { ...rest, needsReview: false };\n}\n\n/** docs.json text the way the repo writes it: two spaces, keys in the Button.docs.json order, trailing newline. */\nexport function formatDocsJson(d: Partial<ComponentDocsJson>): string {\n const order = ['summary', 'category', 'status', ...DOCS_KEYS.filter((k) => k !== 'summary'), 'draftedBy', 'draftedSections', 'needsReview'];\n const out: Record<string, unknown> = {};\n for (const k of order) if ((d as Record<string, unknown>)[k] !== undefined) out[k] = (d as Record<string, unknown>)[k];\n for (const [k, v] of Object.entries(d)) if (!(k in out) && v !== undefined) out[k] = v;\n return `${JSON.stringify(out, null, 2)}\\n`;\n}\n\n/** Keeps untouched nodes as they were written; rebuilds only what changed, in the shape of what it replaces. */\nfunction patchNode(old: JsonNode, next: unknown): JsonNode {\n if (plainEqual(toPlain(old), next)) return old;\n if (old.kind === 'object' && next && typeof next === 'object' && !Array.isArray(next)) {\n const n = next as Record<string, unknown>;\n const kept = old.entries.filter((e) => n[e.key] !== undefined).map((e): JsonEntry => ({ key: e.key, value: patchNode(e.value, n[e.key]) }));\n const added = Object.keys(n)\n .filter((k) => n[k] !== undefined && !getEntry(old, k))\n .map((k): JsonEntry => ({ key: k, value: fromPlain(n[k], undefined, old.inline) }));\n return { kind: 'object', inline: old.inline, entries: [...kept, ...added] };\n }\n if (old.kind === 'array' && Array.isArray(next)) {\n return { kind: 'array', inline: old.inline, items: next.map((v, i) => (old.items[i] ? patchNode(old.items[i]!, v) : fromPlain(v, old.items[0], old.inline))) };\n }\n return fromPlain(next, old);\n}\n\n/**\n * docs.json text for edited docs, written as a minimal diff of the file it replaces: untouched sections stay byte for\n * byte (a hand-formatted file keeps its inline preview nodes), new keys go at the end in the repo order. Without an\n * original (or with one that is not valid JSON) it falls back to formatDocsJson.\n */\nexport function patchDocsJson(original: string | null | undefined, next: Partial<ComponentDocsJson>): string {\n const plain = JSON.parse(formatDocsJson(next)) as unknown;\n if (!original) return formatDocsJson(next);\n try {\n const doc = parseJson(original);\n if (doc.root.kind !== 'object') return formatDocsJson(next);\n return serializeJson({ ...doc, root: patchNode(doc.root, plain) });\n } catch {\n return formatDocsJson(next);\n }\n}\n\n/** Accepts the drafted prose inside a docs.json text: only the review lines change. Throws on invalid JSON. */\nexport function acceptDocsText(text: string): string {\n return patchDocsJson(text, acceptDocsDraft(JSON.parse(text) as ComponentDocsJson));\n}\n\n/** Tier and bump of a docs-only change: Tier 1 under the shared classifier, and a patch. */\nexport const DOCS_CHANGE_BUMP = 'patch' as const;\n","// Change drafts: the words a designer would otherwise type by hand when sending a change for review. Deterministic and\n// offline: computed only from what the diff detected, so they never invent a reason or a number. Shared by the Figma\n// plugin (request form, Push description) and any tool that sends requests or pull requests from detected changes.\n//\n// Voice (docs/DESIGN-LANGUAGE.md section 10): sentence case, starts with a verb, no em dash, digits for numbers.\n// A request title never repeats the component: the issue title already starts with it (\"Badge: add a danger tone\").\n\nimport type { DiffEntry } from './diff-engine';\nimport type { RequestChange, RequestKind } from './requests';\nimport { modeDisplayName } from './types';\nimport { formatValue } from './values';\n\nexport interface DraftText {\n /** One line, sentence case, no trailing period. Empty when nothing was detected. */\n title: string;\n /** 1 or 2 sentences. Empty when nothing was detected. */\n summary: string;\n}\n\n/** Removes em dashes (U+2014), the punctuation the Bridge voice never uses: \" a [em dash] b \" becomes \"a, b\". */\nexport function cleanDraftText(text: string): string {\n return text\n .replace(/\\s*\\u2014\\s*/g, ', ')\n .replace(/,\\s*,/g, ',')\n .replace(/^,\\s*/, '')\n .replace(/[ \\t]+/g, ' ')\n .trim();\n}\n\nconst values = (s: string | undefined) => (s ?? '').split(', ').map((x) => x.trim()).filter(Boolean);\nconst article = (word: string) => (/^[aeiou]/i.test(word) ? 'an' : 'a');\nconst andList = (xs: string[]) => (xs.length <= 1 ? (xs[0] ?? '') : `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`);\nconst plural = (n: number, word: string, many = `${word}s`) => `${n} ${n === 1 ? word : many}`;\nconst capital = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);\nconst lower = (s: string) => s.charAt(0).toLowerCase() + s.slice(1);\n\n/** \"boolean, default false\" -> { type: \"boolean\", def: \"false\" }. */\nfunction propShape(s: string | undefined): { type: string; def: string } | undefined {\n if (!s) return undefined;\n const m = /^(.*?), default (.*)$/.exec(s);\n return m ? { type: m[1]!, def: m[2]! } : { type: s, def: '' };\n}\n\n// ---------------------------------------------------------------------------------------------\n// Structure changes: a layer added, removed or moved in a variant. The scan writes them as rows\n// `New layer \"Icon\" (Size=sm, Variant=primary)` with the kind and the place as values:\n// added `instance Icon/Pencil, after \"Label\"`, removed the same as `before`, moved `after \"A\"` -> `before \"B\"`.\n\nconst VARIANT_FIRST = ['variant', 'tone', 'intent', 'appearance', 'kind', 'type', 'style'];\n\n/** \"Size=sm, State=Default, Variant=primary\" -> \"primary sm\": the values a designer says, default states left out. */\nexport function shortVariant(key: string): string {\n const pairs = key.split(', ').map((p) => {\n const at = p.indexOf('=');\n return at < 0 ? { k: '', v: p.trim() } : { k: p.slice(0, at).trim(), v: p.slice(at + 1).trim() };\n });\n const kept = pairs.filter((p) => p.v && !/^default$/i.test(p.v));\n if (!kept.length) return key;\n const rank = (k: string) => {\n const i = VARIANT_FIRST.indexOf(k.toLowerCase());\n return i < 0 ? VARIANT_FIRST.length : i;\n };\n return kept\n .map((p, i) => ({ ...p, i }))\n .sort((a, b) => rank(a.k) - rank(b.k) || a.i - b.i)\n .map((p) => p.v)\n .join(' ');\n}\n\n/** \"Size=sm, Variant=primary; Size=md, Variant=primary\" -> \"primary sm and primary md\"; empty -> \"every variant\". */\nexport const shortVariants = (list: string | undefined) => (list ? andList(list.split('; ').map(shortVariant)) : 'every variant');\n\nexport interface StructureRow {\n op: 'added' | 'removed' | 'moved';\n name: string;\n /** \"in primary sm\" or \"in every variant\". */\n where: string;\n /** Layer type in words (\"instance\", \"text\", \"frame\"), when known. */\n type?: string | undefined;\n /** Main component of an instance (\"Icon/Pencil\"). */\n main?: string | undefined;\n /** Where it sits now (added, moved) or sat (removed): `after \"Label\"`, `before \"Label\"`, `alone`. */\n at?: string | undefined;\n /** Moved: where it sat before. */\n from?: string | undefined;\n}\n\n/** A structure row read back, or undefined when the field is not one. */\nexport function parseStructureChange(c: RequestChange): StructureRow | undefined {\n const m = /^(New|Removed|Moved) layer \"(.*)\"(?: \\((.*)\\))?$/.exec(c.field);\n if (!m) return undefined;\n const op = m[1] === 'New' ? 'added' : m[1] === 'Removed' ? 'removed' : 'moved';\n const where = `in ${shortVariants(m[3])}`;\n if (op === 'moved') return { op, name: m[2]!, where, at: c.after, from: c.before };\n const shape = (op === 'added' ? c.after : c.before) ?? '';\n const sm = /^(\\S+)(?: (.*?))?, ((?:after|before) \".*\"|alone)$/.exec(shape);\n return { op, name: m[2]!, where, ...(sm ? { type: sm[1], ...(sm[2] ? { main: sm[2] } : {}), at: sm[3] } : {}) };\n}\n\nfunction structurePhrase(r: StructureRow): string {\n const type = r.type ? `${r.type} ` : '';\n const main = r.main ? ` (${r.main})` : '';\n const at = r.at && r.at !== 'alone' ? ` ${r.at}` : '';\n if (r.op === 'added') return `New ${type}layer \"${r.name}\"${main}${at} ${r.where}`;\n if (r.op === 'removed') return `Removed ${type}layer \"${r.name}\"${main}${at} ${r.where}`;\n return `Moved layer \"${r.name}\" ${r.at ?? ''}${r.from ? ` (was ${r.from})` : ''} ${r.where}`.replace(/\\s+/g, ' ');\n}\n\nconst bare = (at: string | undefined) => (at ?? '').replace(/\"/g, '');\n\n/** Title and summary for the first change of a detected component change. */\nfunction firstChange(component: string, kind: RequestKind, c: RequestChange | undefined, all: RequestChange[]): DraftText {\n switch (kind) {\n case 'new-component': {\n const axes = all.filter((x) => x.field.startsWith('Variant '));\n const props = all.filter((x) => x.field.startsWith('Prop '));\n const parts = [axes.length ? plural(axes.length, 'variant axis', 'variant axes') : '', props.length ? plural(props.length, 'prop') : ''].filter(Boolean);\n return {\n title: `Add the ${component} component`,\n summary: `${component} is not in code yet.${parts.length ? ` The Figma component has ${andList(parts)}.` : ''}`,\n };\n }\n case 'new-variant': {\n if (!c) return { title: `Update the ${component} variants`, summary: `The variants of ${component} changed in Figma.` };\n const axis = c.field.replace(/^Variant /, '');\n const before = values(c.before);\n const after = values(c.after);\n const added = after.filter((x) => !before.includes(x));\n const removed = before.filter((x) => !after.includes(x));\n const word = axis.toLowerCase();\n if (!before.length) return { title: `Add a ${axis} variant axis`, summary: `${component} gets a new variant axis, ${axis}, with ${after.length === 1 ? 'the value' : 'the values'} ${andList(after)}.` };\n if (!after.length) return { title: `Remove the ${axis} variant axis`, summary: `${component} no longer has the ${axis} variant axis (${andList(before)}).` };\n if (added.length === 1 && !removed.length) return { title: `Add ${article(added[0]!)} ${added[0]} ${word}`, summary: `${component} gets a new ${axis} value, ${added[0]}.` };\n if (added.length && !removed.length) return { title: `Add ${andList(added)} to ${axis}`, summary: `${component} gets ${plural(added.length, `new ${axis} value`)}: ${andList(added)}.` };\n if (removed.length === 1 && !added.length) return { title: `Remove the ${removed[0]} ${word}`, summary: `${component} no longer has the ${axis} value ${removed[0]}.` };\n if (removed.length && !added.length) return { title: `Remove ${andList(removed)} from ${axis}`, summary: `${component} no longer has the ${axis} values ${andList(removed)}.` };\n return { title: `Change the ${axis} values`, summary: `${axis} on ${component} goes from ${andList(before)} to ${andList(after)}.` };\n }\n case 'prop-change': {\n if (!c) return { title: `Change a ${component} prop`, summary: `A prop of ${component} changed in Figma.` };\n const name = c.field.replace(/^Prop /, '');\n const b = propShape(c.before);\n const a = propShape(c.after);\n if (!b && a) return { title: `Add the ${name} prop`, summary: `${component} gets a new ${a.type} prop, ${name}${a.def ? `, default ${a.def}` : ''}.` };\n if (b && !a) return { title: `Remove the ${name} prop`, summary: `${component} no longer has the ${name} prop.` };\n if (b && a && b.type === a.type && b.def !== a.def) return { title: `Change the ${name} default to ${a.def || 'empty'}`, summary: `The default of ${name} on ${component} goes from ${b.def || 'empty'} to ${a.def || 'empty'}.` };\n return { title: `Change the ${name} prop`, summary: `${name} on ${component} goes from ${c.before ?? 'none'} to ${c.after ?? 'none'}.` };\n }\n case 'token-binding': {\n if (!c) return { title: 'Use another token', summary: `A part of ${component} uses another token in Figma.` };\n const m = /^(.*?)(?: \\((.*)\\))?$/.exec(c.field)!;\n const part = lower(m[1]!);\n const where = m[2] ? ` in ${m[2]}` : '';\n const after = c.after && c.after !== 'none' ? c.after : '';\n const before = c.before && c.before !== 'none' ? c.before : '';\n if (!after) return { title: `Unbind the ${part}`, summary: `The ${part} of ${component}${where} no longer uses ${before || 'a token'}.` };\n return {\n title: `Use ${after} for the ${part}`,\n summary: `The ${part} of ${component}${where} ${before ? `moves from ${before} to ${after}` : `now uses ${after}`}.`,\n };\n }\n case 'structure': {\n const r = c ? parseStructureChange(c) : undefined;\n if (!r) return { title: 'Change the layers to match Figma', summary: `The layers of ${component} changed in Figma.` };\n if (r.op === 'added') {\n const at = r.at && r.at !== 'alone' ? ` ${bare(r.at)}` : '';\n return { title: `Add a layer${at}`, summary: `${component} gets ${article(r.type ?? 'layer')} ${r.type ?? 'layer'}${r.type ? ' layer' : ''}, ${r.name}${r.main ? ` (${r.main})` : ''}${at} ${r.where}.` };\n }\n if (r.op === 'removed') return { title: `Remove the ${r.name} layer`, summary: `${component} no longer has the ${r.name} layer ${r.where}.` };\n return { title: `Move the ${r.name} layer`, summary: `The ${r.name} layer of ${component} moves ${bare(r.at) || 'elsewhere'}${r.from ? ` (it was ${bare(r.from)})` : ''} ${r.where}.` };\n }\n case 'visual':\n return {\n title: 'Update the look to match Figma',\n summary: `${component} looks different in Figma${c?.field.startsWith('Look of ') && c.field !== 'Look of every variant' ? ` in ${c.field.slice(8)}` : ''}, and no variable edit explains it.`,\n };\n default:\n return { title: '', summary: '' };\n }\n}\n\n/**\n * The deterministic title and summary of a component change request, from the changes a scan detected. Manual\n * requests with no detected change (a bug, an idea) get empty text: there is nothing factual to say yet.\n */\nexport function draftRequestText(component: string, kind: RequestKind, changes: RequestChange[]): DraftText {\n const name = component.trim() || 'the component';\n if (!changes.length && kind !== 'new-component') return { title: '', summary: '' };\n const d = firstChange(name, kind, changes[0], changes);\n const rest = kind === 'new-component' ? 0 : changes.length - 1;\n const summary = rest > 0 ? `${d.summary} ${capital(plural(rest, 'other change'))} ${rest === 1 ? 'is' : 'are'} listed below.` : d.summary;\n return { title: cleanDraftText(d.title), summary: cleanDraftText(summary) };\n}\n\n// ---------------------------------------------------------------------------------------------\n// Change lines: one sentence per detected component change, the main line of its row in the plugin and the first line\n// of its request. Claude rewrites it from the before and after images; this is the deterministic default.\n\n/** A change line is one sentence of at most this many characters, with no trailing period. */\nexport const DRAFT_LINE_MAX = 120;\n\n/** Shortens to `max` characters at a word boundary, without a trailing period. */\nfunction clipText(text: string, max: number): string {\n const t = text.replace(/\\s+/g, ' ').trim().replace(/\\.$/, '');\n if (t.length <= max) return t;\n const cut = t.slice(0, max + 1);\n const at = cut.lastIndexOf(' ');\n return (at > max * 0.5 ? cut.slice(0, at) : t.slice(0, max)).replace(/[\\s,;:(]+$/, '');\n}\n\n/** A change line kept to the contract: one line, no em dash, at most 120 characters, no trailing period. */\nexport function sanitizeDraftLine(raw: unknown): string {\n if (typeof raw !== 'string') return '';\n return capital(clipText(cleanDraftText(raw.replace(/[\\r\\n]+/g, ' ')), DRAFT_LINE_MAX));\n}\n\n/** One change row as a short phrase a developer reads (\"Fill uses color.x instead of color.y in Size=sm\"). */\nfunction changePhrase(c: RequestChange): string {\n let m: RegExpExecArray | null;\n if ((m = /^Variant (.+)$/.exec(c.field))) {\n const axis = m[1]!;\n const before = values(c.before);\n const after = values(c.after);\n if (!before.length) return `New ${axis} variant axis: ${after.join(', ')}`;\n if (!after.length) return `${axis} variant axis removed (${before.join(', ')})`;\n const added = after.filter((x) => !before.includes(x));\n const removed = before.filter((x) => !after.includes(x));\n const parts = [added.length ? `${andList(added)} added to ${axis}` : '', removed.length ? `${andList(removed)} removed from ${axis}` : ''].filter(Boolean);\n return parts.join('; ') || `${axis} values reordered: ${after.join(', ')}`;\n }\n if ((m = /^Prop (.+)$/.exec(c.field))) {\n const name = m[1]!;\n const b = propShape(c.before);\n const a = propShape(c.after);\n if (!b && a) return `New ${a.type} prop ${name}${a.def ? `, default ${a.def}` : ''}`;\n if (b && !a) return `${name} prop removed`;\n if (b && a && b.type === a.type) return `${name} default goes from ${b.def || 'empty'} to ${a.def || 'empty'}`;\n return `${name} prop goes from ${c.before ?? 'none'} to ${c.after ?? 'none'}`;\n }\n if ((m = /^Swapped instance(?: \\((.*)\\))?$/.exec(c.field))) return `Shows ${c.after ?? 'another instance'} instead of ${c.before ?? 'the coded one'} ${m[1] ? `in ${m[1]}` : 'in every variant'}`;\n if ((m = /^Look of (.+)$/.exec(c.field))) return `Looks different in ${m[1]}; no variable explains it`;\n const layer = parseStructureChange(c);\n if (layer) return structurePhrase(layer);\n // A token binding: \"Fill\" or \"Fill (Size=sm, Tone=primary)\".\n m = /^(.*?)(?: \\((.*)\\))?$/.exec(c.field)!;\n const where = m[2] ? ` in ${m[2]}` : '';\n const before = c.before && c.before !== 'none' ? c.before : '';\n const after = c.after && c.after !== 'none' ? c.after : '';\n if (!after) return `${m[1]} no longer uses ${before || 'a token'}${where}`;\n if (!before) return `${m[1]} now uses ${after}${where}`;\n return `${m[1]} uses ${after} instead of ${before}${where}`;\n}\n\n/**\n * The deterministic change line of a detected component change: what changed, in one sentence, from the diff only.\n * The first change is spelled out, the others counted (\"and 2 more\"). Empty when nothing was detected.\n */\nexport function draftChangeLine(kind: RequestKind, changes: RequestChange[]): string {\n if (kind === 'new-component') {\n const axes = changes.filter((x) => x.field.startsWith('Variant ')).length;\n const props = changes.filter((x) => x.field.startsWith('Prop ')).length;\n const parts = [axes ? plural(axes, 'variant axis', 'variant axes') : '', props ? plural(props, 'prop') : ''].filter(Boolean);\n return `New component${parts.length ? ` with ${andList(parts)}` : ''}, not in code yet`;\n }\n if (!changes.length) return '';\n const first = changePhrase(changes[0]!);\n const rest = changes.length - 1;\n const tail = rest ? ` (and ${rest} more)` : '';\n return capital(clipText(cleanDraftText(first), DRAFT_LINE_MAX - tail.length)) + tail;\n}\n\n// ---------------------------------------------------------------------------------------------\n// Push description (variables pull request and the requests sent with it)\n\nconst tokenOf = (e: DiffEntry) => e.figma ?? e.head ?? e.base;\nconst pathOf = (e: DiffEntry) => tokenOf(e)?.path ?? e.path;\n\n/** One line per variable edit for a change table: the token, its value before, its value in Figma. */\nexport function pushChangeRows(entries: DiffEntry[]): RequestChange[] {\n return entries.map((e) => {\n const before = e.head ?? e.base;\n const after = e.figma;\n const show = (t: typeof before) => {\n if (!t) return undefined;\n const modes = Object.keys(t.values);\n if (modes.length <= 1) return formatValue(t.type, t.values[modes[0] ?? '']);\n return modes.map((m) => `${modeDisplayName(m)} ${formatValue(t.type, t.values[m])}`).join('; ');\n };\n const renamed = e.local?.kind === 'renamed' && before && after && before.path !== after.path;\n return { field: renamed ? `${before.path} -> ${after.path}` : pathOf(e), before: show(before), after: show(after) };\n });\n}\n\n/** \"a, b and c\", or \"7 tokens, including a and b\" when the list is long. */\nfunction names(paths: string[]): string {\n if (paths.length <= 3) return andList(paths);\n return `${paths.length} tokens, including ${andList(paths.slice(0, 2))}`;\n}\n\n/** Modes a changed token's value moved in (\"Light and Dark\"), for a single changed token. */\nfunction valueModes(e: DiffEntry): string[] {\n return (e.local?.fields ?? []).filter((f) => f.field === 'value' && f.mode && f.mode !== 'value').map((f) => modeDisplayName(f.mode!));\n}\n\nexport interface PushDraftComponent {\n component: string;\n kind: RequestKind;\n}\n\n/**\n * The deterministic Push description: what the checked variable edits do and which components get a request.\n * 1 or 2 sentences, never a reason (only the designer knows why). Empty when nothing is checked.\n */\nexport function draftPushDescription(entries: DiffEntry[], components: PushDraftComponent[] = []): string {\n const by: Record<'changed' | 'added' | 'renamed' | 'removed', DiffEntry[]> = { changed: [], added: [], renamed: [], removed: [] };\n for (const e of entries) by[e.local?.kind ?? 'changed'].push(e);\n const clauses: string[] = [];\n if (by.changed.length) {\n const only = by.changed.length === 1 ? by.changed[0]! : undefined;\n const fields = new Set((only?.local?.fields ?? []).map((f) => f.field));\n const modes = only ? valueModes(only) : [];\n if (only && fields.size === 1 && fields.has('description')) clauses.push(`updates the description of ${pathOf(only)}`);\n else if (only && modes.length) clauses.push(`changes ${pathOf(only)} in ${andList(modes)}`);\n else clauses.push(`changes ${names(by.changed.map(pathOf))}`);\n }\n if (by.added.length) clauses.push(`adds ${names(by.added.map(pathOf))}`);\n if (by.renamed.length) {\n const r = by.renamed[0]!;\n const from = (r.head ?? r.base)?.path;\n clauses.push(by.renamed.length === 1 && from && from !== pathOf(r) ? `renames ${from} to ${pathOf(r)}` : `renames ${names(by.renamed.map(pathOf))}`);\n }\n if (by.removed.length) clauses.push(`removes ${names(by.removed.map(pathOf))}`);\n const sentences: string[] = [];\n if (clauses.length) sentences.push(`${capital(andList(clauses))}.`);\n const fresh = components.filter((c) => c.kind === 'new-component').map((c) => c.component);\n const changed = [...new Set(components.filter((c) => c.kind !== 'new-component').map((c) => c.component))];\n const comp: string[] = [];\n if (changed.length) comp.push(`${changed.length === 1 ? 'a change' : 'changes'} to ${andList(changed)}`);\n if (fresh.length) comp.push(`the new ${andList(fresh)} component${fresh.length === 1 ? '' : 's'}`);\n if (comp.length) sentences.push(`Requests ${andList(comp)}.`);\n return cleanDraftText(sentences.join(' '));\n}\n","// Component docs drafted with Claude: the task (which sections, or a selected passage), the prompt, the answer\n// parsing and sanitizing, the merge into a docs.json, and the Messages API request. Shared by the docs-draft GitHub\n// Action (scripts/docs-draft.mjs), the in-place drafting of the Library page (apps/docs-site docs-ai) and the draft\n// exchange (the user's own Claude through the Bridge MCP server), so an answer is cleaned the same way everywhere.\n// Pure: no DOM, no Node-only API. The callers do the fetch.\n\nimport { cleanDraftText } from './change-drafts';\nimport {\n type ComponentDocsJson,\n type DocsConventions,\n type DocsExampleNode,\n type DocsGuidance,\n type DocsPrefill,\n PROSE_KEYS,\n type ProseKey,\n docsPrompt,\n markClaudeDraft,\n} from './docs-draft';\n\nexport const DOCS_DRAFT_MODEL = 'claude-sonnet-5-5';\nexport const ANTHROPIC_MESSAGES_URL = 'https://api.anthropic.com/v1/messages';\n\n/** How a selected passage is rewritten. */\nexport type DocsSelectionMode = 'clearer' | 'shorter' | 'voice';\nexport const DOCS_SELECTION_MODES: Record<DocsSelectionMode, string> = {\n clearer: 'Make it clearer: plain words, one idea per sentence, the most useful fact first.',\n shorter: 'Make it shorter: keep every fact, drop filler, aim for half the words or fewer.',\n voice: 'Put it in the Bridge voice: sentence case, verbs first, calm and precise, no marketing words, no em dash.',\n};\nexport const isDocsSelectionMode = (m: unknown): m is DocsSelectionMode => typeof m === 'string' && m in DOCS_SELECTION_MODES;\nexport const isProseKey = (k: unknown): k is ProseKey => typeof k === 'string' && (PROSE_KEYS as readonly string[]).includes(k);\n\n/**\n * One drafting job on a component's docs. \"sections\": write these prose sections (rewrite: even when they hold text;\n * check: written sections older than the code, returned only when no longer true for it, so an absent one is still\n * accurate). \"selection\": rewrite one passage of a section, nothing else.\n */\nexport type DocsDraftTask =\n | { kind: 'sections'; keys: ProseKey[]; rewrite?: boolean | undefined; check?: ProseKey[] | undefined }\n | { kind: 'selection'; key: ProseKey; text: string; mode: DocsSelectionMode };\n\n/** Problems in a task, as sentences. Empty when valid. */\nexport function validateDocsTask(x: unknown): string[] {\n if (!x || typeof x !== 'object') return ['The docs task is missing.'];\n const t = x as Partial<Record<string, unknown>>;\n if (t.kind === 'sections') {\n const keys = t.keys;\n if (!Array.isArray(keys) || !keys.length || !keys.every(isProseKey)) return [`The docs task lists no sections: use ${PROSE_KEYS.join(', ')}.`];\n if (t.check !== undefined && (!Array.isArray(t.check) || !t.check.every(isProseKey))) return ['check must list prose sections.'];\n return [];\n }\n if (t.kind === 'selection') {\n const out: string[] = [];\n if (!isProseKey(t.key)) out.push(`The selection needs a section: ${PROSE_KEYS.join(', ')}.`);\n if (typeof t.text !== 'string' || !t.text.trim()) out.push('The selection has no text.');\n if (!isDocsSelectionMode(t.mode)) out.push('The selection mode must be clearer, shorter or voice.');\n return out;\n }\n return ['The docs task kind must be \"sections\" or \"selection\".'];\n}\n\n/** The keys a task writes. */\nexport const docsTaskKeys = (t: DocsDraftTask): ProseKey[] => (t.kind === 'sections' ? t.keys : [t.key]);\n\n/** The prompt to rewrite a selected passage of a section: the facts and the conventions, the passage, one rule. */\nexport function docsSelectionPrompt(prefill: DocsPrefill, conventions: DocsConventions, sel: { key: ProseKey; text: string; mode: DocsSelectionMode }): string {\n const base = docsPrompt(prefill, conventions, { keys: [sel.key] });\n // Reuse the facts and conventions of the sections prompt, with the selection task and contract on top.\n const facts = base.slice(base.indexOf('Facts computed from the code:'));\n return [\n `Rewrite one passage of the \"${sel.key}\" section of ${prefill.component}.docs.json for the Bridge design system.`,\n DOCS_SELECTION_MODES[sel.mode],\n '',\n 'Rules:',\n '- Keep its meaning and every fact that the code supports. Never add props, variants, keyboard behavior or tokens that are not in the facts or the source below.',\n '- Bridge voice: sentence case, plain words, verbs first, no em dashes, no marketing words, no Markdown.',\n '- Rewrite only the passage: it is pasted back in place of the selection, inside the rest of the section.',\n '- Answer with one JSON object, nothing else: { \"replacement\": \"the rewritten passage\" }.',\n '',\n `<passage>\\n${sel.text.trim()}\\n</passage>`,\n '',\n facts,\n ].join('\\n');\n}\n\n/** The prompt of a task: docsPrompt for sections (only those keys), docsSelectionPrompt for a selection. */\nexport function docsTaskPrompt(prefill: DocsPrefill, conventions: DocsConventions, task: DocsDraftTask): string {\n if (task.kind === 'selection') return docsSelectionPrompt(prefill, conventions, task);\n return docsPrompt(prefill, conventions, { keys: task.keys, ...(task.rewrite ? { rewrite: true } : {}), ...(task.check?.length ? { check: task.check } : {}) });\n}\n\n// ---------------------------------------------------------------------------------------------\n// Answers: parse and sanitize\n\n/** The first JSON object in a model reply (plain, or inside a ```json fence). Throws when there is none. */\nexport function parseDocsReply(text: string): Record<string, unknown> {\n const fenced = /```(?:json)?\\s*([\\s\\S]*?)```/i.exec(text);\n const body = fenced ? fenced[1]! : text;\n const start = body.indexOf('{');\n const end = body.lastIndexOf('}');\n if (start < 0 || end <= start) throw new Error('The reply holds no JSON object.');\n const json = JSON.parse(body.slice(start, end + 1)) as unknown;\n if (!json || typeof json !== 'object' || Array.isArray(json)) throw new Error('The reply is not a docs.json object.');\n return json as Record<string, unknown>;\n}\n\n/** One line of docs prose: em dashes out, whitespace folded, trimmed. */\nexport const cleanDocsText = (s: string): string => cleanDraftText(s.replace(/[\\r\\n]+/g, ' '));\n\nconst isExample = (x: unknown): x is DocsExampleNode => {\n if (typeof x === 'string') return true;\n if (!x || typeof x !== 'object' || Array.isArray(x)) return false;\n const n = x as { c?: unknown; p?: unknown; children?: unknown };\n if (typeof n.c !== 'string' || !n.c) return false;\n if (n.p !== undefined && (!n.p || typeof n.p !== 'object' || Array.isArray(n.p))) return false;\n return n.children === undefined || (Array.isArray(n.children) && n.children.every(isExample));\n};\n\nconst textList = (x: unknown): string[] | undefined => {\n if (typeof x === 'string') x = [x];\n if (!Array.isArray(x)) return undefined;\n const out = x.filter((s): s is string => typeof s === 'string').map(cleanDocsText).filter(Boolean);\n return out.length ? out : undefined;\n};\n\nconst guidanceList = (x: unknown, examples: boolean): DocsGuidance[] | undefined => {\n if (!Array.isArray(x)) return undefined;\n const out: DocsGuidance[] = [];\n for (const g of x as unknown[]) {\n if (!g || typeof g !== 'object') continue;\n const r = g as { title?: unknown; text?: unknown; example?: unknown };\n const title = typeof r.title === 'string' ? cleanDocsText(r.title) : '';\n const text = typeof r.text === 'string' ? cleanDocsText(r.text) : '';\n if (!title || !text) continue;\n out.push({ title, text, ...(examples && r.example !== undefined && isExample(r.example) ? { example: r.example } : {}) });\n }\n return out.length ? out : undefined;\n};\n\nexport type DocsSections = Partial<Pick<ComponentDocsJson, ProseKey>>;\n\n/**\n * The prose sections of an answer, kept to the docs.json shapes: only `keys`, summary one cleaned paragraph, lists of\n * non-empty cleaned strings, dos and donts as {title, text} (an example only when `examples` and well formed). Em\n * dashes removed everywhere. Sections that come back empty or in the wrong shape are left out.\n */\nexport function sanitizeDocsSections(raw: unknown, keys: readonly ProseKey[] = PROSE_KEYS, opts: { examples?: boolean } = {}): DocsSections {\n const out: DocsSections = {};\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;\n const r = raw as Record<string, unknown>;\n for (const k of keys) {\n const v = r[k];\n if (k === 'summary') {\n const s = typeof v === 'string' ? cleanDocsText(v) : '';\n if (s) out.summary = s;\n } else if (k === 'dos' || k === 'donts') {\n const g = guidanceList(v, opts.examples ?? false);\n if (g) out[k] = g;\n } else {\n const l = textList(v);\n if (l) out[k] = l;\n }\n }\n return out;\n}\n\n/** A rewritten passage: one cleaned paragraph without wrapping quotes, or '' when there is none. */\nexport function sanitizeDocsReplacement(raw: unknown): string {\n if (typeof raw !== 'string') return '';\n return cleanDocsText(raw.trim().replace(/^[\"'“]+|[\"'”]+$/g, ''));\n}\n\n/**\n * A task's answer. Sections tasks: `sections` drafted or fixed, and `checked`, the checked sections Claude verified and\n * left unchanged (still accurate). Selection: `replacement` only.\n */\nexport type DocsTaskAnswer = { sections: DocsSections; checked: ProseKey[]; replacement?: undefined } | { sections: DocsSections; checked?: undefined; replacement: string };\n\n/**\n * A task's answer from Claude's reply text. Sections: the requested keys, sanitized; throws when none came back.\n * Selection: `replacement` only (sections stay empty); a reply that is plain text counts as the passage.\n */\nexport function parseDocsTaskAnswer(task: DocsDraftTask, text: string): DocsTaskAnswer {\n if (task.kind === 'selection') {\n let raw: unknown = text;\n try {\n const json = parseDocsReply(text);\n raw = json.replacement ?? json.text ?? json[task.key];\n } catch {\n raw = text.replace(/```[a-z]*\\s*|```/gi, '');\n }\n const replacement = sanitizeDocsReplacement(raw);\n if (!replacement) throw new Error('Claude sent no rewritten passage. Try again.');\n return { sections: {}, replacement };\n }\n return docsSectionsAnswer(task, parseDocsReply(text));\n}\n\n/**\n * Sections and checked of a sections task from an answer object: absent checked keys are still accurate. Throws only\n * when the task checks nothing and none of its keys came back.\n */\nexport function docsSectionsAnswer(task: Extract<DocsDraftTask, { kind: 'sections' }>, raw: unknown): { sections: DocsSections; checked: ProseKey[] } {\n const check = (task.check ?? []).filter((k) => task.keys.includes(k));\n const sections = check.length ? sanitizeDocsSections(raw, task.keys) : docsSectionsResult(task, raw);\n return { sections, checked: check.filter((k) => sections[k] === undefined) };\n}\n\n/** The sections of a task from an answer object (API reply or the exchange). Throws when none of the keys came back. */\nexport function docsSectionsResult(task: Extract<DocsDraftTask, { kind: 'sections' }>, raw: unknown): DocsSections {\n const sections = sanitizeDocsSections(raw, task.keys);\n if (!Object.keys(sections).length) throw new Error(`Claude's answer holds none of the sections asked for (${task.keys.join(', ')}). Try again.`);\n return sections;\n}\n\n/**\n * Drafted sections applied to a docs.json, marked for review: the sections replace the ones there, the rest stays as\n * is (anatomy and preview are code-decided and never come from a draft), and draftedSections lists what waits.\n */\nexport function applyDocsSections<T extends Partial<ComponentDocsJson>>(docs: T, sections: DocsSections): T {\n const keys = PROSE_KEYS.filter((k) => sections[k] !== undefined);\n if (!keys.length) return docs;\n return markClaudeDraft({ ...docs, ...sections }, keys);\n}\n\n/**\n * The docs-draft Action's merge: Claude's prose on top of the pre-fill draft, only where the pre-fill is empty (a\n * written section is never overwritten), anatomy kept from the code, the drafted sections marked for review.\n */\nexport function mergeDocsDraft(prefillDraft: Partial<ComponentDocsJson>, reply: Record<string, unknown>): Partial<ComponentDocsJson> {\n const empty = PROSE_KEYS.filter((k) => {\n const v = prefillDraft[k];\n return v === undefined || (typeof v === 'string' ? !v.trim() : Array.isArray(v) && !v.length);\n });\n const sections = sanitizeDocsSections(reply, empty, { examples: true });\n const merged: Partial<ComponentDocsJson> = { ...prefillDraft, ...sections };\n if (reply.preview && !prefillDraft.preview && isExample(reply.preview)) merged.preview = reply.preview;\n merged.anatomy = prefillDraft.anatomy;\n const drafted = PROSE_KEYS.filter((k) => sections[k] !== undefined);\n return markClaudeDraft(merged, drafted.length && drafted.length < PROSE_KEYS.length ? drafted : undefined);\n}\n\n// ---------------------------------------------------------------------------------------------\n// The Messages API call (raw HTTP: no SDK dependency for one call)\n\nexport interface AnthropicHttpRequest {\n url: string;\n init: { method: 'POST'; headers: Record<string, string>; body: string };\n}\n\nexport interface AnthropicRequestInput {\n apiKey: string;\n prompt: string;\n model?: string | undefined;\n system?: string | undefined;\n maxTokens?: number | undefined;\n /** A direct call from a browser page (the user's own key): adds the header the API asks for. */\n browser?: boolean | undefined;\n /** Re-run a declined request on a fallback model inside the same call (server-side fallback beta). */\n fallback?: boolean | undefined;\n}\n\n/** The Messages API request for one prompt. The key goes in x-api-key, to api.anthropic.com only. */\nexport function anthropicRequest(input: AnthropicRequestInput): AnthropicHttpRequest {\n const headers: Record<string, string> = { 'x-api-key': input.apiKey, 'anthropic-version': '2023-06-01', 'content-type': 'application/json' };\n if (input.fallback) headers['anthropic-beta'] = 'server-side-fallback-2026-07-01';\n if (input.browser) headers['anthropic-dangerous-direct-browser-access'] = 'true';\n const body: Record<string, unknown> = {\n model: input.model || DOCS_DRAFT_MODEL,\n max_tokens: input.maxTokens ?? 16000,\n ...(input.fallback ? { fallbacks: 'default' } : {}),\n ...(input.system ? { system: input.system } : {}),\n messages: [{ role: 'user', content: input.prompt }],\n };\n return { url: ANTHROPIC_MESSAGES_URL, init: { method: 'POST', headers, body: JSON.stringify(body) } };\n}\n\n/** The text of a Messages API reply. Throws when Claude declined or the reply was cut off. */\nexport function anthropicReplyText(msg: unknown): string {\n const m = (msg ?? {}) as { stop_reason?: string; content?: { type?: string; text?: unknown }[] };\n if (m.stop_reason === 'refusal') throw new Error('Claude declined to draft this one.');\n if (m.stop_reason === 'max_tokens') throw new Error('The reply was cut off (max_tokens).');\n return (m.content ?? [])\n .filter((b) => b?.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text as string)\n .join('');\n}\n","// Explorations: try experimental variables and components in a real product staging branch without touching main.\n// An exploration is a branch named `explore/<slug>` with an open DRAFT pull request labeled `exploration`. It holds\n// token edits and component work (requests filed with `exploration: explore/<slug>` are implemented there). Every\n// exploration gets the per-branch previews (bridge.config.json previews.apps) and a snapshot of the packages a product\n// staging branch installs (.github/workflows/preview-packages.yml). It is never merged as is: when the idea is\n// validated it is promoted to a normal pull request for review, otherwise it is closed. The CI check \"Exploration not\n// merged as is\" fails while the label is on, so an exploration cannot be merged by accident.\n//\n// Pure: branch naming, the draft pull request body, status and the promotion plan. Shared by Studio, the MCP server\n// and the CLI, so an exploration reads the same everywhere. GitHub calls live in explorations-github.ts.\n\nimport type { BridgeConfig } from './config';\nimport { slugify } from './pr-composer';\nimport { previewLinks, readPreviewComment, type PreviewApps } from './previews';\nimport { classifyRisk, type ChangedFile, type RiskTier } from './risk';\n\n/** Every exploration pull request carries this label while it is an exploration. */\nexport const EXPLORATION_LABEL = 'exploration';\n/** Exploration branches start with it. */\nexport const EXPLORATION_PREFIX = 'explore/';\n/** Where the note that starts an exploration branch lives. Promotion removes it, so main never gets it. */\nexport const EXPLORATION_NOTES_DIR = '.bridge/explorations';\n/** What Studio shows instead of a risk tier while the pull request is an exploration. */\nexport const EXPLORATION_TIER_LABEL = 'Exploration (not mergeable)';\n/** Name of the CI job that fails while the label is on. */\nexport const EXPLORATION_CHECK = 'Exploration not merged as is';\n\nexport type ExplorationUseCase = 'user-test' | 'stakeholder-demo' | 'ab-idea' | 'terminal' | 'other';\nexport type ExplorationStatus = 'active' | 'promoted' | 'closed';\n/** Where an exploration was started: Bridge Studio, the Figma plugin, the CLI or the MCP server (an AI agent). */\nexport type ExplorationSource = 'studio' | 'figma' | 'cli' | 'mcp';\n\nexport const EXPLORATION_USE_CASES: { value: ExplorationUseCase; label: string; hint: string }[] = [\n { value: 'user-test', label: 'Prototype for a user test', hint: 'A coded prototype on a product staging branch, with the real components and tokens.' },\n { value: 'stakeholder-demo', label: 'Stakeholder demo', hint: 'Show an idea on real screens before anyone commits to it.' },\n { value: 'ab-idea', label: 'A/B idea', hint: 'Ship a variant to a staging or experiment branch and compare it with what is live.' },\n { value: 'terminal', label: 'Exploring with Claude Code', hint: 'A designer works from the terminal with Claude and the Bridge MCP server on this branch, never on main.' },\n { value: 'other', label: 'Other', hint: 'Anything else worth trying before it becomes a change.' },\n];\n\nexport const EXPLORATION_STATUS_LABEL: Record<ExplorationStatus, string> = { active: 'Running', promoted: 'Promoted to review', closed: 'Closed' };\n\nexport interface Exploration {\n /** Display name, sentence case: \"Denser data tables\". */\n name: string;\n /** What the team wants to learn, in one or two sentences. */\n purpose: string;\n /** Branch slug: `explore/<slug>`. Derived from the name when missing. */\n slug?: string | undefined;\n useCase?: ExplorationUseCase | undefined;\n /** What is experimental, one line each: \"color.action.primary.bg\", \"Button: pill radius\". */\n experimental?: string[] | undefined;\n /** GitHub login of who started it, when known. */\n author?: string | undefined;\n /** ISO date it started. */\n startedAt?: string | undefined;\n /** Where it was started, so Studio says \"You\" only for what the viewer started there. */\n source?: ExplorationSource | undefined;\n /** The AI agent that started it (\"claude\"), when one did: the GitHub account alone cannot tell. */\n agent?: string | undefined;\n /** A Jira ticket key (\"DS-42\"), first in the pull request title so Jira's GitHub integration links it. */\n jira?: string | undefined;\n}\n\nconst MARK = 'bridge-exploration';\nconst SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n/** \"Denser data tables!\" -> \"denser-data-tables\". Up to 40 characters, cut at a word boundary. Empty when nothing is left. */\nexport function explorationSlug(name: string): string {\n const s = name.trim().replace(/^explore\\//i, '');\n if (!/[a-z0-9]/i.test(s)) return '';\n return slugify(s, 40);\n}\n\n/** `explore/<slug>` for a name, a slug or a branch name. */\nexport function explorationBranch(nameOrBranch: string): string {\n return `${EXPLORATION_PREFIX}${explorationSlug(nameOrBranch)}`;\n}\n\n/** True for `explore/<valid-slug>`. */\nexport function isExplorationBranch(ref: string | null | undefined): boolean {\n const r = (ref ?? '').replace(/^refs\\/heads\\//, '');\n return r.startsWith(EXPLORATION_PREFIX) && SLUG_RE.test(r.slice(EXPLORATION_PREFIX.length));\n}\n\n/** The slug of an exploration branch, or null. */\nexport function explorationSlugFromBranch(ref: string): string | null {\n return isExplorationBranch(ref) ? ref.replace(/^refs\\/heads\\//, '').slice(EXPLORATION_PREFIX.length) : null;\n}\n\n/** Path of the note that starts an exploration branch. */\nexport const explorationNotePath = (slug: string) => `${EXPLORATION_NOTES_DIR}/${slug}.md`;\n\n/** Problems with a new exploration, as sentences that say how to fix them. Empty when it can start. */\nexport function explorationProblems(e: Pick<Exploration, 'name' | 'purpose'> & { slug?: string | undefined }): string[] {\n const out: string[] = [];\n const name = e.name.trim();\n const slug = e.slug?.trim() || explorationSlug(name);\n if (!name) out.push('Name the exploration, for example \"Denser data tables\".');\n else if (name.length > 60) out.push('Keep the name under 60 characters: it becomes the branch name.');\n else if (slug.length < 2 || !SLUG_RE.test(slug)) out.push('Use letters or digits in the name: it becomes the branch explore/<name>.');\n if (!e.purpose.trim()) out.push('Say what you want to learn, in one sentence.');\n return out;\n}\n\nconst useCaseLabel = (u: ExplorationUseCase | undefined) => EXPLORATION_USE_CASES.find((x) => x.value === u)?.label;\n\n/** The note committed as the first commit of the branch (`.bridge/explorations/<slug>.md`). */\nexport function explorationNote(e: Exploration): string {\n const slug = e.slug || explorationSlug(e.name);\n const uc = useCaseLabel(e.useCase);\n return [\n `# Exploration: ${e.name.trim()}`,\n '',\n e.purpose.trim(),\n '',\n `- Branch: \\`${EXPLORATION_PREFIX}${slug}\\``,\n ...(uc ? [`- Use case: ${uc}`] : []),\n ...(e.startedAt ? [`- Started: ${e.startedAt.slice(0, 10)}${e.author ? ` by @${e.author}` : ''}`] : []),\n '',\n 'This file marks the branch as an exploration. It is never merged as is: promoting the pull request to review removes it.',\n '',\n ].join('\\n');\n}\n\nexport interface ExplorationPrContext {\n owner: string;\n repo: string;\n /** Unknown before the pull request exists: the install section then says where the command will appear. */\n pr?: number | undefined;\n packages: string[];\n apps: PreviewApps;\n /** Requests implemented on this exploration. */\n requests?: { number: number; title: string }[] | undefined;\n}\n\n/** Draft pull request title: \"Exploration: denser data tables\". */\nexport function explorationPrTitle(e: Pick<Exploration, 'name'>): string {\n const n = e.name.trim().replace(/\\.$/, '');\n return `Exploration: ${n.charAt(0).toLowerCase()}${n.slice(1)}`;\n}\n\n/**\n * The draft pull request body: purpose, what is experimental, how a product staging branch installs it, the\n * previews, and how to promote or close it. Markdown for people plus one hidden JSON block for tools.\n */\nexport function explorationPrBody(e: Exploration, ctx: ExplorationPrContext): string {\n const slug = e.slug || explorationSlug(e.name);\n const branch = `${EXPLORATION_PREFIX}${slug}`;\n const uc = useCaseLabel(e.useCase);\n const experimental = (e.experimental ?? []).map((x) => x.trim()).filter(Boolean);\n const lines = [\n `## Exploration: ${e.name.trim()}`,\n '',\n `> Not mergeable as is. This draft pull request is a sandbox on \\`${branch}\\`: promote it to a normal review when the idea is validated, or close it.`,\n '',\n `**Purpose.** ${e.purpose.trim()}`,\n ...(uc ? ['', `**Use case.** ${uc}`] : []),\n '',\n '### What is experimental',\n '',\n ...(experimental.length ? experimental.map((x) => `- ${x}`) : ['- Token edits and component work committed to this branch. Nothing here reaches main or production.']),\n ...(ctx.requests?.length ? ['', 'Requests implemented here:', ...ctx.requests.map((r) => `- #${r.number} ${r.title}`)] : []),\n '',\n '### Try it in a product staging branch',\n '',\n ];\n // No guessed command here: pkg.pr.new may not be set up. The sticky comment has the one the workflow published.\n lines.push(\n 'In the product repo, on a branch that deploys to staging (production keeps the released version), install the snapshot with the command in the \"Try this exploration in your product\" comment below. It appears a few minutes after each push and always matches the latest commit.',\n );\n lines.push('', '### Previews', '');\n const links = previewLinks(ctx.apps, { branch, ...(ctx.pr ? { pr: ctx.pr } : {}) });\n if (links.length) lines.push('| App | Preview |', '| --- | --- |', ...links.map((l) => `| ${l.label} | ${l.url} |`));\n else lines.push('Preview deploys are not set up: add `previews.apps` to `bridge.config.json` (docs/PREVIEWS.md).');\n lines.push(\n '',\n '### When it is done',\n '',\n `- **Promote:** in Bridge Studio (Changes, Explorations, Promote to review) or \\`bridge explore promote ${slug}\\`. Bridge marks the pull request ready for review, removes the \\`${EXPLORATION_LABEL}\\` label and the exploration note, and adds the tier labels. Then it goes through the usual review.`,\n '- **Close:** close this pull request. The branch stays for reference; the preview prerelease is removed.',\n '',\n `<!-- ${MARK} ${JSON.stringify({ name: e.name.trim(), purpose: e.purpose.trim(), slug, ...(e.useCase ? { useCase: e.useCase } : {}), ...(experimental.length ? { experimental } : {}), ...(e.author ? { author: e.author } : {}), ...(e.startedAt ? { startedAt: e.startedAt } : {}), ...(e.source ? { source: e.source } : {}), ...(e.agent ? { agent: e.agent } : {}) }).replace(/-->/g, '--\\\\u003e')} -->`,\n );\n return lines.join('\\n');\n}\n\n/** The exploration inside a pull request body, or undefined when it has no valid Bridge block. */\nexport function parseExplorationBody(body: string | null | undefined): Exploration | undefined {\n if (!body) return undefined;\n const m = new RegExp(`<!-- ${MARK} (\\\\{[\\\\s\\\\S]*?\\\\}) -->`).exec(body);\n if (!m) return undefined;\n try {\n const e = JSON.parse(m[1]!) as Exploration;\n return e && typeof e.name === 'string' && typeof e.purpose === 'string' ? e : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport interface ExplorationPullLike {\n state: string;\n merged?: boolean | undefined;\n merged_at?: string | null | undefined;\n labels: (string | { name?: string })[];\n headRef?: string | undefined;\n body?: string | null | undefined;\n}\n\nconst labelNames = (labels: ExplorationPullLike['labels']) => labels.map((l) => (typeof l === 'string' ? l : (l.name ?? '')));\n\n/** True for a pull request that is or was an exploration: an `explore/*` branch, the label, or the Bridge block. */\nexport function isExplorationPull(p: ExplorationPullLike): boolean {\n return isExplorationBranch(p.headRef) || labelNames(p.labels).includes(EXPLORATION_LABEL) || Boolean(parseExplorationBody(p.body));\n}\n\n/**\n * Where an exploration stands: closed without merging = closed; open with the `exploration` label = active\n * (running); otherwise promoted (the label was removed, so it is a normal pull request now, open or merged).\n */\nexport function explorationStatus(p: ExplorationPullLike): ExplorationStatus {\n const merged = Boolean(p.merged || p.merged_at || p.state === 'merged');\n if (p.state !== 'open' && !merged) return 'closed';\n if (p.state === 'open' && labelNames(p.labels).includes(EXPLORATION_LABEL)) return 'active';\n return 'promoted';\n}\n\n/** True while the label is on: the pull request must not merge (the CI check fails, Studio blocks the merge). */\nexport const isActiveExploration = (labels: ExplorationPullLike['labels']) => labelNames(labels).includes(EXPLORATION_LABEL);\n\nexport interface PromotionPlan {\n tier: RiskTier;\n reasons: string[];\n /** Labels to remove (the exploration label). */\n removeLabels: string[];\n /** Tier labels from the shared classifier. */\n addLabels: string[];\n /** Files to delete on the branch before review: the exploration note. */\n removeFiles: string[];\n /** The pull request body for review. */\n body: string;\n /** Title without the \"Exploration:\" prefix. */\n title: string;\n markReady: true;\n}\n\n/**\n * What promoting an exploration does: the tier from the files it changes (the shared classifier, the exploration\n * note left out since promotion deletes it), tier labels, the exploration label removed, a review body that keeps\n * the purpose and closes the requests implemented on it, and the draft marked ready for review.\n */\nexport function promotionPlan(input: {\n title: string;\n body: string | null | undefined;\n labels: ExplorationPullLike['labels'];\n files: ChangedFile[];\n config?: BridgeConfig | undefined;\n /** Request issues implemented on this exploration: the review body closes them. */\n requests?: number[] | undefined;\n date?: Date | undefined;\n}): PromotionPlan {\n const exploration = parseExplorationBody(input.body);\n // A Jira key first in the title (\"DS-42 Exploration: pill buttons\") stays first after promotion.\n const jira = /^([A-Z][A-Z0-9_]*-\\d+)\\s+/.exec(input.title)?.[1] ?? null;\n const title = jira ? input.title.slice(jira.length).trim() : input.title;\n const removeFiles = input.files.filter((f) => f.path.startsWith(`${EXPLORATION_NOTES_DIR}/`) && f.status !== 'removed').map((f) => f.path);\n const files = input.files.filter((f) => !f.path.startsWith(`${EXPLORATION_NOTES_DIR}/`));\n const risk = classifyRisk({ files, ...(input.config ? { config: input.config } : {}) });\n const tokens = files.some((f) => f.path.endsWith('.tokens.json'));\n const addLabels = [`tier: ${risk.tier}`, ...(risk.tier === 3 && tokens ? ['tokens'] : [])];\n const date = (input.date ?? new Date()).toISOString().slice(0, 10);\n const existing = new Set(input.body ? [...input.body.matchAll(/\\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\\s+#(\\d+)/gi)].map((m) => Number(m[1])) : []);\n const closes = [...new Set(input.requests ?? [])].filter((n) => !existing.has(n));\n const kept = (input.body ?? '')\n // The sandbox warning and the promote/close instructions no longer apply.\n .replace(/^> Not mergeable as is\\..*$\\n?\\n?/m, '')\n .replace(/### When it is done[\\s\\S]*?(?=<!-- |$)/, '')\n .replace(/^## Exploration: /m, '## ')\n .trim();\n const body = [\n `**Promoted from an exploration on ${date}.** Review it like any change: the tier below comes from the files it touches.`,\n '',\n kept || `## ${title.replace(/^Exploration:\\s*/i, '')}`,\n '',\n `**Risk tier:** ${risk.tier}.`,\n ...risk.reasons.slice(0, 8).map((r) => `- ${r}`),\n ...(closes.length ? ['', ...closes.map((n) => `Closes #${n}`)] : []),\n ].join('\\n');\n const t = title.replace(/^Exploration:\\s*/i, '').trim() || exploration?.name || title;\n return {\n tier: risk.tier,\n reasons: risk.reasons,\n removeLabels: [EXPLORATION_LABEL],\n addLabels,\n removeFiles,\n body,\n title: `${jira ? `${jira} ` : ''}${t.charAt(0).toUpperCase()}${t.slice(1)}`,\n markReady: true,\n };\n}\n\n/** Where the test build of an exploration stands, from its sticky preview comment and the branch head. */\nexport type ExplorationTryIt =\n | { state: 'ready'; command: string; source: 'pkg.pr.new' | 'release' | 'other'; sha7: string | null }\n | { state: 'building' }\n | { state: 'failed' };\n\n/**\n * The install command a product staging branch can trust, read from the `<!-- bridge-branch-preview -->` comment,\n * never guessed: no comment yet, or a comment about an older commit than the head, means the snapshot is still\n * building; a comment without a command means the publish failed.\n */\nexport function explorationTryIt(input: { comment?: string | null | undefined; headSha?: string | null | undefined }): ExplorationTryIt {\n const c = readPreviewComment(input.comment);\n if (!c) return { state: 'building' };\n if (input.headSha && c.sha7 && !input.headSha.startsWith(c.sha7)) return { state: 'building' };\n if (!c.command || c.source === 'none') return { state: 'failed' };\n return { state: 'ready', command: c.command, source: c.source, sha7: c.sha7 };\n}\n\n/**\n * The message a designer sends a developer: what the exploration is, the install command for a product staging\n * branch, the previews and the pull request. Plain text, one paragraph, ready to paste in a chat.\n */\nexport function explorationShareMessage(input: { name: string; branch: string; url: string; command?: string | null | undefined; previews?: { label: string; url: string }[] | undefined }): string {\n const name = input.name.trim().replace(/\"/g, \"'\");\n const head = input.command\n ? `Exploration \"${name}\" (${input.branch}): try it in a staging branch of your product with: ${input.command}.`\n : `Exploration \"${name}\" (${input.branch}): its test build is being prepared, the install command for a staging branch of your product will be on the pull request in a few minutes.`;\n const previews = (input.previews ?? []).map((p) => `${p.label} ${p.url}`);\n return [head, previews.length ? `Previews: ${previews.join(', ')}.` : '', `Pull request: ${input.url}.`].filter(Boolean).join(' ');\n}\n\n/**\n * The rules Claude follows on an exploration branch (request briefs, docs drafts, token edits with a target branch):\n * work there, never on main, and never open a pull request to main: the exploration's draft pull request is the place.\n */\nexport function explorationRules(branch: string): string[] {\n return [\n `- Work on the existing branch ${branch} (git fetch origin && git switch ${branch}). Commit there.`,\n `- Do not open a pull request to main and do not create another branch: the draft pull request of ${branch} is the place. It is promoted to review only when the idea is validated.`,\n '- Do not mark the pull request ready for review and do not remove the exploration label: promoting is a person\\'s decision.',\n ];\n}\n","// Component change requests: a designer asks for a new component or a change to a coded one (variant, prop, structure,\n// visual, token binding, bug) from Figma or Studio. Variable edits never become requests: they are pull requests\n// people approve (tokens are data). Components need code, so they become requests. Code stays the source of truth, so a request never rewrites React: it lands as\n// a GitHub issue that people (or Claude, through the MCP server or the CLI) implement in a pull request that closes it.\n// Shared by the Figma plugin, Studio, the MCP server, the CLI and the Jira Action, so a request reads the same\n// everywhere. The issue body is plain Markdown for people plus one hidden JSON block for tools.\n\nimport { EXPLORATION_LABEL, explorationRules } from './explorations';\n\nexport type RequestKind = 'new-component' | 'new-variant' | 'prop-change' | 'structure' | 'visual' | 'token-binding' | 'bug' | 'other';\nexport type RequestSource = 'figma' | 'studio' | 'cli' | 'mcp';\nexport type RequestStatus = 'requested' | 'in-progress' | 'done' | 'declined';\n\nexport const REQUEST_KINDS: { value: RequestKind; label: string; hint: string }[] = [\n { value: 'new-component', label: 'New component', hint: 'A component the design system does not have yet.' },\n { value: 'new-variant', label: 'New variant', hint: 'A size, tone or state the component does not have yet.' },\n { value: 'prop-change', label: 'Option change (prop)', hint: 'Add, rename or change an option (a prop in code) or its default.' },\n { value: 'structure', label: 'Structure change', hint: 'A part was added, removed or moved.' },\n { value: 'visual', label: 'Visual change', hint: 'Spacing, radius, layout or icon placement.' },\n { value: 'token-binding', label: 'Token change', hint: 'The component should paint with another token.' },\n { value: 'bug', label: 'Bug', hint: 'It looks or behaves differently from the guidance.' },\n { value: 'other', label: 'Other', hint: 'Anything else.' },\n];\n\n/** Every request issue carries this label; tools list requests by it. */\nexport const REQUEST_LABEL = 'component-change';\n\nexport interface RequestChange {\n /** What changes: a prop, a variant axis, a token, a part (\"radius\", \"size\", \"color.action.primary.bg\"). */\n field: string;\n before?: string | undefined;\n after?: string | undefined;\n}\n\nexport interface ComponentChangeRequest {\n /** Component name as exported (\"Button\"), or the proposed name of a new component. */\n component: string;\n kind: RequestKind;\n /** One line, sentence case: \"Add a danger ghost variant\". */\n title: string;\n /** What and why, in the requester's words. */\n summary: string;\n /**\n * What changed for developers in one sentence (\"Icon added after the label in primary sm: Pencil, 16px\"): written\n * by Claude from the before and after images, or drafted from the detected changes. Optional.\n */\n line?: string | undefined;\n changes: RequestChange[];\n /** Where the design lives, when it comes from Figma. */\n figma?: { fileKey?: string | undefined; nodeId?: string | undefined; nodeName?: string | undefined; url?: string | undefined } | undefined;\n /** Image URLs (Figma exports committed to the requests branch, or links). */\n images?: string[] | undefined;\n source: RequestSource;\n /** GitHub login, when known. */\n requestedBy?: string | undefined;\n /**\n * Exploration branch (`explore/<slug>`) to implement it on instead of a pull request to main. The issue gets the\n * `exploration` label and the brief says to work on that branch (docs/EXPLORATIONS.md).\n */\n exploration?: string | undefined;\n}\n\nexport interface RequestIssue {\n title: string;\n body: string;\n labels: string[];\n assignees: string[];\n}\n\nconst MARK = 'bridge-request';\nconst kindLabel = (k: RequestKind) => REQUEST_KINDS.find((x) => x.value === k)?.label ?? 'Other';\nconst kindSlug = (k: RequestKind) => `request: ${k}`;\n\n/** Issue title: \"Button: add a danger ghost variant\". */\nexport function requestIssueTitle(r: Pick<ComponentChangeRequest, 'component' | 'title'>): string {\n const t = r.title.trim().replace(/\\.$/, '');\n return `${r.component}: ${t.charAt(0).toLowerCase()}${t.slice(1)}`;\n}\n\n/** The GitHub issue for a request: readable Markdown, the labels tools filter on, and a hidden JSON block. */\nexport function composeRequestIssue(r: ComponentChangeRequest, opts: { labels?: string[]; assignees?: string[]; componentUrl?: string } = {}): RequestIssue {\n const rows = r.changes.length\n ? ['| What | Now | Requested |', '| --- | --- | --- |', ...r.changes.map((c) => `| ${cell(c.field)} | ${cell(c.before ?? '')} | ${cell(c.after ?? '')} |`)]\n : [];\n const figma = r.figma?.url ? `[${r.figma.nodeName ?? 'Open in Figma'}](${r.figma.url})` : r.figma?.nodeName ? r.figma.nodeName : '';\n const body = [\n r.kind === 'new-component' ? `## New component request: ${r.component}` : `## ${kindLabel(r.kind)} request for ${r.component}`,\n '',\n r.summary.trim(),\n '',\n ...(r.line?.trim() ? [`**What changes:** ${r.line.trim()}`, ''] : []),\n ...(rows.length ? [...rows, ''] : []),\n ...(r.images?.length ? [...r.images.map((u, i) => `![${r.component} design ${i + 1}](${u})`), ''] : []),\n ...(figma ? [`**Design:** ${figma}`, ''] : []),\n ...(opts.componentUrl ? [`**Component:** ${opts.componentUrl}`, ''] : []),\n ...(r.exploration ? [`**Exploration:** \\`${r.exploration}\\`. Implement it on that branch, not in a pull request to main: it ships to product staging as a snapshot and is promoted to review only when the idea is validated.`, ''] : []),\n '## How to implement',\n '',\n r.exploration\n ? `Commit the change to \\`${r.exploration}\\` (its draft pull request is the place). With Claude: \\`bridge request implement <number>\\` (CLI) or the \\`bridge_get_request\\` MCP tool. Promoting the exploration closes this request when it merges.`\n : `Code is the source of truth: change the component in a pull request that says \\`Closes #<this issue>\\`, so this request closes when it merges. With Claude: \\`bridge request implement <number>\\` (CLI) or the \\`bridge_get_request\\` MCP tool.`,\n '',\n `<sub>Requested from ${sourceLabel(r.source)}${r.requestedBy ? ` by @${r.requestedBy}` : ''} with Bridge.</sub>`,\n '',\n `<!-- ${MARK} ${JSON.stringify(r)} -->`,\n ].join('\\n');\n const labels = [...new Set([REQUEST_LABEL, kindSlug(r.kind), `source: ${r.source}`, ...(r.exploration ? [EXPLORATION_LABEL] : []), ...(opts.labels ?? [])])];\n return { title: requestIssueTitle(r), body, labels, assignees: opts.assignees ?? [] };\n}\n\n/** The request inside an issue body, or undefined when the body has no valid Bridge block. */\nexport function parseRequestIssue(body: string | null | undefined): ComponentChangeRequest | undefined {\n if (!body) return undefined;\n const m = new RegExp(`<!-- ${MARK} (\\\\{[\\\\s\\\\S]*?\\\\}) -->`).exec(body);\n if (!m) return undefined;\n try {\n const r = JSON.parse(m[1]!) as ComponentChangeRequest;\n return r && typeof r.component === 'string' && typeof r.title === 'string' ? { ...r, changes: Array.isArray(r.changes) ? r.changes : [] } : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The issue body with the request linked to an exploration branch: the hidden block gets `exploration` (what the\n * Explorations view, the MCP server and the CLI read) and the readable part says where to implement it. The rest of the\n * body stays as people wrote it. Undefined when the body has no Bridge block (nothing to link).\n */\nexport function withRequestExploration(body: string | null | undefined, branch: string): string | undefined {\n const r = parseRequestIssue(body);\n if (!r || !body) return undefined;\n const block = new RegExp(`<!-- ${MARK} \\\\{[\\\\s\\\\S]*?\\\\} -->`);\n let out = body.replace(block, () => `<!-- ${MARK} ${JSON.stringify({ ...r, exploration: branch })} -->`);\n const line = `**Exploration:** \\`${branch}\\`. Implement it on that branch, not in a pull request to main: it ships to product staging as a snapshot and is promoted to review only when the idea is validated.`;\n if (/^\\*\\*Exploration:\\*\\* .*$/m.test(out)) out = out.replace(/^\\*\\*Exploration:\\*\\* .*$/m, () => line);\n else if (out.includes('\\n## How to implement')) out = out.replace('\\n## How to implement', () => `\\n${line}\\n\\n## How to implement`);\n else out = out.replace(block, (m) => `${line}\\n\\n${m}`);\n return out;\n}\n\n/** Problems with a decline reason, as sentences that say how to fix them. */\nexport function declineReasonProblems(reason: string): string[] {\n const r = reason.trim();\n if (!r) return ['Say why, in one or two sentences: the requester reads it.'];\n if (r.length < 10) return ['Say a bit more, so the requester knows why: at least 10 characters.'];\n return [];\n}\n\n/** The comment posted on a declined request: who declined it and why, in the decliner's words. */\nexport function declineComment(reason: string, by?: string | null): string {\n const quote = reason\n .trim()\n .split('\\n')\n .map((l) => `> ${l}`.trimEnd())\n .join('\\n');\n return [`Declined${by ? ` by @${by.replace(/^@/, '')}` : ''} in Bridge Studio.`, '', quote, '', '<sub>Closed as not planned. Reopen the issue if things change.</sub>'].join('\\n');\n}\n\n/**\n * Where a request stands: open with no linked pull request = requested; open with an open linked pull request =\n * in progress; closed as completed or by a merged pull request = done; closed otherwise = declined.\n */\nexport function requestStatus(issue: { state: 'open' | 'closed'; stateReason?: string | null | undefined; linkedPrs?: { state: 'open' | 'closed'; merged?: boolean }[] }): RequestStatus {\n const prs = issue.linkedPrs ?? [];\n if (issue.state === 'open') return prs.some((p) => p.state === 'open') ? 'in-progress' : 'requested';\n if (prs.some((p) => p.merged) || issue.stateReason === 'completed') return 'done';\n return 'declined';\n}\n\nexport const REQUEST_STATUS_LABEL: Record<RequestStatus, string> = { requested: 'Requested', 'in-progress': 'In progress', done: 'Done', declined: 'Declined' };\n\n/** Issue numbers a pull request body closes (\"Closes #42\", \"fixes #7\", \"resolves #3\"). */\nexport function closingIssueNumbers(body: string | null | undefined): number[] {\n const out = new Set<number>();\n for (const m of (body ?? '').matchAll(/\\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\\s+#(\\d+)/gi)) out.add(Number(m[1]));\n return [...out];\n}\n\n/** Path of a Figma image attached to a request, on the requests branch. */\nexport const REQUESTS_BRANCH = 'bridge-requests';\nexport function requestImagePath(component: string, date: Date): string {\n const slug = component.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'component';\n return `.bridge/requests/${slug}-${date.toISOString().replace(/[-:]/g, '').replace(/\\..*$/, '')}.png`;\n}\n\n/**\n * The brief Claude gets to implement a request (CLI `bridge request implement`, MCP `bridge_get_request`): the request,\n * the component's files, the repo rules, and how to open the pull request so it closes the issue.\n */\nexport function requestBrief(r: ComponentChangeRequest, ctx: { issue: number; issueUrl?: string; files?: string[]; agentsFile?: string; exploration?: string | undefined }): string {\n const exploration = ctx.exploration ?? r.exploration;\n return [\n `Implement Bridge component change request #${ctx.issue}${ctx.issueUrl ? ` (${ctx.issueUrl})` : ''}.`,\n '',\n `Component: ${r.component}`,\n `Kind: ${kindLabel(r.kind)}`,\n `Request: ${r.title}`,\n ...(r.line?.trim() ? [`What changes: ${r.line.trim()}`] : []),\n '',\n r.summary.trim(),\n '',\n ...(r.changes.length ? ['Changes asked:', ...r.changes.map((c) => `- ${c.field}: ${c.before ?? '(none)'} -> ${c.after ?? '(removed)'}`), ''] : []),\n ...(r.figma?.url ? [`Design: ${r.figma.url}`, ''] : []),\n ...(r.images?.length ? ['Images:', ...r.images.map((u) => `- ${u}`), ''] : []),\n ...(ctx.files?.length ? ['Files of this component:', ...ctx.files.map((f) => `- ${f}`), ''] : []),\n 'Rules:',\n `- Follow ${ctx.agentsFile ?? 'AGENTS.md'}: tokens only in component CSS, Base UI for behavior, states, tests, story, docs.json, changeset.`,\n '- A new component, prop or variant is Tier 2: open the pull request as a draft (new component: follow the new component checklist). A token add or rename is Tier 3: describe it, do not invent values.',\n ...(exploration\n ? [`- This request is part of the exploration ${exploration}.`, ...explorationRules(exploration), `- Reference the request in the commit message (\"Refs #${ctx.issue}\"). Promoting the exploration closes it.`]\n : [`- Work on a branch named agent/request-${ctx.issue}. The pull request body must contain \"Closes #${ctx.issue}\".`]),\n '- If the request is unclear or conflicts with the guidance, comment on the issue instead of guessing.',\n ].join('\\n');\n}\n\nconst cell = (s: string) => s.replace(/\\|/g, '\\\\|').replace(/\\n/g, ' ');\nconst sourceLabel = (s: RequestSource) => (s === 'figma' ? 'Figma' : s === 'studio' ? 'Bridge Studio' : s === 'cli' ? 'the CLI' : 'Claude (MCP)');\n\n// ---------------------------------------------------------------------------------------------\n// Integrations (bridge.config.json \"integrations\"): where requests go besides the GitHub issue.\n\nexport interface JiraIntegration {\n /** Jira site, e.g. \"https://acme.atlassian.net\". The token lives in the repo secrets, never in config. */\n baseUrl: string;\n /** Project key, e.g. \"DS\". */\n project: string;\n /** Issue type, default \"Task\". */\n issueType?: string | undefined;\n labels?: string[] | undefined;\n}\n\nexport interface IntegrationsConfig {\n requests?: { labels?: string[] | undefined; assignees?: string[] | undefined } | undefined;\n /** Mirror each request to Jira through the bridge-jira GitHub Action. */\n jira?: JiraIntegration | undefined;\n}\n\n/** Problems in an integrations block, as sentences that say how to fix them. Empty when valid. */\nexport function validateIntegrations(i: IntegrationsConfig | undefined): string[] {\n const out: string[] = [];\n if (!i?.jira) return out;\n if (!/^https:\\/\\/[^/]+/.test(i.jira.baseUrl ?? '')) out.push('Jira site must start with https://, for example https://acme.atlassian.net.');\n if (!/^[A-Z][A-Z0-9_]{1,9}$/.test(i.jira.project ?? '')) out.push('Jira project key is 2 to 10 capital letters or digits, like DS.');\n return out;\n}\n\n/** The Jira issue fields the Action sends for a request (Jira Cloud REST v3, Atlassian document format). */\nexport function jiraIssueFields(r: ComponentChangeRequest, jira: JiraIntegration, issueUrl: string): Record<string, unknown> {\n const text = (t: string) => ({ type: 'text', text: t });\n const para = (...c: unknown[]) => ({ type: 'paragraph', content: c });\n return {\n project: { key: jira.project },\n issuetype: { name: jira.issueType ?? 'Task' },\n summary: requestIssueTitle(r),\n labels: [...new Set(['bridge', REQUEST_LABEL, ...(jira.labels ?? [])])].map((l) => l.replace(/\\s+/g, '-')),\n description: {\n type: 'doc',\n version: 1,\n content: [\n para(text(r.summary.trim() || r.title)),\n ...(r.line?.trim() ? [para(text(r.line.trim()))] : []),\n ...r.changes.map((c) => para(text(`${c.field}: ${c.before ?? '(none)'} -> ${c.after ?? '(removed)'}`))),\n para({ type: 'text', text: 'GitHub request', marks: [{ type: 'link', attrs: { href: issueUrl } }] }),\n ],\n },\n };\n}\n","// Draft exchange: designers draft their change texts with their own Claude (Claude Desktop or Claude Code on their own\n// plan) through the Bridge MCP server, from the DS Bridge Figma plugin. Third-party apps cannot use a Claude plan, and\n// Bridge has no backend, so the channel is the GitHub repo both already reach with the designer's own token:\n//\n// 1. The plugin writes `.bridge/drafts/<sessionId>.json` (status \"pending\") on the requests branch, with the detected\n// changes, the deterministic draft and links to before and after PNGs uploaded next to it.\n// 2. The designer tells their Claude \"Draft my Bridge changes\". The MCP tool bridge_pending_drafts returns the pending\n// items (and the images, so Claude can see them), bridge_write_drafts writes the results back (status \"drafted\").\n// 3. The plugin polls the file, fills the fields it may fill, then deletes the file once the request or push is sent\n// (or cancelled).\n//\n// Bridge Studio uses the same exchange for component docs (a \"docs\" item, from the Library page): the item carries the\n// task (which prose sections, or a selected passage) and the full prompt with the facts from the code; the result\n// carries the sections (or the rewritten passage), sanitized to the docs.json shapes.\n//\n// Writers update with the file sha (optimistic concurrency) and retry on 409. Pure helpers plus a few GitHubClient\n// helpers: no DOM, no figma.*, no Node-only API.\n\nimport { DRAFT_LINE_MAX, cleanDraftText, sanitizeDraftLine, type DraftText } from './change-drafts';\nimport { type DocsDraftTask, type DocsSections, docsSectionsAnswer, docsTaskKeys, sanitizeDocsReplacement, validateDocsTask } from './docs-ai';\nimport type { ProseKey } from './docs-draft';\nimport { GitHubError, type GitHubClient } from './github-client';\nimport { REQUESTS_BRANCH, type RequestChange, type RequestKind, REQUEST_KINDS } from './requests';\n\nexport const DRAFT_EXCHANGE_VERSION = 1;\n/** Folder of pending draft sessions on the requests branch. */\nexport const DRAFTS_DIR = '.bridge/drafts';\n/** What the designer says to their Claude. */\nexport const DRAFT_PHRASE = 'Draft my Bridge changes';\nexport const DRAFT_TITLE_MAX = 70;\nexport const DRAFT_SUMMARY_SENTENCES = 3;\nexport { DRAFT_LINE_MAX };\nconst SUMMARY_MAX = 600;\n\nexport type DraftScope = 'request' | 'push' | 'docs';\n/** Who wrote the session: the DS Bridge Figma plugin, or Bridge Studio (component docs on the Library page). */\nexport type DraftSource = 'figma' | 'studio';\nexport type DraftSessionStatus = 'pending' | 'drafted';\n\nexport interface DraftImage {\n label: 'before' | 'after';\n /** Public URL on the requests branch (github.com/<repo>/blob/bridge-requests/<path>?raw=true). */\n url: string;\n /** Repo path on the requests branch, so tools can read it with the token. */\n path?: string | undefined;\n /** The change line (DraftLine id) this image shows, when an item has several components (a push). */\n line?: string | undefined;\n}\n\n/**\n * One detected component change to describe in one sentence (its \"change line\"): the main line of its row in the\n * plugin and the first line of its request. A request item has one, a push item one per component it requests.\n */\nexport interface DraftLine {\n /** Stable id to answer with (the plugin uses the component's node id). */\n id: string;\n component?: string | undefined;\n kind?: RequestKind | undefined;\n changes: RequestChange[];\n /** The deterministic line, from the changes only, as a starting point. */\n line: string;\n /** The deterministic request title of this component change, as a starting point. Missing from older plugins. */\n title?: string | undefined;\n}\n\nexport interface DraftVariableRow {\n path: string;\n before?: string | undefined;\n after?: string | undefined;\n}\n\nexport interface DraftItem {\n id: string;\n /** \"request\": one component change request. \"push\": the pull request description of variable edits. */\n scope: DraftScope;\n component?: string | undefined;\n kind?: RequestKind | undefined;\n changes: RequestChange[];\n /** Push only: the variable edits (token path, value now, value in Figma). */\n variables?: DraftVariableRow[] | undefined;\n /** Push only: components the push also sends a request for. */\n components?: string[] | undefined;\n /** What the designer already typed: their intent, kept in the answer. */\n notes?: string | undefined;\n images?: DraftImage[] | undefined;\n /** The deterministic draft (from the detected changes only), as a starting point. */\n draft: DraftText;\n /** Component changes to write one line each for. Missing in sessions from older plugins. */\n lines?: DraftLine[] | undefined;\n /** Docs only: the component docs to write. */\n docs?: DraftDocsItem | undefined;\n}\n\n/** A docs item: prose sections of one component's docs.json (or one selected passage), from Bridge Studio. */\nexport interface DraftDocsItem {\n /** Component slug on the Library page (button, icon-button). */\n slug: string;\n /** docs.json path in the repo. */\n path?: string | undefined;\n task: DocsDraftTask;\n /** The full prompt: the task, the rules, the facts from the code (props, CSS module classes, JSDoc, tokens), the voice. */\n prompt: string;\n}\n\nexport interface DraftResult {\n id: string;\n title: string;\n summary: string;\n /**\n * One sentence per change line of the item (by DraftLine id), and the title of the request it becomes. Optional:\n * older writers send none, or lines without a title.\n */\n lines?: DraftResultLine[] | undefined;\n /** Docs items (sections task): the sections Claude wrote, sanitized to the docs.json shapes. */\n docs?: DocsSections | undefined;\n /** Docs items (selection task): the rewritten passage. */\n replacement?: string | undefined;\n /** Docs items (sections task): checked sections Claude verified and left unchanged (still accurate). */\n checked?: ProseKey[] | undefined;\n by: 'claude';\n at: string;\n}\n\nexport interface DraftResultLine {\n id: string;\n /** May be empty when only the title was written. */\n line: string;\n /** The request title of this component change: short, sentence case, at most 70 characters (\"Add an icon after the label\"). */\n title?: string | undefined;\n}\n\nexport interface PendingDrafts {\n version: 1;\n sessionId: string;\n createdAt: string;\n status: DraftSessionStatus;\n source: DraftSource;\n items: DraftItem[];\n results?: DraftResult[] | undefined;\n}\n\n// ---------------------------------------------------------------------------------------------\n// The words Claude gets: the Bridge voice and the exact output contract.\n\nexport const DRAFT_VOICE_RULES = [\n 'Write like a calm, precise colleague. Sentence case. Start the title with a verb.',\n 'Look at the before and after images first, then the change table: say what changes for developers (props, variants, tokens, the look) and why it matters for people who use the component.',\n 'Use only facts from the changes, the images and the designer\\'s notes. Never invent numbers, names, usage or reasons. If the reason is unknown, say what changes and leave the reason out.',\n 'Keep the designer\\'s intent from their notes.',\n 'Never use an em dash: use a colon, a comma or parentheses. No exclamation marks, no emoji, no Markdown.',\n 'A request title never repeats the component name: the issue title already starts with it.',\n `For each change line, write one short sentence (at most ${DRAFT_LINE_MAX} characters, no trailing period) of what changed for developers, read from the before and after images: the part, the variant and the values when you can see them, for example \"Icon added after the label in primary sm: Pencil, 16px\". Never guess a value you cannot read.`,\n `For each change line, also write the title of the request it becomes: short, sentence case, starts with a verb, at most ${DRAFT_TITLE_MAX} characters, no trailing period, never the component name, for example \"Add an icon after the label\".`,\n];\n\nexport const DRAFT_OUTPUT_CONTRACT = [\n `Call bridge_write_drafts once per session with {\"sessionId\": \"...\", \"results\": [{\"id\": \"<item id>\", \"title\": \"...\", \"summary\": \"...\", \"lines\": [{\"id\": \"<line id>\", \"line\": \"...\", \"title\": \"...\"}]}]}, one result per item.`,\n `title: one line, at most ${DRAFT_TITLE_MAX} characters, no trailing period.`,\n `summary: at most ${DRAFT_SUMMARY_SENTENCES} sentences, plain text.`,\n `lines: one per change line the item lists (its \"lines\"), by line id: line is one sentence, at most ${DRAFT_LINE_MAX} characters, no trailing period; title is the request title for that component change, at most ${DRAFT_TITLE_MAX} characters, no trailing period. Leave lines out when the item lists none.`,\n 'Docs items (scope \"docs\", from Bridge Studio): follow the item\\'s prompt and send {\"id\": \"<item id>\", \"docs\": {<only the sections it asks for>}} for a sections task (a section to check goes in only when something in it is no longer true for the code: leave accurate ones out, {\"docs\": {}} when all are), or {\"id\": \"<item id>\", \"replacement\": \"...\"} for a selection task. No title or summary. The designer reviews them on the Library page.',\n 'The designer reviews the text in Figma before anything is sent.',\n];\n\n// ---------------------------------------------------------------------------------------------\n// Pure helpers\n\n/** A random session id: 16 lowercase base-36 characters, safe in a file name. */\nexport function newDraftSessionId(random: () => number = Math.random): string {\n let out = '';\n while (out.length < 16) out += Math.floor(random() * 36).toString(36);\n return out;\n}\n\nconst SESSION_RE = /^[a-z0-9-]{6,64}$/;\nexport const isDraftSessionId = (s: unknown): s is string => typeof s === 'string' && SESSION_RE.test(s);\n\n/** Path of a session file on the requests branch. */\nexport function draftSessionPath(sessionId: string): string {\n if (!isDraftSessionId(sessionId)) throw new Error(`\"${sessionId}\" is not a draft session id.`);\n return `${DRAFTS_DIR}/${sessionId}.json`;\n}\n\n/** Path of an image of a session item on the requests branch: `.bridge/drafts/<sessionId>/<itemId>-<label>.png`. */\nexport function draftImagePath(sessionId: string, itemId: string, label: DraftImage['label']): string {\n const item = itemId.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'item';\n draftSessionPath(sessionId);\n return `${DRAFTS_DIR}/${sessionId}/${item}-${label}.png`;\n}\n\nexport interface ComposeDraftsInput {\n items: DraftItem[];\n source?: DraftSource | undefined;\n sessionId?: string | undefined;\n now?: Date | undefined;\n random?: (() => number) | undefined;\n}\n\n/** A new pending session. Throws when it has no item or an item is invalid. */\nexport function composePendingDrafts(input: ComposeDraftsInput): PendingDrafts {\n const p: PendingDrafts = {\n version: DRAFT_EXCHANGE_VERSION,\n sessionId: input.sessionId ?? newDraftSessionId(input.random),\n createdAt: (input.now ?? new Date()).toISOString(),\n status: 'pending',\n source: input.source ?? 'figma',\n items: input.items.map((i) => ({ ...i, changes: i.changes ?? [] })),\n };\n const problems = validatePendingDrafts(p);\n if (problems.length) throw new Error(problems.join(' '));\n return p;\n}\n\nconst KINDS = new Set<string>(REQUEST_KINDS.map((k) => k.value));\nconst str = (x: unknown) => typeof x === 'string';\nconst optStr = (x: unknown) => x === undefined || typeof x === 'string';\n\n/** Problems in a session, as sentences. Empty when valid. */\nexport function validatePendingDrafts(x: unknown): string[] {\n const out: string[] = [];\n if (!x || typeof x !== 'object' || Array.isArray(x)) return ['A draft session is a JSON object.'];\n const p = x as Partial<PendingDrafts>;\n if (p.version !== DRAFT_EXCHANGE_VERSION) out.push(`Unsupported draft session version ${String(p.version)}: update Bridge.`);\n if (!isDraftSessionId(p.sessionId)) out.push('The session id is missing or invalid.');\n if (!str(p.createdAt) || Number.isNaN(Date.parse(p.createdAt!))) out.push('createdAt must be an ISO date.');\n if (p.status !== 'pending' && p.status !== 'drafted') out.push('status must be \"pending\" or \"drafted\".');\n if (p.source !== 'figma' && p.source !== 'studio') out.push('source must be \"figma\" or \"studio\".');\n if (!Array.isArray(p.items) || !p.items.length) out.push('A draft session needs at least one item.');\n const ids = new Set<string>();\n for (const [n, i] of (Array.isArray(p.items) ? p.items : []).entries()) {\n const at = `Item ${n + 1}`;\n if (!i || typeof i !== 'object') {\n out.push(`${at} is not an object.`);\n continue;\n }\n if (!str(i.id) || !i.id) out.push(`${at} has no id.`);\n else if (ids.has(i.id)) out.push(`${at} repeats the id \"${i.id}\".`);\n else ids.add(i.id);\n if (i.scope !== 'request' && i.scope !== 'push' && i.scope !== 'docs') out.push(`${at}: scope must be \"request\", \"push\" or \"docs\".`);\n if (i.scope === 'docs') {\n const d = i.docs;\n if (!d || typeof d !== 'object' || !str(d.slug) || !d.slug || !str(d.prompt) || !d.prompt || !optStr(d.path)) out.push(`${at}: a docs item needs docs {slug, task, prompt}.`);\n else out.push(...validateDocsTask(d.task).map((m) => `${at}: ${m}`));\n } else if (i.docs !== undefined) out.push(`${at}: only a docs item has docs.`);\n if (!optStr(i.component)) out.push(`${at}: component must be text.`);\n if (i.kind !== undefined && !KINDS.has(i.kind)) out.push(`${at}: unknown kind \"${String(i.kind)}\".`);\n if (!Array.isArray(i.changes) || i.changes.some((c) => !c || !str(c.field) || !optStr(c.before) || !optStr(c.after))) out.push(`${at}: changes must be a list of {field, before, after}.`);\n if (i.variables !== undefined && (!Array.isArray(i.variables) || i.variables.some((v) => !v || !str(v.path)))) out.push(`${at}: variables must be a list of {path, before, after}.`);\n if (i.variables !== undefined && i.scope !== 'push') out.push(`${at}: only a push item has variables.`);\n if (i.images !== undefined && (!Array.isArray(i.images) || i.images.some((m) => !m || (m.label !== 'before' && m.label !== 'after') || !str(m.url)))) out.push(`${at}: images must be a list of {label: before or after, url}.`);\n if (!i.draft || !str(i.draft.title) || !str(i.draft.summary)) out.push(`${at}: draft must hold a title and a summary.`);\n if (i.lines !== undefined && (!Array.isArray(i.lines) || i.lines.some((l) => !l || !str(l.id) || !l.id || !str(l.line) || !optStr(l.title) || !Array.isArray(l.changes)))) out.push(`${at}: lines must be a list of {id, changes, line, title}.`);\n }\n if (p.results !== undefined) {\n if (!Array.isArray(p.results)) out.push('results must be a list.');\n else\n for (const r of p.results) {\n if (!r || !str(r.id) || !str(r.title) || !str(r.summary)) out.push('Each result needs an id, a title and a summary.');\n else if (r.docs !== undefined && (!r.docs || typeof r.docs !== 'object' || Array.isArray(r.docs))) out.push('Result docs must be an object of sections.');\n else if (!optStr(r.replacement)) out.push('A result replacement must be text.');\n else if (r.lines !== undefined && (!Array.isArray(r.lines) || r.lines.some((l) => !l || !str(l.id) || !str(l.line) || !optStr(l.title)))) out.push('Result lines must be a list of {id, line, title}.');\n }\n }\n return out;\n}\n\n/** The session in a file's text, or undefined when it is not a valid session. */\nexport function parsePendingDrafts(text: string | null | undefined): PendingDrafts | undefined {\n if (!text) return undefined;\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch {\n return undefined;\n }\n return validatePendingDrafts(json).length ? undefined : (json as PendingDrafts);\n}\n\nexport function serializePendingDrafts(p: PendingDrafts): string {\n return `${JSON.stringify(p, null, 2)}\\n`;\n}\n\n/** Shortens to `max` characters at a word boundary, without a trailing period. */\nfunction clip(text: string, max: number): string {\n const t = text.replace(/\\s+/g, ' ').trim().replace(/\\.$/, '');\n if (t.length <= max) return t;\n const cut = t.slice(0, max + 1);\n const at = cut.lastIndexOf(' ');\n return (at > max * 0.5 ? cut.slice(0, at) : t.slice(0, max)).replace(/[\\s,;:]+$/, '');\n}\n\n/** At most 3 sentences and 600 characters. */\nfunction sentences(text: string): string {\n const t = text.replace(/\\s+/g, ' ').trim();\n const parts = t.match(/[^.!?]+(?:[.!?]+(?=\\s|$)|$)/g) ?? [t];\n let out = parts.slice(0, DRAFT_SUMMARY_SENTENCES).map((s) => s.trim()).join(' ');\n if (out.length > SUMMARY_MAX) out = `${clip(out, SUMMARY_MAX)}.`;\n return out;\n}\n\n/**\n * Title and summary kept to the contract: em dashes removed, title one line of at most 70 characters with no\n * trailing period, summary at most 3 sentences. Both may come back empty.\n */\nexport function sanitizeDraftText(raw: { title?: unknown; summary?: unknown }): DraftText {\n const title = typeof raw.title === 'string' ? clip(cleanDraftText(raw.title), DRAFT_TITLE_MAX) : '';\n const summary = typeof raw.summary === 'string' ? sentences(cleanDraftText(raw.summary)) : '';\n return { title, summary };\n}\n\n/** What a writer (bridge_write_drafts) sends for one item, before sanitizing. */\nexport interface DraftResultInput {\n id: string;\n title?: unknown;\n summary?: unknown;\n lines?: unknown;\n /** Docs items: the sections written (sections task). */\n docs?: unknown;\n /** Docs items: the rewritten passage (selection task). */\n replacement?: unknown;\n}\n\n/** The docs part of a result for a docs item, sanitized to its task. Throws when it holds nothing the task asked for. */\nexport function sanitizeDocsResult(item: DraftItem, r: DraftResultInput): Pick<DraftResult, 'docs' | 'replacement' | 'checked'> {\n const task = item.docs!.task;\n if (task.kind === 'selection') {\n const raw = r.replacement ?? (r.docs && typeof r.docs === 'object' ? (r.docs as Record<string, unknown>)[task.key] : undefined);\n const replacement = sanitizeDocsReplacement(raw);\n if (!replacement) throw new Error(`Item \"${item.id}\" asks to rewrite a passage of ${task.key}: send {\"id\": \"${item.id}\", \"replacement\": \"...\"}.`);\n return { replacement };\n }\n try {\n const { sections, checked } = docsSectionsAnswer(task, r.docs ?? {});\n return { docs: sections, checked };\n } catch {\n throw new Error(`Item \"${item.id}\" asks for the sections ${docsTaskKeys(task).join(', ')}: send {\"id\": \"${item.id}\", \"docs\": {${task.keys.map((k) => `\"${k}\": ...`).join(', ')}}} in the shapes of its prompt.`);\n }\n}\n\n/**\n * The change lines of a result kept to the contract: known line ids only (throws on an unknown one), one sentence of\n * at most 120 characters each, empty ones dropped, the last one per id kept.\n */\nexport function sanitizeResultLines(item: Pick<DraftItem, 'id' | 'lines'>, raw: unknown): DraftResultLine[] {\n if (raw === undefined || raw === null) return [];\n if (!Array.isArray(raw)) throw new Error(`lines for \"${item.id}\" must be a list of {\"id\", \"line\", \"title\"}.`);\n const known = new Set((item.lines ?? []).map((l) => l.id));\n const out = new Map<string, DraftResultLine>();\n for (const l of raw as { id?: unknown; line?: unknown; title?: unknown }[]) {\n const id = typeof l?.id === 'string' ? l.id : '';\n if (!known.has(id)) throw new Error(`Item \"${item.id}\" has no change line \"${id}\".${known.size ? ` Use the line ids from bridge_pending_drafts: ${[...known].join(', ')}.` : ' It lists no lines: leave lines out.'}`);\n const line = sanitizeDraftLine(l.line);\n const title = sanitizeDraftTitle(l.title);\n if (line || title) out.set(id, { id, line, ...(title ? { title } : {}) });\n }\n return [...out.values()];\n}\n\n/** A request title kept to the contract: one line, no em dash, sentence case, at most 70 characters, no trailing period. */\nexport function sanitizeDraftTitle(raw: unknown): string {\n if (typeof raw !== 'string') return '';\n const t = clip(cleanDraftText(raw.replace(/[\\r\\n]+/g, ' ')), DRAFT_TITLE_MAX);\n return t.charAt(0).toUpperCase() + t.slice(1);\n}\n\n/**\n * The session with these results added (a result for the same item replaces the earlier one). Results are sanitized.\n * Throws on an unknown item id or an empty result. Status is \"drafted\" once every item has a result.\n */\nexport function mergeDraftResults(p: PendingDrafts, results: DraftResultInput[], at: Date = new Date()): PendingDrafts {\n const ids = new Set(p.items.map((i) => i.id));\n const next = new Map((p.results ?? []).map((r) => [r.id, r]));\n for (const r of results) {\n if (!ids.has(r.id)) throw new Error(`Session ${p.sessionId} has no item \"${r.id}\". Use the ids from bridge_pending_drafts: ${[...ids].join(', ')}.`);\n const item = p.items.find((i) => i.id === r.id)!;\n if (item.scope === 'docs') {\n next.set(r.id, { id: r.id, title: '', summary: '', ...sanitizeDocsResult(item, r), by: 'claude', at: at.toISOString() });\n continue;\n }\n const clean = sanitizeDraftText(r);\n const lines = sanitizeResultLines(item, r.lines);\n if (!clean.title && !clean.summary && !lines.length) throw new Error(`The result for \"${r.id}\" has no title and no summary, and no line.`);\n next.set(r.id, { id: r.id, title: clean.title, summary: clean.summary, ...(lines.length ? { lines } : {}), by: 'claude', at: at.toISOString() });\n }\n const merged = p.items.map((i) => next.get(i.id)).filter((r): r is DraftResult => !!r);\n return { ...p, results: merged, status: merged.length === p.items.length ? 'drafted' : 'pending' };\n}\n\n/** The Markdown brief of one item, for Claude: what to write, the facts, the starting draft. */\nexport function draftItemBrief(i: DraftItem): string {\n if (i.scope === 'docs' && i.docs) {\n const t = i.docs.task;\n const check = t.kind === 'sections' ? (t.check ?? []).filter((k) => t.keys.includes(k)) : [];\n const write = t.kind === 'sections' ? t.keys.filter((k) => !check.includes(k)) : [];\n const what =\n t.kind === 'selection'\n ? `rewrite one passage of the ${t.key} section (${t.mode}), answer with \"replacement\"`\n : [\n write.length ? `${t.rewrite ? 'rewrite' : 'write'} the sections ${write.join(', ')}` : '',\n check.length ? `check the sections ${check.join(', ')} against the code and return one only when something in it is no longer true (leave accurate ones out)` : '',\n ]\n .filter(Boolean)\n .join('; ') + ', answer with \"docs\"';\n return [`Item ${i.id}: component docs${i.component ? ` of ${i.component}` : ''} from Bridge Studio (${i.docs.path ?? i.docs.slug}): ${what}.`, '', i.docs.prompt].join('\\n');\n }\n const kind = i.kind ? REQUEST_KINDS.find((k) => k.value === i.kind)?.label : undefined;\n const cell = (s: string | undefined) => (s ?? '').replace(/\\|/g, '\\\\|').replace(/\\n/g, ' ');\n const lines: string[] = [`Item ${i.id}: ${i.scope === 'request' ? 'a component change request (a GitHub issue developers implement)' : 'the description of a pull request with design token (variable) edits from Figma'}.`];\n if (i.component) lines.push(`Component: ${i.component}`);\n if (kind) lines.push(`Kind: ${kind}`);\n if (i.components?.length) lines.push(`Components with a change request: ${i.components.join(', ')}`);\n if (i.changes.length) lines.push('', '| What | Now | In Figma |', '| --- | --- | --- |', ...i.changes.map((c) => `| ${cell(c.field)} | ${cell(c.before) || 'none'} | ${cell(c.after) || 'removed'} |`));\n if (i.variables?.length) lines.push('', '| Token | Now | In Figma |', '| --- | --- | --- |', ...i.variables.map((v) => `| ${cell(v.path)} | ${cell(v.before) || 'none'} | ${cell(v.after) || 'removed'} |`));\n if (!i.changes.length && !i.variables?.length && !i.lines?.length) lines.push('', 'No change detected: rely on the notes and the images.');\n if (i.draft.title || i.draft.summary) lines.push('', 'Starting draft, written from the changes only:', `Title: ${i.draft.title}`, `Summary: ${i.draft.summary}`);\n if (i.notes?.trim()) lines.push('', 'The designer\\'s notes (keep their intent):', i.notes.trim());\n if (i.lines?.length) {\n lines.push('', `Change lines to write (one sentence each, at most ${DRAFT_LINE_MAX} characters, from the before and after images), each with the title of its request (at most ${DRAFT_TITLE_MAX} characters):`);\n for (const l of i.lines) {\n lines.push(`- Line ${l.id}${l.component ? `, ${l.component}` : ''}${l.kind ? ` (${REQUEST_KINDS.find((k) => k.value === l.kind)?.label ?? l.kind})` : ''}. Starting line: ${l.line || '(none)'}${l.title ? `. Starting title: ${l.title}` : ''}`);\n for (const c of l.changes) lines.push(` - ${c.field}: ${c.before || 'none'} -> ${c.after || 'removed'}`);\n }\n }\n if (i.images?.length) lines.push('', `Images: ${i.images.map((m) => `${m.label}${m.line ? ` (line ${m.line})` : ''} ${m.url}`).join(', ')}`);\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------------------------\n// GitHub: read and write sessions on the requests branch\n\ntype DraftClient = Pick<GitHubClient, 'getFile' | 'putFile' | 'deleteFile' | 'listDirectory'>;\n\nconst isConflict = (err: unknown) => err instanceof GitHubError ? err.status === 409 || (err.status === 422 && /sha/i.test(`${err.detail ?? ''} ${err.message}`)) : (err as { status?: number })?.status === 409;\n\n/** Writes a new session file on the requests branch (the branch must exist). Returns the session. */\nexport async function createPendingDrafts(client: DraftClient, p: PendingDrafts, branch = REQUESTS_BRANCH): Promise<PendingDrafts> {\n const problems = validatePendingDrafts(p);\n if (problems.length) throw new Error(problems.join(' '));\n await client.putFile({ path: draftSessionPath(p.sessionId), content: serializePendingDrafts(p), branch, message: `Bridge drafts: ${p.items.length === 1 ? '1 item' : `${p.items.length} items`} waiting for Claude` });\n return p;\n}\n\n/** One session and its file sha, or undefined when the file is gone (sent, cancelled) or not a session. */\nexport async function readPendingDrafts(client: Pick<GitHubClient, 'getFile'>, sessionId: string, branch = REQUESTS_BRANCH): Promise<{ drafts: PendingDrafts; sha: string } | undefined> {\n const f = await client.getFile(draftSessionPath(sessionId), branch);\n const drafts = parsePendingDrafts(f?.text);\n return f && drafts ? { drafts, sha: f.sha } : undefined;\n}\n\n/** Every valid session on the requests branch, newest first. Unreadable files are skipped. */\nexport async function listPendingDrafts(client: Pick<GitHubClient, 'getFile' | 'listDirectory'>, opts: { status?: DraftSessionStatus | 'all'; branch?: string } = {}): Promise<PendingDrafts[]> {\n const branch = opts.branch ?? REQUESTS_BRANCH;\n const entries = (await client.listDirectory(DRAFTS_DIR, branch)).filter((e) => e.type === 'file' && /\\.json$/.test(e.name));\n const out: PendingDrafts[] = [];\n for (const e of entries) {\n const id = e.name.replace(/\\.json$/, '');\n if (!isDraftSessionId(id)) continue;\n const r = await readPendingDrafts(client, id, branch).catch(() => undefined);\n if (r && r.drafts.sessionId === id) out.push(r.drafts);\n }\n const status = opts.status ?? 'all';\n return out.filter((p) => status === 'all' || p.status === status).sort((a, b) => b.createdAt.localeCompare(a.createdAt));\n}\n\n/**\n * Read, change and write a session with its sha; when someone else wrote it in between (409), read it again and\n * retry, up to `attempts` times. Throws when the session does not exist.\n */\nexport async function updatePendingDrafts(\n client: DraftClient,\n sessionId: string,\n change: (p: PendingDrafts) => PendingDrafts,\n opts: { branch?: string; attempts?: number; message?: string } = {},\n): Promise<PendingDrafts> {\n const branch = opts.branch ?? REQUESTS_BRANCH;\n const attempts = Math.max(1, opts.attempts ?? 3);\n for (let attempt = 1; ; attempt++) {\n const cur = await readPendingDrafts(client, sessionId, branch);\n if (!cur) throw new Error(`No pending drafts for session ${sessionId}: it was sent or cancelled in Figma. Call bridge_pending_drafts for the current ones.`);\n const next = change(cur.drafts);\n try {\n await client.putFile({ path: draftSessionPath(sessionId), content: serializePendingDrafts(next), branch, message: opts.message ?? 'Bridge drafts: update', sha: cur.sha });\n return next;\n } catch (err) {\n if (attempt >= attempts || !isConflict(err)) throw err;\n }\n }\n}\n\n/** Writes Claude's results into a session (sanitized, merged, status \"drafted\" when complete), retrying on 409. */\nexport function writeDraftResults(client: DraftClient, sessionId: string, results: DraftResultInput[], opts: { branch?: string; now?: Date; attempts?: number } = {}): Promise<PendingDrafts> {\n return updatePendingDrafts(client, sessionId, (p) => mergeDraftResults(p, results, opts.now), {\n ...opts,\n message: `Bridge drafts: ${results.length === 1 ? '1 text' : `${results.length} texts`} drafted by Claude`,\n });\n}\n\n/**\n * Removes a session once it was sent or cancelled: its file, then its images (best effort). Returns false when it was\n * already gone.\n */\nexport async function deletePendingDrafts(client: DraftClient, sessionId: string, opts: { branch?: string } = {}): Promise<boolean> {\n const branch = opts.branch ?? REQUESTS_BRANCH;\n const path = draftSessionPath(sessionId);\n const f = await client.getFile(path, branch);\n if (!f) return false;\n await client.deleteFile({ path, branch, message: 'Bridge drafts: done', sha: f.sha });\n const images = await client.listDirectory(`${DRAFTS_DIR}/${sessionId}`, branch).catch(() => []);\n for (const img of images.filter((e) => e.type === 'file')) {\n await client.deleteFile({ path: img.path, branch, message: 'Bridge drafts: done', sha: img.sha }).catch(() => undefined);\n }\n return true;\n}\n\n/** Creates the requests branch from the head of `baseBranch` when it is missing. Never moves an existing branch. */\nexport async function ensureRequestsBranch(client: Pick<GitHubClient, 'getBranchSha' | 'createBranch'>, baseBranch: string): Promise<void> {\n if (await client.getBranchSha(REQUESTS_BRANCH)) return;\n const head = await client.getBranchSha(baseBranch);\n if (!head) throw new Error(`Branch \"${baseBranch}\" was not found, so the ${REQUESTS_BRANCH} branch cannot start from it.`);\n await client.createBranch(REQUESTS_BRANCH, head);\n}\n\nexport interface DocsDraftSessionInput {\n component: string;\n slug: string;\n path?: string | undefined;\n task: DocsDraftTask;\n prompt: string;\n /** Branch the requests branch starts from when it does not exist yet. */\n baseBranch: string;\n now?: Date | undefined;\n random?: (() => number) | undefined;\n}\n\n/**\n * Bridge Studio asks the user's own Claude for component docs: one docs item in a new session (source \"studio\") on\n * the requests branch, created from `baseBranch` when missing. Returns the session to poll.\n */\nexport async function createDocsDraftSession(\n client: Pick<GitHubClient, 'getBranchSha' | 'createBranch' | 'getFile' | 'putFile' | 'deleteFile' | 'listDirectory'>,\n input: DocsDraftSessionInput,\n): Promise<PendingDrafts> {\n await ensureRequestsBranch(client, input.baseBranch);\n const what = input.task.kind === 'selection' ? `Rewrite a passage of ${input.task.key}` : `${input.task.rewrite ? 'Rewrite' : 'Write'} ${input.task.keys.join(', ')}`;\n const item: DraftItem = {\n id: 'docs-1',\n scope: 'docs',\n component: input.component,\n changes: [],\n draft: { title: `${input.component} docs`, summary: what },\n docs: { slug: input.slug, ...(input.path ? { path: input.path } : {}), task: input.task, prompt: input.prompt },\n };\n return createPendingDrafts(client, composePendingDrafts({ items: [item], source: 'studio', now: input.now, random: input.random }));\n}\n\n// ---------------------------------------------------------------------------------------------\n// Polling: the plugin and Studio read the session until Claude answers\n\nexport const DRAFT_POLL_INTERVAL_MS = 5_000;\nexport const DRAFT_POLL_TIMEOUT_MS = 10 * 60_000;\n\nexport interface DraftPollerOptions {\n client: Pick<GitHubClient, 'getFile'>;\n sessionId: string;\n intervalMs?: number | undefined;\n timeoutMs?: number | undefined;\n now?: (() => number) | undefined;\n setTimer?: ((fn: () => void, ms: number) => unknown) | undefined;\n clearTimer?: ((handle: unknown) => void) | undefined;\n /** Claude answered every item. Polling has stopped. */\n onResults: (results: DraftResult[], drafts: PendingDrafts) => void;\n /** No answer within the timeout. Polling has stopped; start() polls again. */\n onTimeout: () => void;\n /** The file is gone (sent or cancelled elsewhere). Polling has stopped. */\n onGone?: (() => void) | undefined;\n /** A read failed; polling goes on. */\n onError?: ((message: string) => void) | undefined;\n}\n\n/** Reads the session every 5 seconds until Claude answers, the file goes away, or 10 minutes pass. */\nexport class DraftPoller {\n private handle: unknown;\n private startedAt = 0;\n private running = false;\n private busy = false;\n\n constructor(private readonly o: DraftPollerOptions) {}\n\n get active(): boolean {\n return this.running;\n }\n\n private now(): number {\n return (this.o.now ?? Date.now)();\n }\n\n private schedule(): void {\n const set = this.o.setTimer ?? ((fn: () => void, ms: number) => setTimeout(fn, ms));\n this.handle = set(() => void this.tick(), this.o.intervalMs ?? DRAFT_POLL_INTERVAL_MS);\n }\n\n /** Starts (or restarts, after a timeout) polling; the timeout counts from now. */\n start(): void {\n this.stop();\n this.running = true;\n this.startedAt = this.now();\n this.schedule();\n }\n\n stop(): void {\n if (this.handle !== undefined) (this.o.clearTimer ?? ((h: unknown) => clearTimeout(h as ReturnType<typeof setTimeout>)))(this.handle);\n this.handle = undefined;\n this.running = false;\n }\n\n private async tick(): Promise<void> {\n if (!this.running) return;\n this.handle = undefined;\n const done = await this.check();\n if (done || !this.running) return;\n if (this.now() - this.startedAt >= (this.o.timeoutMs ?? DRAFT_POLL_TIMEOUT_MS)) {\n this.stop();\n this.o.onTimeout();\n return;\n }\n this.schedule();\n }\n\n /** Reads the file once. True when polling is over (answered or gone). */\n async check(): Promise<boolean> {\n if (this.busy) return false;\n this.busy = true;\n try {\n const cur = await readPendingDrafts(this.o.client, this.o.sessionId);\n if (!cur) {\n this.stop();\n this.o.onGone?.();\n return true;\n }\n if (cur.drafts.status === 'drafted' && cur.drafts.results?.length) {\n this.stop();\n this.o.onResults(cur.drafts.results, cur.drafts);\n return true;\n }\n return false;\n } catch (err) {\n this.o.onError?.(err instanceof Error ? err.message : String(err));\n return false;\n } finally {\n this.busy = false;\n }\n }\n}\n","// Explorations on GitHub: start one (branch from the base with the exploration note, a draft pull request labeled\n// `exploration`), list them, promote one to review, close one. Shared by Studio (in the browser, with the viewer's\n// token), the MCP server and the CLI. The pure rules are in explorations.ts.\n\nimport type { BridgeConfig } from './config';\nimport {\n EXPLORATION_LABEL,\n EXPLORATION_PREFIX,\n explorationNote,\n explorationNotePath,\n explorationPrBody,\n explorationPrTitle,\n explorationProblems,\n explorationSlug,\n explorationStatus,\n explorationTryIt,\n isExplorationPull,\n parseExplorationBody,\n promotionPlan,\n type Exploration,\n type ExplorationSource,\n type ExplorationStatus,\n type ExplorationTryIt,\n type PromotionPlan,\n} from './explorations';\nimport { GitHubError, type GitHubClient, type PullRequestSummary } from './github-client';\nimport { findPreviewComment, previewLinks, previewsSettled, type BranchPreview, type PreviewApps } from './previews';\nimport { branchPreviewUrls } from './previews-github';\n\nexport interface ExplorationSettings {\n /** Branch explorations start from and pull requests target (the default branch). */\n base: string;\n /** Snapshot packages (bridge.config.json previews.packages). */\n packages: string[];\n /** Per-branch preview URL templates (bridge.config.json previews.apps). */\n apps: PreviewApps;\n /** Requests the exploration answers, listed in its draft pull request body. */\n requests?: { number: number; title: string }[] | undefined;\n /** More labels for the draft pull request, such as the product ones (productMarks). */\n labels?: string[] | undefined;\n}\n\nexport interface ExplorationSummary {\n number: number;\n url: string;\n branch: string;\n slug: string;\n name: string;\n purpose: string;\n useCase?: string | undefined;\n status: ExplorationStatus;\n draft: boolean;\n author: string;\n /** Where it was started and the AI agent that started it, when the exploration block says so. */\n source?: ExplorationSource | undefined;\n agent?: string | undefined;\n updatedAt: string;\n /** Head commit of the branch. */\n headSha: string;\n /**\n * Template previews Vercel cannot have shortened (a host label of 63 characters or less), without a round trip. The\n * URLs Vercel reports, with their build state, come from `explorationTestBuildOnGitHub`.\n */\n previews: { app: string; label: string; url: string }[];\n}\n\n/** One exploration from a pull request summary. */\nexport function explorationSummary(p: PullRequestSummary, _owner: string, _repo: string, s: Pick<ExplorationSettings, 'packages' | 'apps'>): ExplorationSummary {\n const e = parseExplorationBody(p.body);\n const slug = p.headRef?.startsWith(EXPLORATION_PREFIX) ? p.headRef.slice(EXPLORATION_PREFIX.length) : (e?.slug ?? explorationSlug(p.title));\n return {\n number: p.number,\n url: p.url,\n branch: p.headRef,\n slug,\n name: e?.name ?? p.title.replace(/^[A-Z][A-Z0-9_]*-\\d+\\s+/, '').replace(/^Exploration:\\s*/i, ''),\n purpose: e?.purpose ?? '',\n ...(e?.useCase ? { useCase: e.useCase } : {}),\n status: explorationStatus({ state: p.state, labels: p.labels, headRef: p.headRef, body: p.body }),\n draft: p.draft,\n author: e?.author ?? p.author,\n ...(e?.source ? { source: e.source } : {}),\n ...(e?.agent ? { agent: e.agent } : {}),\n updatedAt: p.updatedAt,\n headSha: p.headSha,\n previews: previewLinks(s.apps, { branch: p.headRef, pr: p.number, sha: p.headSha }),\n };\n}\n\n/** Explorations of the repo, newest activity first. `state: 'open'` lists the running ones and the promoted open ones. */\nexport async function listExplorationsOnGitHub(gh: GitHubClient, s: Pick<ExplorationSettings, 'packages' | 'apps'>, opts: { state?: 'open' | 'closed' | 'all' } = {}): Promise<ExplorationSummary[]> {\n const pulls = await gh.listPullRequests(opts.state ?? 'open');\n return pulls.filter((p) => isExplorationPull({ state: p.state, labels: p.labels, headRef: p.headRef, body: p.body })).map((p) => explorationSummary(p, gh.owner, gh.name, s));\n}\n\nexport interface StartedExploration {\n branch: string;\n slug: string;\n pr: number;\n url: string;\n commit: string;\n /** Just started: the snapshot is not built yet. `explorationTestBuildOnGitHub` reads the command once it is. */\n tryIt: ExplorationTryIt;\n previews: { app: string; label: string; url: string }[];\n}\n\n/**\n * Starts an exploration: the branch `explore/<slug>` from the base with one commit (the exploration note), a draft\n * pull request labeled `exploration`, then the body rewritten with the pull request number so it carries the\n * install command. Refuses an exploration whose branch already exists.\n */\nexport async function startExplorationOnGitHub(gh: GitHubClient, e: Exploration, s: ExplorationSettings): Promise<StartedExploration> {\n const problems = explorationProblems(e);\n if (problems.length) throw new GitHubError(422, problems.join(' '));\n if (!gh.canWrite) throw new GitHubError(401, 'Starting an exploration needs a GitHub token (contents and pull requests, read and write, on this repository only).');\n const slug = e.slug || explorationSlug(e.name);\n const branch = `${EXPLORATION_PREFIX}${slug}`;\n const x = gh.withBranchPrefix(EXPLORATION_PREFIX);\n if (await x.getBranchSha(branch)) throw new GitHubError(422, `An exploration named \"${slug}\" already exists (${branch}). Pick another name, or continue that one.`);\n const full: Exploration = { ...e, slug, startedAt: e.startedAt ?? new Date().toISOString() };\n const commit = await x.commitToNewBranch({\n base: s.base,\n branch,\n message: `chore(explore): start ${full.name.trim()}\\n\\n${full.purpose.trim()}\\n\\nExploration: never merged as is. Promote it to review or close it.`,\n files: [{ path: explorationNotePath(slug), content: explorationNote(full) }],\n });\n const ctx = { owner: gh.owner, repo: gh.name, packages: s.packages, apps: s.apps, ...(s.requests?.length ? { requests: s.requests } : {}) };\n const title = full.jira ? `${full.jira.trim().toUpperCase()} ${explorationPrTitle(full)}` : explorationPrTitle(full);\n const pr = await x.createPullRequest({ title, head: branch, base: s.base, body: explorationPrBody(full, ctx), draft: true });\n await x.addLabels(pr.number, [EXPLORATION_LABEL, ...(s.labels ?? [])]);\n // The number exists now: the body gets the install command.\n await x.updatePullRequest(pr.number, { body: explorationPrBody(full, { ...ctx, pr: pr.number }) }).catch(() => undefined);\n return {\n branch,\n slug,\n pr: pr.number,\n url: pr.url,\n commit: commit.sha,\n tryIt: { state: 'building' },\n previews: previewLinks(s.apps, { branch, pr: pr.number, sha: commit.sha }),\n };\n}\n\n/**\n * Where the test build of an exploration stands: the install command from its sticky preview comment when it matches\n * the branch head, \"building\" while the workflow has not caught up, \"failed\" when the publish failed. Two reads.\n */\nexport async function explorationTryItOnGitHub(gh: GitHubClient, e: { number: number; branch: string }): Promise<ExplorationTryIt> {\n const [comments, head] = await Promise.all([gh.listIssueComments(e.number), gh.getBranchSha(e.branch).catch(() => undefined)]);\n return explorationTryIt({ comment: findPreviewComment(comments)?.body, headSha: head });\n}\n\nexport interface ExplorationTestBuild {\n /** The install command from the sticky preview comment, or building/failed. Never a guessed command. */\n tryIt: ExplorationTryIt;\n /** Every configured app with the URL Vercel reports (null while unknown) and its build state. */\n previews: BranchPreview[];\n /** True when the command is ready (or the publish failed) and every preview is built: polling can stop. */\n settled: boolean;\n}\n\n/**\n * Everything \"Try it\" shows for an exploration, read in one go: the command from the preview comment and the real\n * preview URLs (deployments, Vercel statuses, the Vercel comment). Comments and the branch head are read once.\n */\nexport async function explorationTestBuildOnGitHub(gh: GitHubClient, e: { number: number; branch: string }, config: Pick<BridgeConfig, 'previews'> | undefined): Promise<ExplorationTestBuild> {\n const [comments, head] = await Promise.all([gh.listIssueComments(e.number), gh.getBranchSha(e.branch).catch(() => undefined)]);\n const tryIt = explorationTryIt({ comment: findPreviewComment(comments)?.body, headSha: head });\n const previews = await branchPreviewUrls(gh, e.number, config, { branch: e.branch, sha: head, comments }).catch(() => [] as BranchPreview[]);\n return { tryIt, previews, settled: tryIt.state !== 'building' && previewsSettled(previews) };\n}\n\n/** The open exploration pull request of a branch, slug or number. */\nexport async function findExplorationOnGitHub(gh: GitHubClient, ref: string | number): Promise<PullRequestSummary & { body: string }> {\n if (typeof ref === 'number' || /^#?\\d+$/.test(String(ref))) {\n const p = await gh.getPullRequest(Number(String(ref).replace(/^#/, '')));\n if (!isExplorationPull({ state: p.state, labels: p.labels, headRef: p.headRef, body: p.body })) throw new GitHubError(422, `Pull request #${p.number} is not an exploration.`);\n return p;\n }\n const branch = `${EXPLORATION_PREFIX}${explorationSlug(String(ref))}`;\n const open = await gh.findOpenPullRequest(branch);\n if (!open) throw new GitHubError(404, `No open exploration on ${branch}. \\`bridge explore list\\` shows the running ones.`);\n return gh.getPullRequest(open.number);\n}\n\nexport interface PromotedExploration extends PromotionPlan {\n number: number;\n url: string;\n branch: string;\n /** Steps that did not go through, with what to do on GitHub instead. */\n warnings: string[];\n}\n\n/**\n * Promotes an exploration to a normal pull request for review: the exploration note removed from the branch, the\n * tier labels from the shared classifier, the `exploration` label removed, the body for review (closing the\n * requests implemented on it), and the draft marked ready for review (GraphQL). Never merges.\n */\nexport async function promoteExplorationOnGitHub(\n gh: GitHubClient,\n ref: string | number,\n opts: { config?: BridgeConfig | undefined; requests?: number[] | undefined; date?: Date | undefined; dryRun?: boolean | undefined } = {},\n): Promise<PromotedExploration> {\n const p = await findExplorationOnGitHub(gh, ref);\n const status = explorationStatus({ state: p.state, labels: p.labels, headRef: p.headRef, body: p.body });\n if (status !== 'active') throw new GitHubError(422, status === 'closed' ? `Exploration #${p.number} is closed. Reopen it on GitHub first.` : `#${p.number} is already promoted to review.`);\n const files = await gh.listPullRequestFiles(p.number);\n const plan = promotionPlan({ title: p.title, body: p.body, labels: p.labels, files: files.map((f) => ({ path: f.filename, status: f.status })), config: opts.config, requests: opts.requests, date: opts.date });\n const out: PromotedExploration = { ...plan, number: p.number, url: p.url, branch: p.headRef, warnings: [] };\n if (opts.dryRun) return out;\n if (!gh.canWrite) throw new GitHubError(401, 'Promoting an exploration needs a GitHub token (contents and pull requests, read and write).');\n const x = gh.withBranchPrefix(EXPLORATION_PREFIX);\n if (plan.removeFiles.length) {\n await x.commitToBranch({ branch: p.headRef, message: 'chore(explore): promote to review, remove the exploration note', files: plan.removeFiles.map((path) => ({ path, content: null })) }).catch((e: Error) => {\n // A refused token is not a partial success: nothing else would go through either.\n if (e instanceof GitHubError && e.auth === 'rejected') throw e;\n out.warnings.push(`The exploration note stays on the branch (${e.message}). Delete ${plan.removeFiles.join(', ')} before merging.`);\n });\n }\n await x.addLabels(p.number, plan.addLabels);\n await x.removeLabel(p.number, EXPLORATION_LABEL).catch((e: Error) => {\n if (!(e instanceof GitHubError && e.status === 404)) out.warnings.push(`The exploration label is still on (${e.message}). Remove it on GitHub.`);\n });\n await x.updatePullRequest(p.number, { title: plan.title, body: plan.body });\n await x.markReadyForReview(p.number).catch((e: Error) => {\n out.warnings.push(`Still a draft: ${e.message}`);\n });\n return out;\n}\n\n/** Closes an exploration without merging. The branch stays for reference; the workflow removes the prerelease. */\nexport async function closeExplorationOnGitHub(gh: GitHubClient, ref: string | number): Promise<{ number: number; url: string; branch: string }> {\n if (!gh.canWrite) throw new GitHubError(401, 'Closing an exploration needs a GitHub token (pull requests: write).');\n const p = await findExplorationOnGitHub(gh, ref);\n await gh.updatePullRequest(p.number, { state: 'closed' });\n return { number: p.number, url: p.url, branch: p.headRef };\n}\n","// Deciding on a component change request on GitHub: link it to an exploration, assign someone, or decline it. The\n// same calls for Studio (the viewer's own token), the MCP server and the CLI. Pure rules live in requests.ts.\nimport { EXPLORATION_LABEL, isExplorationBranch } from './explorations';\nimport { GitHubClient, GitHubError } from './github-client';\nimport { declineComment, declineReasonProblems, withRequestExploration } from './requests';\n\nexport interface RequestExplorationLink {\n number: number;\n branch: string;\n /** Who is now on it, when someone was assigned in the same step. */\n assignees: string[];\n /** Sentences about the parts that did not go through (label refused): the link itself holds. */\n warnings: string[];\n}\n\n/**\n * Links a request to an exploration branch, the way `bridge request create --exploration` files one: the hidden block\n * gets `exploration`, the issue gets the `exploration` label, and whoever starts the exploration is assigned, so the\n * request reads \"in progress\" everywhere. Implementing it then happens on that branch (`request implement --branch`).\n */\nexport async function linkRequestToExplorationOnGitHub(gh: GitHubClient, n: number, branch: string, opts: { assignee?: string | null } = {}): Promise<RequestExplorationLink> {\n if (!isExplorationBranch(branch)) throw new GitHubError(422, `\"${branch}\" is not an exploration branch. Exploration branches are named explore/<name>.`);\n const issue = await gh.getIssue(n);\n const body = withRequestExploration(issue.body, branch);\n if (!body) throw new GitHubError(422, `#${n} has no Bridge request block, so it cannot be linked. Add \"exploration: ${branch}\" to it on GitHub.`);\n await gh.updateIssue(n, { body });\n const warnings: string[] = [];\n if (!(await gh.addLabels(n, [EXPLORATION_LABEL]))) warnings.push(`The ${EXPLORATION_LABEL} label could not be added to #${n}.`);\n let assignees: string[] = [];\n if (opts.assignee) {\n try {\n assignees = await gh.addAssignees(n, [opts.assignee.replace(/^@/, '')]);\n } catch {\n warnings.push(`@${opts.assignee.replace(/^@/, '')} could not be assigned to #${n}.`);\n }\n }\n return { number: n, branch, assignees, warnings };\n}\n\n/** Assigns someone to a request. Throws when GitHub does not keep the assignee (no access to the repository). */\nexport async function assignRequestOnGitHub(gh: GitHubClient, n: number, login: string): Promise<string[]> {\n const who = login.trim().replace(/^@/, '');\n if (!who) throw new GitHubError(422, 'Pick who should work on it.');\n const assignees = await gh.addAssignees(n, [who]);\n if (!assignees.some((a) => a.toLowerCase() === who.toLowerCase())) throw new GitHubError(422, `GitHub did not assign @${who}: they need access to this repository.`);\n return assignees;\n}\n\n/** Declines a request: the reason as a comment the requester is notified of, then the issue closed as not planned. */\nexport async function declineRequestOnGitHub(gh: GitHubClient, n: number, reason: string, by?: string | null): Promise<void> {\n const problems = declineReasonProblems(reason);\n if (problems.length) throw new GitHubError(422, problems.join(' '));\n await gh.addComment(n, declineComment(reason, by));\n await gh.updateIssue(n, { state: 'closed', state_reason: 'not_planned' });\n}\n","// Fidelity check: does a component built in Figma look like the code? Compares a Figma export of one variant with\n// an image of the same variant rendered from code (the Storybook reference images, see fidelity-references.ts).\n// Pure and dependency free: images are plain RGBA buffers, decoded by the caller (a canvas in the plugin, pngjs in\n// Node). The result shapes are JSON so a report can be stored and shown later (Studio Quality, follow-up).\n\n/** An RGBA image, 4 bytes per pixel, row by row (ImageData, pngjs and canvas all use this layout). */\nexport interface RgbaImage {\n width: number;\n height: number;\n data: Uint8Array | Uint8ClampedArray;\n}\n\nexport interface Size {\n width: number;\n height: number;\n}\n\nexport interface CompareOptions {\n /** Export scale of both images (device pixels per CSS pixel). Sizes are reported in CSS pixels. Default 2. */\n scale?: number;\n /**\n * Color distance under which two pixels are the same, 0 to 1 (YIQ, as pixelmatch). Default 0.1: absorbs gamma\n * and antialiasing ramps, catches a token swap (a gray one step away is about 0.12).\n */\n threshold?: number;\n /**\n * Neighborhood, in device pixels, searched for a matching pixel before one counts as different. Figma and Chrome\n * rasterize text and curves differently (glyph hinting, subpixel positions, corner antialiasing): a pixel that has\n * its twin within this distance is the same shape drawn half a pixel away. Default: one CSS pixel (= scale).\n */\n radius?: number;\n /** Largest share of different pixels, in percent, that still matches. Default 3. */\n maxPercent?: number;\n /** Largest size difference per side, in CSS pixels, that still matches. Default 1. */\n sizeTolerance?: number;\n /** Also return the diff overlay. Default true. */\n diffImage?: boolean;\n}\n\nexport interface ImageCompareResult {\n matches: boolean;\n /** Different pixels in percent of the larger canvas, two decimals. */\n percent: number;\n differentPixels: number;\n totalPixels: number;\n /** CSS pixel sizes (image size divided by the scale, rounded). */\n size: { figma: Size; code: Size };\n sizeMatches: boolean;\n /** The code image faded to gray with different pixels in red, on the larger canvas. */\n diff?: RgbaImage | undefined;\n}\n\nexport const FIDELITY_DEFAULTS = { scale: 2, threshold: 0.1, maxPercent: 3, sizeTolerance: 1 } as const;\n\n// Largest YIQ squared distance (black vs white), as in pixelmatch.\nconst MAX_DELTA = 35215;\n// Outside the overlap of two sizes: only near-white (transparent) pixels are the same.\nconst STRICT_THRESHOLD = 0.02;\n\n/** Pixel `i` of an image composited over white, or white outside the image. */\nfunction rgbAt(img: RgbaImage, x: number, y: number): [number, number, number] {\n if (x < 0 || y < 0 || x >= img.width || y >= img.height) return [255, 255, 255];\n const i = (y * img.width + x) * 4;\n const a = img.data[i + 3]! / 255;\n return [255 + (img.data[i]! - 255) * a, 255 + (img.data[i + 1]! - 255) * a, 255 + (img.data[i + 2]! - 255) * a];\n}\n\n/** YIQ squared distance between two opaque colors (pixelmatch's perceptual metric). */\nexport function colorDelta(a: [number, number, number], b: [number, number, number]): number {\n const dr = a[0] - b[0];\n const dg = a[1] - b[1];\n const db = a[2] - b[2];\n const y = dr * 0.29889531 + dg * 0.58662247 + db * 0.11448223;\n const i = dr * 0.59597799 - dg * 0.2741761 - db * 0.32180189;\n const q = dr * 0.21147017 - dg * 0.52261711 + db * 0.31114694;\n return 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q;\n}\n\n/** Whether color `c` appears in `img` within `radius` pixels of (x, y). */\nfunction foundNear(img: RgbaImage, x: number, y: number, c: [number, number, number], radius: number, max: number): boolean {\n for (let dy = -radius; dy <= radius; dy++) for (let dx = -radius; dx <= radius; dx++) if (colorDelta(c, rgbAt(img, x + dx, y + dy)) <= max) return true;\n return false;\n}\n\n/**\n * Compares a Figma export with the code reference of the same variant. A pixel differs when its color is not found\n * near the same place in the other image, in either direction: a shape drawn half a pixel away, or text rasterized\n * a little differently, matches; a missing border, another color, other padding or a different size does not.\n * Pixels outside the smaller image count as transparent: there, any visible color differs (a missing footer is a\n * difference even when its gray is light).\n */\nexport function compareImages(figma: RgbaImage, code: RgbaImage, options: CompareOptions = {}): ImageCompareResult {\n const scale = options.scale ?? FIDELITY_DEFAULTS.scale;\n const radius = Math.max(0, Math.round(options.radius ?? scale));\n const max = MAX_DELTA * (options.threshold ?? FIDELITY_DEFAULTS.threshold) ** 2;\n const strict = MAX_DELTA * STRICT_THRESHOLD ** 2;\n const width = Math.max(figma.width, code.width);\n const height = Math.max(figma.height, code.height);\n const total = width * height;\n const wantDiff = options.diffImage !== false;\n const out = wantDiff ? new Uint8ClampedArray(total * 4) : undefined;\n let different = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const a = rgbAt(figma, x, y);\n const b = rgbAt(code, x, y);\n // Where only one image has pixels (a size difference), any visible color counts: a light surface on white is\n // a missing part, not antialiasing.\n const m = x < Math.min(figma.width, code.width) && y < Math.min(figma.height, code.height) ? max : strict;\n const same = colorDelta(a, b) <= m || (foundNear(code, x, y, a, radius, m) && foundNear(figma, x, y, b, radius, m));\n if (!same) different++;\n if (out) {\n const o = (y * width + x) * 4;\n if (same) {\n // The code image, faded: light gray context for the red marks.\n const gray = 255 + ((b[0] * 0.299 + b[1] * 0.587 + b[2] * 0.114) - 255) * 0.1;\n out[o] = out[o + 1] = out[o + 2] = gray;\n } else {\n out[o] = 220;\n out[o + 1] = 38;\n out[o + 2] = 38;\n }\n out[o + 3] = 255;\n }\n }\n }\n const css = (img: RgbaImage): Size => ({ width: Math.round(img.width / scale), height: Math.round(img.height / scale) });\n const size = { figma: css(figma), code: css(code) };\n const tol = options.sizeTolerance ?? FIDELITY_DEFAULTS.sizeTolerance;\n const sizeMatches = Math.abs(size.figma.width - size.code.width) <= tol && Math.abs(size.figma.height - size.code.height) <= tol;\n const percent = total ? Math.round((different / total) * 10000) / 100 : 0;\n return {\n matches: sizeMatches && percent <= (options.maxPercent ?? FIDELITY_DEFAULTS.maxPercent),\n percent,\n differentPixels: different,\n totalPixels: total,\n size,\n sizeMatches,\n ...(out ? { diff: { width, height, data: out } } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------------------------\n// Report: what a check found, per component and variant. JSON, storable as is.\n\nexport type FidelityVariantStatus = 'matches' | 'differs' | 'skipped';\n\nexport interface FidelityVariantResult {\n /** Variant key, as the plugin stores it (\"Size=md, State=Default, Variant=primary\"). */\n key: string;\n status: FidelityVariantStatus;\n percent?: number | undefined;\n size?: { figma: Size; code: Size } | undefined;\n /** Skipped variants: why there is nothing to compare, in designer words. */\n reason?: string | undefined;\n}\n\nexport type FidelityComponentStatus = 'matches' | 'differs' | 'not-checked';\n\nexport interface FidelityComponentResult {\n component: string;\n status: FidelityComponentStatus;\n checked: number;\n differing: number;\n skipped: number;\n /** The variant that differs most (or matches least well). */\n worst?: { key: string; percent: number; size: { figma: Size; code: Size } } | undefined;\n /** Not checked at all: why. */\n reason?: string | undefined;\n variants: FidelityVariantResult[];\n}\n\nexport interface FidelityReport {\n version: 1;\n checkedAt: string;\n /** Figma file the sets were exported from. */\n file?: string | undefined;\n /** Commit the code images were made from. */\n reference: { sha: string; createdAt: string };\n options: { scale: number; threshold: number; radius: number; maxPercent: number; sizeTolerance: number };\n components: FidelityComponentResult[];\n summary: { components: number; matches: number; differs: number; notChecked: number; variantsChecked: number; variantsSkipped: number };\n}\n\n/** Rolls variant results up into one component result. */\nexport function summarizeComponent(component: string, variants: FidelityVariantResult[], reason?: string): FidelityComponentResult {\n const compared = variants.filter((v) => v.status !== 'skipped');\n const differing = compared.filter((v) => v.status === 'differs');\n const rank = (v: FidelityVariantResult) => (v.status === 'differs' ? 1000 : 0) + (v.percent ?? 0) + (v.size && !sameSize(v.size) ? 500 : 0);\n const worst = [...compared].sort((a, b) => rank(b) - rank(a))[0];\n return {\n component,\n status: compared.length === 0 ? 'not-checked' : differing.length ? 'differs' : 'matches',\n checked: compared.length,\n differing: differing.length,\n skipped: variants.length - compared.length,\n ...(worst && worst.size ? { worst: { key: worst.key, percent: worst.percent ?? 0, size: worst.size } } : {}),\n ...(compared.length === 0 ? { reason: reason ?? variants.find((v) => v.reason)?.reason } : {}),\n variants,\n };\n}\n\nconst sameSize = (s: { figma: Size; code: Size }) => s.figma.width === s.code.width && s.figma.height === s.code.height;\n\nexport function buildFidelityReport(input: {\n components: FidelityComponentResult[];\n reference: { sha: string; createdAt: string };\n options?: CompareOptions;\n file?: string;\n now?: Date;\n}): FidelityReport {\n const o = input.options ?? {};\n const scale = o.scale ?? FIDELITY_DEFAULTS.scale;\n const c = input.components;\n return {\n version: 1,\n checkedAt: (input.now ?? new Date()).toISOString(),\n ...(input.file ? { file: input.file } : {}),\n reference: input.reference,\n options: {\n scale,\n threshold: o.threshold ?? FIDELITY_DEFAULTS.threshold,\n radius: Math.round(o.radius ?? scale),\n maxPercent: o.maxPercent ?? FIDELITY_DEFAULTS.maxPercent,\n sizeTolerance: o.sizeTolerance ?? FIDELITY_DEFAULTS.sizeTolerance,\n },\n components: c,\n summary: {\n components: c.length,\n matches: c.filter((x) => x.status === 'matches').length,\n differs: c.filter((x) => x.status === 'differs').length,\n notChecked: c.filter((x) => x.status === 'not-checked').length,\n variantsChecked: c.reduce((n, x) => n + x.checked, 0),\n variantsSkipped: c.reduce((n, x) => n + x.skipped, 0),\n },\n };\n}\n\nconst fmtPercent = (p: number) => (p >= 10 ? `${Math.round(p)}%` : p >= 1 ? `${Math.round(p * 10) / 10}%` : p > 0 ? 'under 1%' : '0%');\nconst fmtSize = (s: Size) => `${s.width}x${s.height}`;\n\n/** One variant's verdict: \"Matches the code\" or \"Differs from the code: 12% of pixels, size 120x40 vs 118x40\". */\nexport function fidelityVerdict(v: Pick<FidelityVariantResult, 'status' | 'percent' | 'size' | 'reason'>): string {\n if (v.status === 'skipped') return `Not compared: ${v.reason ?? 'no image of the code'}`;\n if (v.status === 'matches') return 'Matches the code';\n const parts = [`${fmtPercent(v.percent ?? 0)} of pixels`];\n if (v.size && !sameSize(v.size)) parts.push(`size ${fmtSize(v.size.figma)} vs ${fmtSize(v.size.code)}`);\n return `Differs from the code: ${parts.join(', ')}`;\n}\n\n/** One component's line, from its worst variant. */\nexport function fidelityComponentLine(c: FidelityComponentResult): string {\n if (c.status === 'not-checked') return `Not compared: ${c.reason ?? 'no image of the code'}`;\n if (c.status === 'matches') return c.checked === 1 ? 'Matches the code' : `Matches the code (${c.checked} variants)`;\n const w = c.worst!;\n const head = fidelityVerdict({ status: 'differs', percent: w.percent, size: w.size });\n return c.checked > 1 ? `${head} (${c.differing} of ${c.checked} variants)` : head;\n}\n","// Code images for the fidelity check: which code render matches each generated Figma variant, and where the images\n// live. The generator (component-specs.ts) draws one Figma variant per axis combination; this module turns that same\n// spec back into props, content and a pseudo state, so the hidden Storybook story \"Internal/Figma reference\" renders\n// what the Figma variant should look like (same texts, icons and width). A variant that cannot be rendered the same\n// way is skipped with a reason, never guessed.\n//\n// Images are made on main by .github/workflows/figma-references.yml (bridge figma-references) and published to the\n// `bridge-visual` branch, the one Visual impact already publishes to, under figma-references/: manifest.json plus one\n// PNG per variant. The plugin reads them through the GitHub contents API with the token it already has.\n\nimport { variantKeyOf, type ComponentSpec, type ComponentSpecsFile, type SpecExample, type SpecPart, type SpecVariant } from './component-spec';\n\nexport const FIGMA_REFERENCES_BRANCH = 'bridge-visual';\nexport const FIGMA_REFERENCES_DIR = 'figma-references';\nexport const FIGMA_REFERENCES_MANIFEST = `${FIGMA_REFERENCES_DIR}/manifest.json`;\n/** Story id of packages/react/src/stories/FigmaReference.stories.tsx. */\nexport const FIGMA_REFERENCE_STORY = 'internal-figma-reference--variant';\n/** Width token of a block-level root in Figma (the plugin draws fill roots at this width: FILL_WIDTH_TOKEN). */\nexport const FIGMA_FILL_WIDTH_TOKEN = 'size.80';\n\nexport type ReferencePseudo = 'hover' | 'active' | 'focus-visible';\n\n/** What the reference story renders for one variant. JSON, passed to the story as a string arg. */\nexport interface ReferenceRender {\n /** Export name of the component (\"Button\", \"Card\"). */\n component: string;\n /** Props from the variant axes and the default property values (\"variant\": \"primary\", \"disabled\": true). */\n props: Record<string, unknown>;\n /** Text children (the Label property) of a simple component. */\n text?: string | undefined;\n /** Compound parts, in order: export name and text (\"CardHeader\", \"Header\"). */\n parts?: { component: string; text: string }[] | undefined;\n /** Icon props -> Lucide icon name (\"icon\": \"Pencil\"). */\n icons?: Record<string, string> | undefined;\n /** Hover, pressed or focus, forced with the pseudo-states addon classes. */\n pseudo?: ReferencePseudo | undefined;\n /** Width token path of the frame the component sits in, for roots that fill their container. */\n width?: string | undefined;\n /**\n * Children from the code example the set was drawn with (a table's rows, a form's fields): texts and design system\n * elements with their props, icons by name. Replaces `text` and `parts`.\n */\n children?: (string | SpecExample)[] | undefined;\n}\n\nexport type ReferencePlan = { ok: true; render: ReferenceRender } | { ok: false; reason: string };\n\nconst STATE_PSEUDO: Record<string, ReferencePseudo | 'rest' | 'disabled'> = {\n default: 'rest',\n rest: 'rest',\n enabled: 'rest',\n hover: 'hover',\n hovered: 'hover',\n pressed: 'active',\n active: 'active',\n focus: 'focus-visible',\n focused: 'focus-visible',\n 'focus visible': 'focus-visible',\n disabled: 'disabled',\n};\n\nconst iconName = (component: string) => component.replace(/^Icon\\//, '');\nconst exportName = (name: string) => name.replace(/[^A-Za-z0-9]+/g, '');\n\n/** How to render one generated variant from code, or why it cannot be compared. */\nexport function planReference(spec: ComponentSpec, variant: SpecVariant, file?: Pick<ComponentSpecsFile, 'slots'>): ReferencePlan {\n // A popup drawn open: the code image shows the component closed, so there is nothing to compare it with.\n if (spec.view === 'popup') return { ok: false, reason: 'drawn open in Figma; the code image shows it closed' };\n const props: Record<string, unknown> = { ...(spec.fixed ?? {}) };\n let pseudo: ReferencePseudo | undefined;\n for (const axis of spec.axes) {\n const value = variant.props[axis.name];\n if (value === undefined) return { ok: false, reason: `the variant has no ${axis.name} value` };\n if (axis.prop) {\n props[axis.prop] = value === 'true' ? true : value === 'false' ? false : value;\n continue;\n }\n // The Checked axis the generator draws from Base UI's checked state: the checked and indeterminate props.\n if (axis.name === 'Checked') {\n props.checked = value === 'true';\n if (value === 'mixed') props.indeterminate = true;\n continue;\n }\n if (axis.name.toLowerCase() !== 'state') return { ok: false, reason: `${axis.name} has no matching option in code` };\n const s = STATE_PSEUDO[value.toLowerCase()];\n if (!s) return { ok: false, reason: `the ${value} state has no code equivalent to render` };\n if (s === 'disabled') props.disabled = true;\n else if (s !== 'rest') pseudo = s;\n }\n\n const root = spec.parts.find((p) => !p.parent);\n if (!root) return { ok: false, reason: 'the spec has no root layer' };\n const children = (id: string) => spec.parts.filter((p) => p.parent === id);\n const textOf = (part: SpecPart): string | { reason: string } => {\n const swapTo = variant.slots?.[part.id] ?? part.swap?.default;\n if (part.swap && swapTo) {\n const slot = file?.slots?.find((s) => s.name === swapTo);\n if (!slot) return { reason: `${swapTo} is not in the specs` };\n if (slot.kind !== 'text' || !slot.text) return { reason: `Figma shows a placeholder (${swapTo}) that code has no example of` };\n return slot.text.default;\n }\n const prop = spec.properties.find((p) => p.name === part.text && p.type === 'TEXT');\n return typeof prop?.default === 'string' ? prop.default : part.name;\n };\n\n let text: string | undefined;\n const icons: Record<string, string> = {};\n for (const prop of spec.properties) {\n if (prop.type === 'TEXT') {\n // Optional content hidden by default (an input's prefix, a description): not passed, as Figma does not show it.\n const hidden = spec.properties.some((b) => b.type === 'BOOLEAN' && b.prop === prop.prop && b.default === false);\n if (hidden && prop.prop) continue;\n if (prop.prop === 'children') text = String(prop.default);\n else if (prop.prop) props[prop.prop] = String(prop.default);\n continue;\n }\n // BOOLEAN: an optional icon shown by default gets its icon below; any other default-on flag is a prop, unless the\n // content it shows is already passed (a description's text, an example's token name).\n const iconPart = spec.parts.find((p) => p.kind === 'icon' && p.visible === prop.name);\n if (prop.default === true && !iconPart && prop.prop && props[prop.prop] === undefined && spec.example?.p?.[prop.prop] === undefined) props[prop.prop] = true;\n }\n\n for (const part of spec.parts) {\n if (part.kind !== 'icon' || !part.swap) continue;\n const shown = part.visible ? spec.properties.find((p) => p.name === part.visible)?.default === true : true;\n if (!shown) continue;\n if (!part.swap.prop) return { ok: false, reason: `the ${part.name} icon has no matching option in code` };\n icons[part.swap.prop] = iconName(variant.slots?.[part.id] ?? part.swap.default);\n }\n\n // Texts that no prop carries: an input's placeholder, or a compound component's parts (CardHeader...).\n let parts: { component: string; text: string }[] | undefined;\n const loose = spec.properties.filter((p) => p.type === 'TEXT' && !p.prop);\n const frames = children(root.id).filter((p) => p.kind === 'frame');\n // Compound parts are frames named like their text (CardHeader's \"Header\") or holding a slot, not a field's box.\n const compound = text === undefined && frames.length > 0 && frames.every((f) => spec.parts.some((p) => p.parent === f.id && p.kind === 'text' && (p.swap || p.text === f.name)));\n if (compound) {\n parts = [];\n for (const f of frames) {\n const t = spec.parts.find((p) => p.parent === f.id && p.kind === 'text')!;\n const value = textOf(t);\n if (typeof value !== 'string') return { ok: false, reason: value.reason };\n parts.push({ component: `${exportName(spec.name)}${exportName(f.name)}`, text: value });\n }\n }\n for (const p of loose) {\n // A value display Base UI writes from the component's value (a progress percentage): code writes it too.\n if (p.name === 'Value') continue;\n const part = spec.parts.find((x) => x.text === p.name);\n if (compound && part && part.parent !== root.id) continue;\n if (part && /placeholder$/.test(part.id)) {\n props.placeholder = String(p.default);\n continue;\n }\n return { ok: false, reason: `the ${p.name} text has no matching option in code` };\n }\n\n // The code example the content came from: its props (the variant's own win) and children.\n const example = spec.example;\n const exampleChildren = example?.children?.length ? example.children : undefined;\n return {\n ok: true,\n render: {\n component: exportName(spec.view || spec.fixed || example ? (example?.c ?? spec.component ?? spec.name) : spec.name),\n props: { ...(example?.p ?? {}), ...props },\n ...(exampleChildren ? { children: exampleChildren } : {}),\n ...(text !== undefined && !exampleChildren ? { text } : {}),\n ...(parts && !exampleChildren ? { parts } : {}),\n ...(Object.keys(icons).length ? { icons } : {}),\n ...(pseudo ? { pseudo } : {}),\n ...(root.fill ? { width: FIGMA_FILL_WIDTH_TOKEN } : {}),\n },\n };\n}\n\n/** File name of a variant's image, stable and file safe: \"button/size-md__state-default__variant-primary.png\". */\nexport function referenceImagePath(component: string, key: string): string {\n const slug = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');\n const file = key\n .split(',')\n .map((kv) => slug(kv))\n .filter(Boolean)\n .join('__');\n return `${slug(component)}/${file || 'default'}.png`;\n}\n\nexport type FigmaReferenceEntry = { file: string; width: number; height: number } | { skipped: string };\n\nexport interface FigmaReferenceManifest {\n version: 1;\n tool: '@bridge-ds/visual';\n createdAt: string;\n /** Commit of the code the images were made from. */\n sha: string;\n /** Device pixels per CSS pixel, the scale the plugin exports Figma variants at. */\n scale: number;\n mode: { brand: string; theme: string; density: string };\n storyId: string;\n components: Record<string, { specHash: string; variants: Record<string, FigmaReferenceEntry> }>;\n}\n\n/** Every variant of every spec with its render plan (the capture's to-do list). */\nexport function planReferences(file: ComponentSpecsFile): { component: string; specHash: string; key: string; plan: ReferencePlan }[] {\n return file.components.flatMap((spec) =>\n spec.variants.map((v) => ({ component: spec.name, specHash: spec.hash, key: variantKeyOf(v.props), plan: planReference(spec, v, file) })),\n );\n}\n","// Review and merge rules shared by Bridge Studio, the MCP server and the CLI: one implementation of who may merge\n// a branch, what blocks it, the owner override and its audit comment, the review queue and the status of a branch.\n// Pure functions over GitHub REST shapes, no fetch, no DOM. Same rules as docs/GOVERNANCE.md: the highest tier wins,\n// Tier 2 and 3 need a design and a tech approval, nothing merges while tests fail. Who may ship comes from\n// `governance.rights` (rights.ts). Moved from the docs site (apps/docs-site/src/lib/review-rules.ts re-exports it).\nimport type { OverridePolicy } from './config';\nimport { isActiveExploration } from './explorations';\nimport { canShip, unreadableShipTeams, whoCanShipSentence, type ShipPolicy } from './rights';\nimport { classifyRisk, type RiskTier } from './risk';\n\nexport interface LabelLike {\n name: string;\n}\n\n/** Tier from labels (`tier-3`, `tier: 3`, `risk:3`), the PR template checkbox (`- [x] Tier 3`) or a `Risk tier: 3` line. Highest wins. */\nexport function parseTier(labels: LabelLike[], body: string | null | undefined): RiskTier | null {\n const found: number[] = [];\n for (const l of labels) {\n const m = l.name.match(/^(?:risk[\\s:-]*)?tier[\\s:_-]*([123])\\b/i) ?? l.name.match(/^risk[\\s:_-]*([123])$/i);\n if (m) found.push(Number(m[1]));\n }\n for (const m of (body ?? '').matchAll(/-\\s*\\[[xX]\\]\\s*\\**\\s*Tier\\s*([123])\\b/g)) found.push(Number(m[1]));\n // \"**Risk tier:** 3, high\" or \"Risk tier: Tier 2\"\n for (const m of (body ?? '').matchAll(/risk tier\\W{0,6}(?:tier\\s*)?([123])\\b/gi)) found.push(Number(m[1]));\n return found.length ? (Math.max(...found) as RiskTier) : null;\n}\n\n/** What GitHub returns about a pull request's lifecycle. `merged_at` is set once merged; `state` is then \"closed\". */\nexport interface PullStateLike {\n state?: string;\n draft?: boolean;\n merged?: boolean;\n merged_at?: string | null;\n}\n\nexport type PullState = 'merged' | 'closed' | 'draft' | 'open';\n\n/** Merged wins over closed (GitHub reports merged pull requests as closed), closed over draft, draft over open. */\nexport function pullState(p: PullStateLike): PullState {\n if (p.merged_at || p.merged) return 'merged';\n if (p.state && p.state !== 'open') return 'closed';\n if (p.draft) return 'draft';\n return 'open';\n}\n\n/** Label and pill tone of each state, for list and detail views. */\nexport const PULL_STATE_PILL: Record<PullState, { label: string; cls: string }> = {\n merged: { label: 'Merged', cls: '' },\n closed: { label: 'Closed', cls: '' },\n draft: { label: 'Draft', cls: '' },\n open: { label: 'Open', cls: '' },\n};\n\n/** Pull requests still waiting for review (open or draft): merged and closed ones never count as open reviews. */\nexport function openPulls<P extends PullStateLike>(pulls: P[]): P[] {\n return pulls.filter((p) => {\n const s = pullState(p);\n return s === 'open' || s === 'draft';\n });\n}\n\nexport interface CiRunLike {\n name: string;\n status: 'queued' | 'in_progress' | 'completed' | string;\n conclusion: string | null;\n html_url?: string;\n}\n\nexport interface CiStatusLike {\n context: string;\n state: 'success' | 'failure' | 'error' | 'pending' | string;\n target_url?: string | null;\n}\n\nexport type CiState = 'pass' | 'fail' | 'pending' | 'none';\n\nexport interface CiSummary {\n state: CiState;\n total: number;\n passed: number;\n failed: { name: string; url?: string }[];\n pending: { name: string; url?: string }[];\n}\n\nconst OK = new Set(['success', 'neutral', 'skipped']);\n\n/** Combines check runs and commit statuses into one verdict. Any failure wins over pending. */\nexport function summarizeCi(runs: CiRunLike[], statuses: CiStatusLike[] = []): CiSummary {\n const failed: CiSummary['failed'] = [];\n const pending: CiSummary['pending'] = [];\n let passed = 0;\n for (const r of runs) {\n if (r.status !== 'completed') pending.push({ name: r.name, url: r.html_url });\n else if (r.conclusion && OK.has(r.conclusion)) passed++;\n else failed.push({ name: r.name, url: r.html_url });\n }\n // Statuses repeat per context; the first one is the latest.\n const seen = new Set<string>();\n for (const s of statuses) {\n if (seen.has(s.context)) continue;\n seen.add(s.context);\n if (s.state === 'success') passed++;\n else if (s.state === 'pending') pending.push({ name: s.context, url: s.target_url ?? undefined });\n else failed.push({ name: s.context, url: s.target_url ?? undefined });\n }\n const total = passed + failed.length + pending.length;\n const state: CiState = total === 0 ? 'none' : failed.length ? 'fail' : pending.length ? 'pending' : 'pass';\n return { state, total, passed, failed, pending };\n}\n\nexport interface ReviewLike {\n user: { login: string } | null;\n state: 'APPROVED' | 'CHANGES_REQUESTED' | 'COMMENTED' | 'DISMISSED' | 'PENDING' | string;\n submitted_at?: string | null;\n}\n\nexport interface ApprovalSummary {\n approvers: string[];\n changesRequested: string[];\n design: boolean;\n tech: boolean;\n}\n\n/** Latest decisive review per person (comments do not reset an approval), then owner coverage. */\nexport function summarizeApprovals(reviews: ReviewLike[], owners: { design: string[]; tech: string[] }, author?: string): ApprovalSummary {\n const latest = new Map<string, string>();\n const sorted = [...reviews].sort((a, b) => String(a.submitted_at ?? '').localeCompare(String(b.submitted_at ?? '')));\n for (const r of sorted) {\n const login = r.user?.login;\n if (!login || login === author) continue;\n if (r.state === 'APPROVED' || r.state === 'CHANGES_REQUESTED' || r.state === 'DISMISSED') latest.set(login, r.state);\n }\n const approvers = [...latest].filter(([, s]) => s === 'APPROVED').map(([l]) => l);\n const changesRequested = [...latest].filter(([, s]) => s === 'CHANGES_REQUESTED').map(([l]) => l);\n const lower = (xs: string[]) => xs.map((x) => x.toLowerCase().replace(/^@/, ''));\n const d = lower(owners.design);\n const t = lower(owners.tech);\n const a = lower(approvers);\n let design: boolean;\n let tech: boolean;\n if (d.length || t.length) {\n design = d.length ? a.some((x) => d.includes(x)) : a.length > 0;\n // One person holding both roles cannot cover both approvals alone.\n const soloBoth = (x: string) => a.length === 1 && d.includes(x);\n tech = t.length ? a.some((x) => t.includes(x) && !soloBoth(x)) : a.length > 1;\n } else {\n // No owners configured: two distinct approvers stand in for design and tech.\n design = a.length >= 1;\n tech = a.length >= 2;\n }\n return { approvers, changesRequested, design, tech };\n}\n\nexport type MissingApproval = 'design approval' | 'tech approval' | 'approval';\n\nexport interface MergeGate {\n allowed: boolean;\n reasons: string[];\n /** True when the only failing reasons are missing approvals and the viewer is in `governance.override.allowed`. */\n overridable: boolean;\n /** Approvals still missing, in the words the override comment uses. */\n missing: MissingApproval[];\n /** Whether the viewer holds the right to ship (true when no rule singles anyone out or the viewer is unknown). */\n canShip: boolean;\n}\n\nconst normLogin = (x: string) => x.trim().toLowerCase().replace(/^@/, '');\n\n/** Whether `login` may use the owner override. Case-insensitive, a leading @ is ignored. */\nexport function canOverride(login: string | null | undefined, policy: OverridePolicy | null | undefined): boolean {\n if (!login || !policy?.allowed.length) return false;\n return policy.allowed.map(normLogin).includes(normLogin(login));\n}\n\n/**\n * Whether the Merge button is enabled, and why not. Mirrors docs/GOVERNANCE.md.\n * The owner override only ever covers missing approvals: CI failing or running, changes requested, a draft,\n * a closed pull request or a merge conflict always block, for everyone.\n */\nexport function mergeGate(input: {\n tier: RiskTier | null;\n ci: CiSummary;\n approvals: ApprovalSummary;\n draft: boolean;\n mergeable?: boolean | null;\n state: string;\n merged_at?: string | null;\n /** Login of the connected viewer (GitHub /user). */\n viewer?: string | null;\n override?: OverridePolicy | null;\n /** A running exploration (label `exploration`): never merged as is, whatever else is green. */\n exploration?: boolean;\n /** Who may ship (shipPolicy from governance.rights). null or absent: anyone with write access. */\n ship?: ShipPolicy | null;\n}): MergeGate {\n const blocking: string[] = [];\n const missing: MissingApproval[] = [];\n const approvalReasons: string[] = [];\n const lifecycle = pullState(input);\n if (lifecycle === 'merged') blocking.push('This branch is already merged.');\n else if (lifecycle === 'closed') blocking.push('This branch is closed.');\n if (input.exploration && lifecycle !== 'merged' && lifecycle !== 'closed') blocking.push('It is an exploration: promote it to review first.');\n if (input.draft) blocking.push('It is a draft. Mark it ready for review on GitHub first.');\n if (input.ci.state === 'fail') blocking.push(`Tests fail: ${input.ci.failed.map((f) => f.name).join(', ')}.`);\n if (input.ci.state === 'pending') blocking.push('Tests are still running.');\n if (input.approvals.changesRequested.length) blocking.push(`Changes requested by @${input.approvals.changesRequested.join(', @')}.`);\n const tier = input.tier ?? 3;\n // docs/GOVERNANCE.md: Tier 2 (new component, variant or prop) and Tier 3 need a design and a tech owner approval.\n if (tier >= 2) {\n if (!input.approvals.design) {\n approvalReasons.push('It needs a design owner approval.');\n missing.push('design approval');\n }\n if (!input.approvals.tech) {\n approvalReasons.push('It needs a tech owner approval.');\n missing.push('tech approval');\n }\n } else if (!input.approvals.approvers.length) {\n approvalReasons.push('It needs one approval.');\n missing.push('approval');\n }\n const conflict = input.mergeable === false ? [CONFLICT_REASON] : [];\n // Only a known viewer is checked: without a login the Merge button asks to connect first anyway.\n const shipper = !input.viewer || canShip(input.viewer, input.ship);\n // A team holding the right that GitHub would not show: say why and how to fix it, never treat it as empty.\n const ship = !shipper && lifecycle !== 'merged' && lifecycle !== 'closed' ? [whoCanShipSentence(input.ship!), ...unreadableShipTeams(input.ship).map((t) => (t.status === 'unreadable' ? t.message : ''))] : [];\n // Order: state, draft, CI, changes requested, approvals, who ships, conflict.\n const reasons = [...blocking, ...approvalReasons, ...ship, ...conflict];\n const allowed = reasons.length === 0;\n // The override skips approvals only: it never lets someone ship who does not hold the right.\n const overridable = !allowed && blocking.length + conflict.length + ship.length === 0 && missing.length > 0 && canOverride(input.viewer, input.override);\n return { allowed, reasons, overridable, missing, canShip: shipper };\n}\n\n/** The gate reason of a conflict, in the words a designer reads. Detected by identity, never by regex. */\nexport const CONFLICT_REASON = 'It conflicts with main: resolve it with Update from main on the branch.';\n\nexport const OVERRIDE_HEADING = '**Bridge owner override**';\n\n/** Problem with an override reason, or null when it is accepted. */\nexport function overrideReasonProblem(reason: string, policy: OverridePolicy): string | null {\n if (!policy.requireReason) return null;\n const n = reason.trim().length;\n if (n === 0) return `Write why this merges without the missing approvals, in at least ${policy.minReasonLength} characters.`;\n if (n < policy.minReasonLength) return `Write at least ${policy.minReasonLength} characters (${n} so far), so the history says why.`;\n return null;\n}\n\n/**\n * The audit comment posted on the pull request before an override merge. Stable format: History and the PR\n * timeline find it by its first line, `**Bridge owner override**`, and read it back with parseOverrideComment.\n */\nexport function overrideComment(login: string, reason: string, missing: MissingApproval[]): string {\n const why = reason.trim().replace(/\\s+/g, ' ').replace(/[.\\s]+$/, '');\n return `${OVERRIDE_HEADING}\\n\\nOwner override by @${normLogin(login)}: ${why || 'no reason given'}. Missing: ${missing.join(', ')}. Merged from Bridge.`;\n}\n\n/** The comment body after GitHub refused the merge, so the audit trail does not claim a merge that never happened. */\nexport function overrideRefusedComment(body: string, message: string): string {\n return body.replace(/ Merged from Bridge\\.$/, ` Merge refused by GitHub: ${message.trim().replace(/[.\\s]+$/, '')}. Not merged.`);\n}\n\nexport interface OverrideRecord {\n login: string;\n reason: string;\n missing: string[];\n merged: boolean;\n}\n\n/** Reads an override comment back; null for any other comment. */\nexport function parseOverrideComment(body: string | null | undefined): OverrideRecord | null {\n const text = (body ?? '').trim();\n if (!text.startsWith(OVERRIDE_HEADING)) return null;\n const m = text.match(/Owner override by @([\\w-]+): ([\\s\\S]*?)\\. Missing: ([^.]*)\\. (Merged from Bridge\\.|Merge refused by GitHub)/);\n if (!m) return null;\n return { login: m[1]!, reason: m[2]!, missing: m[3]!.split(/,\\s*/).filter(Boolean), merged: m[4]!.startsWith('Merged') };\n}\n\nexport type MergeMethod = 'squash' | 'merge' | 'rebase';\n\n/** Merge methods the repo allows, squash first. Unknown settings (no push access) count as allowed. */\nexport function allowedMergeMethods(repo: { allow_squash_merge?: boolean; allow_merge_commit?: boolean; allow_rebase_merge?: boolean } | null | undefined): MergeMethod[] {\n const out: MergeMethod[] = [];\n if (repo?.allow_squash_merge !== false) out.push('squash');\n if (repo?.allow_merge_commit !== false) out.push('merge');\n if (repo?.allow_rebase_merge !== false) out.push('rebase');\n return out;\n}\n\n/** Whether the viewer can write to the repo, from `permissions` on GET /repos/{owner}/{repo} with their token. */\nexport function hasWriteAccess(perms: { admin?: boolean; maintain?: boolean; push?: boolean } | null | undefined): boolean {\n return Boolean(perms && (perms.admin || perms.maintain || perms.push));\n}\n\nexport type ReviewStatusKind =\n | 'merged'\n | 'closed'\n | 'draft'\n | 'ci-failing'\n | 'changes-requested'\n | 'ci-running'\n | 'needs-design'\n | 'needs-tech'\n | 'needs-approval'\n | 'conflict'\n | 'checking'\n | 'ready'\n | 'unknown';\n\n/**\n * Sort order for a \"needs you\" list, most urgent first: what blocks the merge, then what waits for an approval,\n * then what is ready, then running checks and unknown ones, drafts and finished ones last. Lower comes first.\n */\nexport const REVIEW_STATUS_ORDER: Record<ReviewStatusKind, number> = {\n 'ci-failing': 0,\n conflict: 1,\n 'changes-requested': 2,\n 'needs-design': 3,\n 'needs-tech': 4,\n 'needs-approval': 5,\n ready: 6,\n 'ci-running': 7,\n checking: 8,\n unknown: 9,\n draft: 10,\n merged: 11,\n closed: 12,\n};\n\n/**\n * One status chip for a pull request, from real data. Same rules and order as the pull request header\n * (lib/changes needFromDetail): lifecycle, draft, CI failing, changes requested, merge conflict, CI running, then\n * missing approvals (Tier 3 by default), then ready. `mergeable` null means GitHub has not computed it yet: the chip\n * reads \"Checking\" instead of an approval or \"Ready to ship\", so a list never says something the detail contradicts.\n * Undefined means it was not read: no conflict known. `ready` is returned only when mergeGate allows the merge.\n * Unknown CI or reviews (null, still loading or failed) never read as ready.\n */\nexport function reviewStatusKind(input: {\n state?: string;\n draft?: boolean;\n merged_at?: string | null;\n ci: CiSummary | null;\n approvals: ApprovalSummary | null;\n tier: RiskTier | null;\n mergeable?: boolean | null;\n}): ReviewStatusKind {\n const out = (kind: ReviewStatusKind): ReviewStatusKind => kind;\n const lifecycle = pullState(input);\n if (lifecycle === 'merged') return out('merged');\n if (lifecycle === 'closed') return out('closed');\n if (lifecycle === 'draft') return out('draft');\n if (input.ci?.state === 'fail') return out('ci-failing');\n if (input.approvals?.changesRequested.length) return out('changes-requested');\n if (input.mergeable === false) return out('conflict');\n if (input.ci?.state === 'pending') return out('ci-running');\n if (!input.ci || !input.approvals) return out('unknown');\n if (input.mergeable === null) return out('checking');\n const tier = input.tier ?? 3;\n if (tier >= 2) {\n if (!input.approvals.design) return out('needs-design');\n if (!input.approvals.tech) return out('needs-tech');\n } else if (!input.approvals.approvers.length) return out('needs-approval');\n const gate = mergeGate({ tier: input.tier, ci: input.ci, approvals: input.approvals, draft: Boolean(input.draft), mergeable: input.mergeable, state: input.state ?? 'open', merged_at: input.merged_at });\n return gate.allowed ? out('ready') : out('unknown');\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// The review queue: which open pull requests wait for a review. Left out: running explorations (tried, never merged\n// as is) and GitHub automation (the changesets release pull request, anything github-actions[bot] opened).\n\nexport interface QueuePull extends PullStateLike {\n state: string;\n labels?: ({ name?: string } | string)[];\n head: { ref: string };\n user?: { login: string; type?: string } | null;\n}\n\nconst BOTS = new Set(['github-actions[bot]', 'app/github-actions', 'changeset-bot[bot]']);\n\n/** The changesets release pull request (\"Version packages\"), on a changeset-release/* branch. */\nexport const isReleasePull = (p: Pick<QueuePull, 'head'>) => p.head.ref.startsWith('changeset-release/');\n\n/** Opened by GitHub automation, not by a person: the release pull request or anything github-actions[bot] opened. */\nexport function isAutomationPull(p: Pick<QueuePull, 'head' | 'user'>): boolean {\n return isReleasePull(p) || BOTS.has((p.user?.login ?? '').toLowerCase());\n}\n\n/** A running exploration: open and labeled exploration. */\nconst runningExploration = (p: Pick<QueuePull, 'state' | 'labels'>) => p.state === 'open' && isActiveExploration((p.labels ?? []) as never);\n\n/** The open pull requests that wait for a review, in the order given. Every count in the Studio comes from here. */\nexport function reviewQueue<P extends QueuePull>(pulls: P[]): P[] {\n return openPulls(pulls).filter((p) => !isAutomationPull(p) && !runningExploration(p));\n}\n\n/** The open release pull request, if the changesets action opened one. */\nexport function releasePull<P extends QueuePull>(pulls: P[]): P | null {\n return openPulls(pulls).find((p) => isReleasePull(p)) ?? null;\n}\n\n/**\n * The approval a change needs, the same rule everywhere: the tier the author set (label, PR template checkbox or\n * \"Risk tier\" line) or the one the shared classifier computes from the changed files, highest wins. Without files\n * (not read yet) only a label counts, and a missing label stays unknown.\n */\nexport function effectiveTier(labels: LabelLike[], body: string | null | undefined, files: { filename: string; status?: string }[] | null): RiskTier | null {\n const labelled = parseTier(labels, body);\n if (!files) return labelled;\n const computed = classifyRisk({ files: files.map((f) => ({ path: f.filename, status: f.status })) }).tier;\n return Math.max(labelled ?? 0, computed) as RiskTier;\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Reopen\n\nexport type ReopenEligibility =\n /** The branch is still there: the change can be reopened as it was. */\n | { kind: 'reopen' }\n /** The branch is gone: nothing to reopen, but its token edits can start a new change. */\n | { kind: 'gone' }\n /** Not closed, or not the viewer's to reopen, or not known yet. */\n | { kind: 'none' };\n\nconst norm = (x: string) => x.trim().toLowerCase().replace(/^@/, '');\n\n/**\n * Whether the viewer can reopen a closed change: only a change closed without shipping, only its author or an owner\n * (governance.owners, both roles), and only someone GitHub lets write (write access, or the author). `branch` is what\n * GitHub said about the head branch: there, removed, or not read.\n */\nexport function reopenEligibility(x: {\n state: PullState;\n viewer: string | null;\n author: string;\n owners: string[];\n canWrite: boolean;\n branch: 'exists' | 'gone' | 'unknown';\n}): ReopenEligibility {\n if (x.state !== 'closed' || !x.viewer) return { kind: 'none' };\n const isAuthor = norm(x.viewer) === norm(x.author);\n const isOwner = x.owners.some((o) => norm(o) === norm(x.viewer!));\n if (!isAuthor && !isOwner) return { kind: 'none' };\n if (!x.canWrite && !isAuthor) return { kind: 'none' };\n if (x.branch === 'exists') return { kind: 'reopen' };\n if (x.branch === 'gone') return { kind: 'gone' };\n return { kind: 'none' };\n}\n\n\n// ---------------------------------------------------------------------------------------------------------------\n// Who still approves, and who else to ask (\"Ask someone else to review\" in the review queue)\n\nexport type ApprovalRole = 'design' | 'tech' | 'approval';\n\nconst NO_CI: CiSummary = { state: 'pass', total: 0, passed: 0, failed: [], pending: [] };\nconst ROLE_OF_MISSING: Record<MissingApproval, ApprovalRole> = { 'design approval': 'design', 'tech approval': 'tech', approval: 'approval' };\n\n/** The approvals a tier needs, as mergeGate counts them (Tier 2 and 3: design and tech; Tier 1: one approval). */\nexport function requiredApprovals(tier: RiskTier | null): ApprovalRole[] {\n return mergeGate({ tier, ci: NO_CI, approvals: { approvers: [], changesRequested: [], design: false, tech: false }, draft: false, state: 'open' }).missing.map((m) => ROLE_OF_MISSING[m]);\n}\n\n/** The approvals still missing on a branch, from its tier and the reviews read (empty when either is unknown). */\nexport function pendingApprovals(tier: RiskTier | null | undefined, approvals: ApprovalSummary | null | undefined): ApprovalRole[] {\n if (tier == null || !approvals) return [];\n return mergeGate({ tier, ci: NO_CI, approvals, draft: false, state: 'open' }).missing.map((m) => ROLE_OF_MISSING[m]);\n}\n\nconst uniqLogins = (xs: string[]) => xs.filter((x, i) => xs.findIndex((y) => normLogin(y) === normLogin(x)) === i);\n\n/**\n * Who can still give an approval: the owners listed for the role (both lists for a plain approval) minus the author\n * and anyone who already approved. `open`: the config lists nobody for the role, so any reviewer but the author counts.\n */\nexport function eligibleReviewers(role: ApprovalRole, p: { owners: { design: string[]; tech: string[] }; author: string; approvers?: string[] | undefined }): { open: boolean; logins: string[]; listed: string[] } {\n const raw = role === 'design' ? p.owners.design : role === 'tech' ? p.owners.tech : uniqLogins([...p.owners.design, ...p.owners.tech]);\n const listed = raw.map((x) => x.replace(/^@/, ''));\n const approvers = (p.approvers ?? []).map(normLogin);\n const logins = listed.filter((l) => normLogin(l) !== normLogin(p.author) && !approvers.includes(normLogin(l)));\n return { open: listed.length === 0, logins, listed };\n}\n\n/**\n * \"Ask someone else to review\": the other people who can give the missing approvals, never the viewer or the author.\n * Empty when nobody else can (the caller says to review it or to add a reviewer in Settings).\n */\nexport function reviewersToAsk(x: { tier: RiskTier | null; approvals: ApprovalSummary; owners: { design: string[]; tech: string[] }; author: string; viewer: string | null | undefined }): string[] {\n const roles = pendingApprovals(x.tier, x.approvals);\n const all = roles.flatMap((r) => eligibleReviewers(r, { owners: x.owners, author: x.author, approvers: x.approvals.approvers }).logins);\n return uniqLogins(all).filter((l) => normLogin(l) !== normLogin(x.viewer ?? '') && normLogin(l) !== normLogin(x.author));\n}\n","// Update a branch from main (\"bring in the latest library\"), shared by Bridge Studio, the MCP server and the CLI.\n// Reads how far a branch is behind and what both sides touched since they parted; when nothing conflicts, GitHub's\n// update-branch; when only token files conflict, a merge commit with the person's token choices (\"keep mine\" or\n// \"use main's\", core token-merge); anything in code stays with a developer. One implementation over the core\n// GitHub client: Studio passes its own client (studioClient), the MCP server and the CLI theirs.\nimport { loadConfig, DEFAULT_TOKEN_PATHS, type BridgeConfig } from './config';\nimport type { GitHubClient, TreeEntry } from './github-client';\nimport { buildTokenSet, layoutOptions, type LayoutOptions, type TokenSet } from './token-set';\nimport { parseContrastChecks, type ContrastPair } from './wcag';\nimport { applyTokenMerge, choiceFor, planTokenMerge, type MergeChoices, type TokenMergeConflict, type TokenMergeInput, type TokenMergePlan } from './token-merge';\n\nconst plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;\n\n/** A file of a compare (GET /repos/{o}/{r}/compare/{base}...{head}). */\nexport interface CompareFile {\n filename: string;\n status: string;\n previous_filename?: string | undefined;\n sha?: string | null | undefined;\n}\n\n/** Every path a compare file names: a renamed file counts under its old name too. */\nconst names = (files: CompareFile[]) => files.flatMap((f) => (f.previous_filename ? [f.filename, f.previous_filename] : [f.filename]));\n\n/** Files both the branch and main changed since they parted, split into token files and the rest (code). */\nexport function overlap(changeFiles: CompareFile[], libraryFiles: CompareFile[], isTokenFile: (path: string) => boolean): { tokenFiles: string[]; codeFiles: string[] } {\n const lib = new Set(names(libraryFiles));\n const both = [...new Set(names(changeFiles).filter((f) => lib.has(f)))].sort();\n return { tokenFiles: both.filter(isTokenFile), codeFiles: both.filter((f) => !isTokenFile(f)) };\n}\n\n/** GitHub lists at most 300 files per compare: past that, Bridge cannot know what both sides touched. */\nexport const COMPARE_FILE_LIMIT = 300;\n\nexport type ConflictRoute = { kind: 'tokens'; files: string[] } | { kind: 'code'; alsoTokens: boolean; files: string[] };\n\n/**\n * Who resolves the conflict. Only token files on both sides: the designer, in Bridge. Any code file on both sides, a\n * file list GitHub cut short, or no shared file at all (GitHub saw a conflict Bridge cannot explain): a developer.\n */\nexport function conflictRoute(o: { tokenFiles: string[]; codeFiles: string[] }, opts: { truncated?: boolean } = {}): ConflictRoute {\n if (opts.truncated || (!o.tokenFiles.length && !o.codeFiles.length)) return { kind: 'code', alsoTokens: false, files: [] };\n if (o.codeFiles.length) return { kind: 'code', alsoTokens: o.tokenFiles.length > 0, files: o.codeFiles };\n return { kind: 'tokens', files: o.tokenFiles };\n}\n\n/** A rule from GET /repos/{o}/{r}/rules/branches/{branch}. */\nexport interface BranchRuleLike {\n type: string;\n parameters?: { dismiss_stale_reviews_on_push?: boolean } | null;\n}\n\n/**\n * Whether GitHub dismisses approvals when new commits arrive, from the rules that apply to the library branch. True\n * or false when a pull request rule says so; null when no rule says (classic branch protection is not readable\n * without admin rights).\n */\nexport function dismissStaleFrom(rules: BranchRuleLike[] | null | undefined): boolean | null {\n const pr = (rules ?? []).filter((r) => r.type === 'pull_request');\n if (!pr.length) return null;\n return pr.some((r) => r.parameters?.dismiss_stale_reviews_on_push === true);\n}\n\n/** The commit message of the resolution, so History and the branch say what the person chose. */\nexport function resolutionMessage(input: { library: string; conflicts: TokenMergeConflict[]; choices: MergeChoices; who?: string | null | undefined }): string {\n const lines = input.conflicts.map((c) => `- ${c.path} (${c.file}): ${choiceFor(c, input.choices) === 'theirs' ? `used the ${input.library} value` : 'kept this change'}`);\n const title = input.conflicts.length ? `Bring in the latest ${input.library} and resolve ${plural(input.conflicts.length, 'token conflict')}` : `Bring in the latest ${input.library}`;\n const by = input.who ? `\\n\\nResolved in Bridge by @${input.who.replace(/^@/, '')}.` : '\\n\\nResolved in Bridge.';\n return `${title}${lines.length ? `\\n\\n${lines.join('\\n')}` : ''}${by}`;\n}\n\nexport type LibraryState = 'current' | 'behind' | 'conflict' | 'unknown';\n\nexport interface Freshness {\n state: LibraryState;\n /** Library updates (commits on the library branch) since the change started; null when not read. */\n behindBy: number | null;\n /** The commit the change and the library share. */\n mergeBase: string | null;\n}\n\n/**\n * How the change stands against the latest library. A conflict (mergeable false) wins: GitHub cannot combine them.\n * Otherwise it is behind when the library has commits the change has not. A shipped or closed change has nothing to\n * bring in. A compare that could not be read says unknown, never \"up to date\".\n */\nexport function freshness<C extends { behind_by?: number | undefined; merge_base_commit?: { sha: string } | null | undefined }>(input: { compare: C | null | undefined; mergeable: boolean | null | undefined; open: boolean }): Freshness {\n const behindBy = typeof input.compare?.behind_by === 'number' ? input.compare.behind_by : null;\n const mergeBase = input.compare?.merge_base_commit?.sha ?? null;\n if (!input.open) return { state: 'current', behindBy, mergeBase };\n if (input.mergeable === false) return { state: 'conflict', behindBy, mergeBase };\n if (behindBy === null) return { state: 'unknown', behindBy, mergeBase };\n return { state: behindBy > 0 ? 'behind' : 'current', behindBy, mergeBase };\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Reads and writes over the core GitHub client\n\n/** The compare of main and a branch head, in the shape the conflict reader needs (client.compareDetailed). */\nexport interface LibraryCompare {\n mergeBase: string | null;\n baseSha: string | null;\n baseTree: string | null;\n files: CompareFile[];\n}\n\nexport interface LibraryConflicts {\n route: ConflictRoute;\n /** Present for a pure token-file conflict. */\n tokens?: {\n root: string;\n plan: TokenMergePlan;\n input: TokenMergeInput;\n sets: { base: TokenSet; mine: TokenSet; theirs: TokenSet };\n /** Every token file of each side, relative to the tokens root. */\n mineFiles: Record<string, string>;\n theirsFiles: Record<string, string>;\n pairs: ContrastPair[];\n options: LayoutOptions;\n };\n /** What the commit needs: main's tip and its tree, the branch head tree and its own files. */\n write?: { mainSha: string; mainTree: string; headSha: string; headTree: Map<string, TreeEntry>; changeFiles: CompareFile[] };\n}\n\nconst withoutRoot = (root: string, p: string) => (root && p.startsWith(`${root}/`) ? p.slice(root.length + 1) : p);\n\nasync function treeAt(gh: GitHubClient, sha: string): Promise<Map<string, TreeEntry>> {\n const t = await gh.getTree(await gh.getCommitTree(sha));\n if (t.truncated) throw new Error('This repository is too big for Bridge to read in one go. A developer resolves the conflict on GitHub.');\n return new Map(t.entries.filter((e) => e.type === 'blob').map((e) => [e.path, e]));\n}\n\nasync function textAt(gh: GitHubClient, sha: string, path: string): Promise<string> {\n return (await gh.readFile(path, sha)) ?? '';\n}\n\nasync function tokenFilesAt(gh: GitHubClient, sha: string, root: string, tree: Map<string, TreeEntry>): Promise<Record<string, string>> {\n const prefix = root ? `${root}/` : '';\n const paths = [...tree.keys()].filter((p) => p.startsWith(prefix) && p.endsWith('.tokens.json'));\n return Object.fromEntries(await Promise.all(paths.map(async (p) => [withoutRoot(root, p), await textAt(gh, sha, p)] as const)));\n}\n\nasync function configAt(gh: GitHubClient, sha: string, tree: Map<string, TreeEntry>): Promise<BridgeConfig | null> {\n if (!tree.has('bridge.config.json')) return null;\n try {\n return loadConfig(await textAt(gh, sha, 'bridge.config.json'));\n } catch {\n return null;\n }\n}\n\n/**\n * What conflicts and who resolves it. Reads the files main changed since the branch started (one compare), then, for\n * a pure token-file conflict, the token files at the shared start, in the branch and in main. `tokensRoot` is the\n * best guess before the config is read (Studio: its site config); `contrastFallback` the contrast checks to use when\n * main has none.\n */\nexport async function readLibraryConflicts(\n gh: GitHubClient,\n compare: LibraryCompare,\n headSha: string,\n opts: { tokensRoot?: string | undefined; contrastFallback?: string | undefined } = {},\n): Promise<LibraryConflicts> {\n const { mergeBase, baseSha: mainSha, baseTree: mainTree } = compare;\n const changeFiles = compare.files;\n if (!mergeBase || !mainSha || !mainTree) return { route: conflictRoute({ tokenFiles: [], codeFiles: [] }) };\n const library = (await gh.compareDetailed(mergeBase, mainSha)).files;\n const truncated = changeFiles.length >= COMPARE_FILE_LIMIT || library.length >= COMPARE_FILE_LIMIT;\n // The tokens root guess first: the config of main confirms it before anything is written.\n const guess = opts.tokensRoot ?? DEFAULT_TOKEN_PATHS.root;\n const route = conflictRoute(\n overlap(changeFiles, library, (p) => p.endsWith('.tokens.json') && p.startsWith(`${guess}/`)),\n { truncated },\n );\n if (route.kind !== 'tokens') return { route };\n\n const [baseTree, headTree, theirsTree] = await Promise.all([treeAt(gh, mergeBase), treeAt(gh, headSha), treeAt(gh, mainSha)]);\n const config = (await configAt(gh, mainSha, theirsTree)) ?? (await configAt(gh, mergeBase, baseTree));\n const root = config?.tokens.root ?? guess;\n const options = config ? layoutOptions(config) : {};\n const checksPath = `${root}/${config?.tokens.contrastChecks ?? DEFAULT_TOKEN_PATHS.contrastChecks}`;\n const [baseFiles, mineFiles, theirsFiles, checks] = await Promise.all([\n tokenFilesAt(gh, mergeBase, root, baseTree),\n tokenFilesAt(gh, headSha, root, headTree),\n tokenFilesAt(gh, mainSha, root, theirsTree),\n theirsTree.has(checksPath) ? textAt(gh, mainSha, checksPath) : Promise.resolve(''),\n ]);\n const input: TokenMergeInput = { base: baseFiles, mine: mineFiles, theirs: theirsFiles, files: route.files.map((f) => withoutRoot(root, f)) };\n return {\n route,\n tokens: {\n root,\n plan: planTokenMerge(input),\n input,\n sets: { base: buildTokenSet(baseFiles, options), mine: buildTokenSet(mineFiles, options), theirs: buildTokenSet(theirsFiles, options) },\n mineFiles,\n theirsFiles,\n pairs: parseContrastChecks(checks || opts.contrastFallback),\n options,\n },\n write: { mainSha, mainTree, headSha, headTree, changeFiles },\n };\n}\n\n/**\n * Every token file once resolved, relative to the tokens root: main's files, the branch's own token files where only\n * the branch touched them, and the merged files where both did.\n */\nexport function resolvedTokenFiles(data: LibraryConflicts, choices: MergeChoices): { all: Record<string, string>; merged: Record<string, string | null> } {\n const t = data.tokens!;\n const merged = applyTokenMerge(t.input, choices).files;\n const all: Record<string, string> = { ...t.theirsFiles };\n for (const f of data.write!.changeFiles) {\n for (const p of [f.previous_filename, f.filename]) {\n if (!p || !p.endsWith('.tokens.json') || !p.startsWith(`${t.root}/`)) continue;\n const rel = withoutRoot(t.root, p);\n if (rel in merged) continue;\n if (t.mineFiles[rel] === undefined) delete all[rel];\n else all[rel] = t.mineFiles[rel]!;\n }\n }\n for (const [rel, text] of Object.entries(merged)) {\n if (text === null) delete all[rel];\n else all[rel] = text;\n }\n return { all, merged };\n}\n\n/**\n * Commits the resolution to the branch: a merge commit of main and the branch, whose tree is main plus the branch's\n * own files plus the merged token files. Fast-forward only: when the branch moved meanwhile, GitHub refuses and\n * nothing is lost.\n */\nexport async function commitLibraryResolution(\n gh: GitHubClient,\n pull: { head: { ref: string; sha: string }; base: { ref: string } },\n data: LibraryConflicts,\n choices: MergeChoices,\n who: string | null | undefined,\n): Promise<string> {\n const t = data.tokens;\n const w = data.write;\n if (!t || !w) throw new Error('Only a token conflict can be resolved in Bridge. A developer resolves code conflicts on GitHub.');\n if (w.headSha !== pull.head.sha) throw new Error('The branch moved while you were choosing. Read it again and resolve again.');\n const { merged } = resolvedTokenFiles(data, choices);\n const shared = new Set(data.route.files);\n type Entry = { path: string; mode: string; sha: string | null } | { path: string; mode: string; content: string };\n const tree: Entry[] = [];\n for (const f of w.changeFiles) {\n if (shared.has(f.filename)) continue;\n if (f.previous_filename && !shared.has(f.previous_filename)) tree.push({ path: f.previous_filename, mode: '100644', sha: null });\n if (f.status === 'removed') {\n tree.push({ path: f.filename, mode: '100644', sha: null });\n continue;\n }\n const e = w.headTree.get(f.filename);\n if (!e) throw new Error(`Bridge could not read ${f.filename} in the branch. Read it again and try again.`);\n tree.push({ path: e.path, mode: e.mode, sha: e.sha });\n }\n for (const [rel, text] of Object.entries(merged)) {\n const path = t.root ? `${t.root}/${rel}` : rel;\n const mode = w.headTree.get(path)?.mode ?? '100644';\n tree.push(text === null ? { path, mode, sha: null } : { path, mode, content: text });\n }\n const newTree = await gh.createTreeEntries(w.mainTree, tree);\n const message = resolutionMessage({ library: pull.base.ref, conflicts: t.plan.conflicts, choices, who });\n const commit = await gh.createCommit(message, newTree, [w.headSha, w.mainSha]);\n await gh.updateBranch(pull.head.ref, commit);\n return commit;\n}\n","// The writes behind the actions on a branch in review, shared by Bridge Studio (scripts/reviews.ts), the MCP server\n// and the CLI: merge, merge as owner override (reason posted first, marked \"not merged\" when GitHub refuses), review,\n// close and reopen. The rules that decide whether they are allowed live in review-gate.ts; these only write, through\n// the core GitHub client, so every surface sends GitHub the same requests.\nimport type { GitHubClient, Review } from './github-client';\nimport { OVERRIDE_HEADING, overrideComment, overrideRefusedComment, type MergeMethod, type MissingApproval } from './review-gate';\n\n/** Merges a branch at the head the person saw (GitHub refuses when it moved meanwhile). Studio's Merge button: squash. */\nexport async function mergeOnGitHub(gh: GitHubClient, input: { number: number; headSha: string; method?: MergeMethod | undefined }): Promise<{ sha: string }> {\n const r = await gh.mergePullRequest(input.number, { method: input.method ?? 'squash', sha: input.headSha });\n return { sha: r.sha };\n}\n\n/** Where an owner override stopped: GitHub refused the reason comment (nothing merged), or the merge itself. */\nexport class OverrideMergeError extends Error {\n constructor(\n readonly stage: 'comment' | 'merge',\n message: string,\n readonly cause?: unknown,\n readonly commentUrl?: string | undefined,\n ) {\n super(message);\n this.name = 'OverrideMergeError';\n }\n}\n\n/**\n * Merge as owner override: posts the reason on the branch first (the audit trail History reads back), then merges\n * with the first merge method the repository allows. When GitHub refuses the merge, the comment is edited to say\n * \"Merge refused by GitHub ... Not merged\", so the trail never claims a merge that did not happen. The caller checks\n * the gate first (mergeGate: overridable) and the reason (overrideReasonProblem).\n */\nexport async function overrideMergeOnGitHub(\n gh: GitHubClient,\n input: { number: number; headSha: string; login: string; reason: string; missing: MissingApproval[]; method: MergeMethod },\n): Promise<{ sha: string; commentUrl: string; comment: string }> {\n const body = overrideComment(input.login, input.reason, input.missing);\n let comment: { id: number; url: string };\n try {\n comment = await gh.createIssueComment(input.number, body);\n } catch (err) {\n throw new OverrideMergeError('comment', `GitHub did not take the comment, so nothing merged: ${(err as Error).message}`, err);\n }\n try {\n const r = await gh.mergePullRequest(input.number, { method: input.method, sha: input.headSha, commitMessage: body.replace(OVERRIDE_HEADING, '').trim() });\n return { sha: r.sha, commentUrl: comment.url, comment: body };\n } catch (err) {\n const msg = (err as Error).message.trim().replace(/[.\\s]+$/, '');\n await gh.updateIssueComment(comment.id, overrideRefusedComment(body, msg)).catch(() => undefined);\n throw new OverrideMergeError(\n 'merge',\n `GitHub refused to merge it: ${msg}. Your reason stays on the branch, marked not merged. The protection of main may need an approving review or an admin bypass.`,\n err,\n comment.url,\n );\n }\n}\n\nexport type ReviewEvent = 'APPROVE' | 'REQUEST_CHANGES' | 'COMMENT';\n\n/** Approve, request changes or comment, on the head the reviewer saw. Changes and comments need a text. */\nexport async function reviewOnGitHub(gh: GitHubClient, input: { number: number; event: ReviewEvent; body?: string | undefined; headSha?: string | undefined }): Promise<Review> {\n const text = input.body?.trim() ?? '';\n if (input.event === 'REQUEST_CHANGES' && !text) throw new Error('Add a comment that says what to change.');\n if (input.event === 'COMMENT' && !text) throw new Error('Write a comment first.');\n return gh.submitReview(input.number, { event: input.event, body: text || undefined, commitId: input.headSha });\n}\n\n/** A comment on the branch's conversation. */\nexport async function commentOnGitHub(gh: GitHubClient, n: number, body: string): Promise<{ id: number; url: string }> {\n const text = body.trim();\n if (!text) throw new Error('Write the comment first.');\n return gh.createIssueComment(n, text);\n}\n\n/**\n * \"Ask someone else to review\": requests the review from `others` (core reviewersToAsk) and takes the viewer off the\n * requested reviewers when GitHub had them on it. Throws how to fix it when nobody else can.\n */\nexport async function askOthersToReviewOnGitHub(gh: GitHubClient, input: { number: number; others: string[]; viewer?: string | null | undefined; viewerRequested?: boolean | undefined }): Promise<string[]> {\n if (!input.others.length) throw new Error('Nobody else can give the missing approval. Review it, or ask an owner in Settings to add a reviewer.');\n await gh.requestReviewers(input.number, input.others);\n if (input.viewer && input.viewerRequested) await gh.removeRequestedReviewers(input.number, [input.viewer]).catch(() => undefined);\n return input.others;\n}\n\n/** Closes a branch without merging it. Its work stays on GitHub and it can be reopened. */\nexport async function closeOnGitHub(gh: GitHubClient, n: number): Promise<void> {\n await gh.updatePullRequest(n, { state: 'closed' });\n}\n\n/** Reopens a closed branch (GitHub refuses when its branch was deleted). */\nexport async function reopenOnGitHub(gh: GitHubClient, n: number): Promise<void> {\n await gh.updatePullRequest(n, { state: 'open' });\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Adding edits to a branch already in review\n\nconst sameLogin = (a: string | null | undefined, b: string | null | undefined) => Boolean(a && b && a.toLowerCase().replace(/^@/, '') === b.toLowerCase().replace(/^@/, ''));\n\n/** Only the author or someone with write access to the repository adds to a branch. */\nexport function canAddTo(p: { user: { login: string } | null }, viewer: string | null | undefined, write: boolean): boolean {\n if (!viewer) return false;\n return write || sameLogin(p.user?.login, viewer);\n}\n\n/** The comment posted on the branch, so reviewers see what was added and from where. */\nexport function addedComment(paths: string[], viewer: string | null | undefined, from = 'the Bridge token editor'): string {\n const lines = paths.slice(0, 20).map((p) => `- \\`${p}\\``);\n if (paths.length > 20) lines.push(`- and ${paths.length - 20} more`);\n return `${viewer ? `@${viewer} added` : 'Added'} token edits from ${from}:\\n\\n${lines.join('\\n')}`;\n}\n","// Jira ticket keys: an optional \"DS-42\" given when a branch is created (Bridge Studio, the MCP server, the CLI).\n// Jira's GitHub integration links a pull request whose title (or branch name) starts with the key, so the key goes\n// first in both.\n\nconst JIRA_KEY = /^[A-Z][A-Z0-9_]{0,9}-[1-9]\\d{0,6}$/;\n\n/**\n * The Jira key given when a branch is created, normalised (\"ds-42 \" is \"DS-42\"), or null when empty. Throws a\n * sentence that says how to fix it when the text is not a key.\n */\nexport function parseJiraKey(input: string | null | undefined): string | null {\n const t = (input ?? '').trim().toUpperCase();\n if (!t) return null;\n if (!JIRA_KEY.test(t)) throw new Error('Write the Jira ticket as its key, like DS-42, or leave it empty.');\n return t;\n}\n\n/** Whether a text is a Jira key, without throwing (for live field validation). */\nexport const isJiraKey = (input: string) => JIRA_KEY.test(input.trim().toUpperCase());\n\nconst LEADING_KEY = /^\\[?([A-Z][A-Z0-9_]{0,9}-[1-9]\\d{0,6})\\]?[:\\s]\\s*/;\n\n/** The Jira key a title starts with (\"DS-42 tokens: darker primary\" gives \"DS-42\"), else null. */\nexport function jiraKeyOf(title: string): string | null {\n return LEADING_KEY.exec(title.trim())?.[1] ?? null;\n}\n\n/** The title without its leading Jira key. */\nexport const withoutJiraKey = (title: string) => title.trim().replace(LEADING_KEY, '');\n\n/** The pull request title with the key first: \"DS-42 tokens: darker primary\". Idempotent; no key, no change. */\nexport function titleWithJiraKey(title: string, key: string | null): string {\n if (!key) return title;\n return `${key} ${withoutJiraKey(title)}`;\n}\n\n/** The branch name with the key first in its last part: \"tokens/DS-42-darker-primary-20261019-1200\". */\nexport function branchWithJiraKey(branch: string, key: string | null): string {\n if (!key || branch.includes(key)) return branch;\n const i = branch.lastIndexOf('/');\n return i < 0 ? `${key}-${branch}` : `${branch.slice(0, i + 1)}${key}-${branch.slice(i + 1)}`;\n}\n","// Component docs (docs.json) proposed as a reviewable change, shared by the Library edit mode in Bridge Studio, the MCP\n// server and the CLI: what blocks a docs.json (validateDocs), the editor's cleaning, and one pull request per set of\n// docs edits (Tier 1 under the shared classifier, a patch changeset), at most one open per component (a new send\n// continues the open one), and an author line that says who wrote the text. The GitHub writes use the core client.\nimport { formatDocsJson, missingProse, patchDocsJson, type ComponentDocsJson } from './docs-draft';\nimport type { GitHubClient, PullRequestSummary } from './github-client';\nimport { classifyRisk, type RiskResult } from './risk';\nimport { branchWithJiraKey, titleWithJiraKey } from './jira';\n\n/** One component's docs.json, before (null: a new file) and after, at its repo path. */\nexport interface DocsFileEdit {\n path: string;\n component: string;\n slug: string;\n before: string | null;\n after: string;\n}\n\n/** Who wrote the docs, for the pull request body and its source label. */\nexport interface DocsOrigin {\n /** \"in the Bridge docs editor\". */\n where: string;\n footer: string;\n label: string;\n}\n\nexport const DOCS_EDITOR_ORIGIN: DocsOrigin = {\n where: 'in the Bridge docs editor',\n footer: 'Written by a person in the Bridge docs editor. No AI involved in this text.',\n label: 'source: bridge-web',\n};\n\nexport const DOCS_MCP_ORIGIN: DocsOrigin = {\n where: 'with Claude through the Bridge MCP server',\n footer: 'Proposed with the Bridge MCP server on behalf of a person. Docs Claude drafted say \"draftedBy\": \"claude\" until a reviewer accepts them.',\n label: 'source: mcp',\n};\n\nexport interface DocsIssue {\n field: string;\n message: string;\n}\n\nconst EM_DASH = /\\u2014/;\n\n/** What blocks proposing a docs.json: a summary, no empty list items, no em dash (Bridge voice). */\nexport function validateDocs(d: ComponentDocsJson): DocsIssue[] {\n const out: DocsIssue[] = [];\n if (!d.summary.trim()) out.push({ field: 'summary', message: 'Add a summary: one or two sentences on what it is for.' });\n const lists = ['whenToUse', 'whenNotToUse', 'accessibility', 'contentGuidelines'] as const;\n for (const k of lists) (d[k] ?? []).forEach((x, i) => !x.trim() && out.push({ field: `${k}.${i}`, message: 'Fill or remove the empty item.' }));\n for (const k of ['dos', 'donts'] as const) d[k].forEach((g, i) => (!g.title.trim() || !g.text.trim()) && out.push({ field: `${k}.${i}`, message: 'Give every item a title and a sentence.' }));\n const prose = JSON.stringify([d.summary, d.whenToUse, d.whenNotToUse, d.dos, d.donts, d.accessibility, d.contentGuidelines ?? [], d.anatomy ?? {}]);\n if (EM_DASH.test(prose)) out.push({ field: 'voice', message: 'Replace the em dashes with a colon, a comma or two sentences.' });\n return out;\n}\n\n/** Drops empty list items and trims text, the way the editor saves. */\nexport function cleanDocs(d: ComponentDocsJson): ComponentDocsJson {\n const list = (xs: string[] | undefined) => (xs ?? []).map((x) => x.trim()).filter(Boolean);\n const guide = (xs: ComponentDocsJson['dos']) => xs.map((g) => ({ ...g, title: g.title.trim(), text: g.text.trim() })).filter((g) => g.title || g.text);\n return {\n ...d,\n summary: d.summary.trim(),\n whenToUse: list(d.whenToUse),\n whenNotToUse: list(d.whenNotToUse),\n dos: guide(d.dos),\n donts: guide(d.donts),\n accessibility: list(d.accessibility),\n contentGuidelines: list(d.contentGuidelines),\n anatomy: Object.fromEntries(Object.entries(d.anatomy ?? {}).filter(([k, v]) => k.trim() && v.trim())),\n };\n}\n\n/** docs.json in the editor's canonical form: cleaned, in the Button.docs.json key order. Used to compare. */\nexport const docsText = (d: ComponentDocsJson) => formatDocsJson(cleanDocs(d));\n\n/** docs.json text the editor writes: cleaned, as a minimal diff of the file on main (or the branch) when there is one. */\nexport const docsFileText = (d: ComponentDocsJson, original: string | null) => patchDocsJson(original, cleanDocs(d));\n\nexport interface DocsProposal {\n branch: string;\n title: string;\n body: string;\n files: { path: string; content: string }[];\n risk: RiskResult;\n bump: 'patch';\n labels: string[];\n}\n\nconst slugDate = (d: Date) => d.toISOString().slice(0, 10).replace(/-/g, '');\n\n/** The branch slug of a component's docs: \"visually-hidden\" for VisuallyHidden or visually-hidden, at most 40 characters. */\nexport const docsSlug = (nameOrSlug: string) =>\n nameOrSlug\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-')\n .slice(0, 40);\n\n/* ------------------------------------------------------------------------------------------------------------------ */\n/* Who wrote the text */\n\n/** Section names (as the editor shows them) by who wrote their text in this send. */\nexport interface DocsAuthorship {\n /** Drafted by Claude, kept as Claude wrote it after review. */\n claude: string[];\n /** Drafted by Claude, then edited by the person. */\n edited: string[];\n /** Written by the person, no Claude draft involved. */\n written: string[];\n /** Drafted by Claude, not reviewed yet (they go out marked for review). */\n pending: string[];\n}\n\nconst listOf = (xs: string[]) => (xs.length < 2 ? (xs[0] ?? '') : `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`);\n\n/**\n * The author line of a docs proposal: \"by a person, no AI\" only when no Claude draft is in the text; \"drafted by\n * Claude AI, reviewed and sent by @ana\" when the person kept Claude's text as is; \"drafted by Claude AI, edited by\n * @ana\" with the edited sections when they changed parts of it.\n */\nexport function docsAuthorLine(a: DocsAuthorship, who: string | null | undefined, where = 'the Bridge docs editor'): string {\n const w = who?.trim() ? `@${who.trim().replace(/^@/, '')}` : 'a person';\n if (!a.claude.length && !a.edited.length && !a.pending.length) return `Written by ${w} in ${where}. No AI involved in this text.`;\n const head = a.edited.length\n ? `Drafted by Claude AI, edited by ${w} in ${where}.`\n : a.claude.length\n ? `Drafted by Claude AI, reviewed and sent by ${w} in ${where}.`\n : `Drafted by Claude AI, sent by ${w} in ${where} before review.`;\n const mixed = [a.edited, a.written, a.pending].some((x) => x.length);\n return [\n head,\n a.edited.length ? `Edited by ${w}: ${listOf(a.edited)}.` : '',\n a.claude.length && mixed ? `As Claude drafted them: ${listOf(a.claude)}.` : '',\n a.written.length ? `Written by ${w}: ${listOf(a.written)}.` : '',\n a.pending.length && (a.claude.length || a.edited.length || a.written.length) ? `Not reviewed yet: ${listOf(a.pending)}.` : '',\n ]\n .filter(Boolean)\n .join(' ');\n}\n\n/** Without an author line from the editor: the docs' own record (\"draftedBy\": \"claude\") decides, never \"no AI\" over it. */\nexport function defaultDocsFooter(edits: Pick<DocsFileEdit, 'after'>[], origin: DocsOrigin): string {\n if (origin.label !== DOCS_EDITOR_ORIGIN.label) return origin.footer;\n const claude = edits.some((e) => {\n try {\n return (JSON.parse(e.after) as ComponentDocsJson).draftedBy === 'claude';\n } catch {\n return false;\n }\n });\n return claude ? `Drafted by Claude AI (the docs say \"draftedBy\": \"claude\"), sent by a person ${origin.where}.` : origin.footer;\n}\n\n/** The body with its author line (the text after the last \"---\" line) replaced, or added when it has none. */\nexport function withAuthorLine(body: string, line: string): string {\n const i = body.lastIndexOf('\\n---\\n');\n return i < 0 ? `${body.trimEnd()}\\n\\n---\\n${line}` : `${body.slice(0, i + 5)}${line}`;\n}\n\n/* ------------------------------------------------------------------------------------------------------------------ */\n/* One open proposal per component */\n\n/** The open docs proposal of a component: the one a new send continues instead of opening a second one. */\nexport interface OpenDocsProposal {\n number: number;\n url: string;\n branch: string;\n author: string;\n title: string;\n updatedAt: string;\n}\n\nconst escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n/**\n * True when `branch` is a docs proposal branch of this component: docs/<slug>-<yyyymmdd>-<id>, with an optional Jira\n * key before the slug (docs/DS-42-button-...). \"button\" does not match docs/button-group-... branches. Older MCP\n * branches used the lowercased name (docs/visuallyhidden-...): they match too.\n */\nexport function isDocsProposalBranch(branch: string, component: { name: string; slug?: string | undefined }): boolean {\n const slugs = new Set([docsSlug(component.slug ?? component.name), docsSlug(component.name), docsSlug(component.name.toLowerCase())]);\n return [...slugs].some((s) => new RegExp(`^docs/(?:[A-Z][A-Z0-9]*-\\\\d+-)?${escapeRe(s)}-\\\\d{8}-[a-z0-9]+$`).test(branch));\n}\n\ntype PullLike = Pick<PullRequestSummary, 'number' | 'state' | 'headRef' | 'author' | 'title' | 'url' | 'updatedAt'> & { baseRef?: string | undefined };\n\n/** The most recently updated open docs proposal of the component (into `base` when given), or null. */\nexport function findOpenDocsProposal(pulls: PullLike[], component: { name: string; slug?: string | undefined }, base?: string): OpenDocsProposal | null {\n const hit = pulls\n .filter((p) => p.state === 'open' && isDocsProposalBranch(p.headRef, component) && (!base || !p.baseRef || p.baseRef === base))\n .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))[0];\n return hit ? { number: hit.number, url: hit.url, branch: hit.headRef, author: hit.author, title: hit.title, updatedAt: hit.updatedAt } : null;\n}\n\n/** Reads the open pull requests and returns the component's open docs proposal, or null. */\nexport async function findOpenDocsProposalOnGitHub(gh: GitHubClient, component: { name: string; slug?: string | undefined }, base?: string): Promise<OpenDocsProposal | null> {\n return findOpenDocsProposal(await gh.listPullRequests('open'), component, base);\n}\n\n/**\n * Adds a send to the open proposal: one commit with the docs.json on its branch (nothing when the text is the same),\n * and the author line of its description brought up to date. Returns the commit sha, or '' when nothing changed.\n */\nexport async function continueDocsProposalOnGitHub(\n gh: GitHubClient,\n open: Pick<OpenDocsProposal, 'number' | 'branch'>,\n edit: Pick<DocsFileEdit, 'path' | 'component' | 'after'>,\n opts: { authorLine?: string | undefined; message?: string | undefined } = {},\n): Promise<string> {\n const message = opts.message ?? `docs(${docsSlug(edit.component)}): edit usage guidance in the Bridge docs editor`;\n const cur = await gh.getFile(edit.path, open.branch);\n if (cur?.text === edit.after) return '';\n const sha = await gh.putFile({ path: edit.path, content: edit.after, branch: open.branch, message, sha: cur?.sha });\n if (opts.authorLine) {\n const line = opts.authorLine;\n await gh\n .getPullRequest(open.number)\n .then((pr) => gh.updatePullRequest(open.number, { body: withAuthorLine(pr.body, line) }))\n .catch(() => undefined);\n }\n return sha;\n}\n\n/** One pull request for the docs edits of a draft: branch, title, body, files with a patch changeset, the tier. */\nexport function docsProposal(\n edits: DocsFileEdit[],\n opts: { title?: string | undefined; notes?: string | undefined; date: Date; packageName?: string | undefined; changesetDir?: string | undefined; origin?: DocsOrigin | undefined; authorLine?: string | undefined },\n): DocsProposal {\n const origin = opts.origin ?? DOCS_EDITOR_ORIGIN;\n if (!edits.length) throw new Error('No docs edits in the draft.');\n const names = edits.map((e) => e.component);\n const list = names.length === 1 ? names[0]! : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;\n const title = opts.title?.trim() || `docs(${names.length === 1 ? edits[0]!.slug : 'components'}): usage guidance for ${list}`;\n const slug = docsSlug(names.length === 1 ? edits[0]!.slug : `${edits[0]!.slug}-and-${names.length - 1}-more`);\n const branch = `docs/${slug}-${slugDate(opts.date)}-${opts.date.getTime().toString(36).slice(-4)}`;\n const csPath = `${opts.changesetDir ?? '.changeset'}/docs-${slug}-${opts.date.getTime().toString(36)}.md`;\n const pkg = opts.packageName ?? '@bridge-ds/react';\n const changeset = `---\\n\"${pkg}\": patch\\n---\\n\\nUsage guidance for ${list}.\\n`;\n const files = [...edits.map((e) => ({ path: e.path, content: e.after })), { path: csPath, content: changeset }];\n const risk = classifyRisk({ files: files.map((f) => ({ path: f.path, status: 'modified' })) });\n const rows = edits.map((e) => {\n let state = 'edited';\n try {\n const d = JSON.parse(e.after) as ComponentDocsJson;\n const gaps = missingProse(d);\n state = gaps.length ? `still missing: ${gaps.join(', ')}` : 'every section filled';\n } catch {\n state = 'not valid JSON';\n }\n return `- \\`${e.path}\\` (${e.before === null ? 'new' : 'changed'}, ${state})`;\n });\n const body = [\n `## Docs change`,\n '',\n `Usage guidance for ${list}, written ${origin.where}.`,\n '',\n ...rows,\n '',\n `**Risk:** ${risk.label}. Docs only: the published components do not change. Changeset: patch.`,\n '',\n opts.notes?.trim() ? `## Notes\\n\\n${opts.notes.trim()}\\n` : '',\n '---',\n opts.authorLine?.trim() || defaultDocsFooter(edits, origin),\n ]\n .filter((x, i, a) => !(x === '' && a[i - 1] === ''))\n .join('\\n');\n return { branch, title, body, files, risk, bump: 'patch', labels: ['docs', origin.label, `tier-${risk.tier}`] };\n}\n\n\n/**\n * Opens one pull request with the docs edits from the default branch, the Jira key first in the title and the branch\n * name (Jira's GitHub integration links them). Returns its number, link and branch. Labels are best effort.\n * One open proposal per component: when the component already has one, the edit goes there as a new commit\n * (`continued`; `unchanged` when it already says this) instead of a second pull request.\n */\nexport async function proposeDocsOnGitHub(\n gh: GitHubClient,\n edits: DocsFileEdit[],\n opts: {\n base: string;\n title?: string | undefined;\n notes?: string | undefined;\n jira?: string | null | undefined;\n date?: Date | undefined;\n origin?: DocsOrigin | undefined;\n extraLabels?: string[] | undefined;\n commitNote?: string | undefined;\n /** Who wrote the text (docsAuthorLine). Without it, the origin's footer, never \"no AI\" over a Claude draft. */\n authorLine?: string | undefined;\n /** Default true: continue the component's open proposal. False always opens a new one. */\n continueOpen?: boolean | undefined;\n },\n): Promise<{ number: number; url: string; branch: string; title: string; continued: boolean; unchanged: boolean }> {\n if (opts.continueOpen !== false && edits.length === 1) {\n const e = edits[0]!;\n // A failed read does not block the send: it opens a new proposal, as before.\n const open = await findOpenDocsProposalOnGitHub(gh, { name: e.component, slug: e.slug }, opts.base).catch(() => null);\n if (open) {\n const sha = await continueDocsProposalOnGitHub(gh, open, e, { authorLine: opts.authorLine?.trim() || defaultDocsFooter(edits, opts.origin ?? DOCS_EDITOR_ORIGIN) });\n return { number: open.number, url: open.url, branch: open.branch, title: open.title, continued: true, unchanged: !sha };\n }\n }\n const p = docsProposal(edits, { title: opts.title, notes: opts.notes, date: opts.date ?? new Date(), origin: opts.origin, authorLine: opts.authorLine });\n const prTitle = titleWithJiraKey(p.title, opts.jira ?? null);\n const branch = branchWithJiraKey(p.branch, opts.jira ?? null);\n const mainSha = await gh.getBranchSha(opts.base);\n if (!mainSha) throw new Error(`Branch ${opts.base} not found.`);\n const tree = await gh.createTree(await gh.getCommitTree(mainSha), p.files.map((f) => ({ path: f.path, content: f.content })));\n const commit = await gh.createCommit(`${prTitle}\\n\\n${opts.commitNote ?? 'Proposed with the Bridge docs editor.'}`, tree, [mainSha]);\n await gh.createBranch(branch, commit);\n const pr = await gh.createPullRequest({ title: prTitle, head: branch, base: opts.base, body: p.body, draft: false });\n await gh.addLabels(pr.number, [...p.labels, ...(opts.extraLabels ?? [])]).catch(() => false);\n return { number: pr.number, url: pr.url, branch, title: prTitle, continued: false, unchanged: false };\n}\n\n/**\n * Rewrites one file on an open branch in one commit (`next` gets the current text). Returns the commit sha, or ''\n * when nothing changed. The Library editor saves an edited docs.json and accepts a Claude draft this way.\n */\nexport async function commitFileOnGitHub(gh: GitHubClient, input: { path: string; branch: string; message: string; next: (text: string) => string }): Promise<string> {\n const cur = await gh.getFile(input.path, input.branch);\n if (!cur) throw new Error(`${input.path} is not on ${input.branch}. Check the component name and the branch.`);\n const content = input.next(cur.text);\n if (content === cur.text) return '';\n return gh.putFile({ path: input.path, content, branch: input.branch, message: input.message, sha: cur.sha });\n}\n","// \"Share with a product team\" on a branch, shared by Bridge Studio, the MCP server and the CLI: a product team installs the change in its own app before it ships, the\n// designer's release candidate. Everything comes from what the Preview packages workflow\n// (.github/workflows/preview-packages.yml) really does:\n// - every update to an open or draft change builds the library packages (previews.packages in bridge.config.json)\n// and posts the install command in its sticky comment (`<!-- bridge-branch-preview -->`), about two minutes\n// after the update, whether or not the checks pass;\n// - with pkg.pr.new, one snapshot per update, kept after the change ships or closes;\n// - without it (this repository today), tarballs on a `preview-pr-<n>` GitHub prerelease: only the latest update\n// is kept, and the \"Remove the preview prerelease\" job deletes it when the change ships or closes.\n// Nothing is published to the npm registry per change: there is no dist-tag, the command installs by URL.\nimport { readPreviewComment } from './previews';\n\n/** The dialog's explanation, in designer words. */\nexport const SHARE_EXPLAIN = 'Product teams can install this branch in their app before it is merged, and remove it any time.';\n\nexport type ChangeLifecycle = 'open' | 'draft' | 'merged' | 'closed';\ntype Source = 'pkg.pr.new' | 'release' | 'other';\n\nexport type ShareState =\n /** The command for the latest update is posted. */\n | { kind: 'ready'; command: string; source: Source }\n /** No command for the latest update yet. */\n | { kind: 'building' }\n /** The workflow posted for the latest update but could not publish. */\n | { kind: 'failed' }\n /** The change touches none of the preview packages: there is nothing to install. */\n | { kind: 'no-packages' }\n /** Shipped or closed. `stillWorks` from where the preview lived; null when no preview was ever posted. */\n | { kind: 'shipped' | 'closed'; stillWorks: boolean | null; command: string | null };\n\n/** `@bridge-ds/react` -> `packages/react/`, the folder the workflow builds it from (PACKAGE_DIRS). */\nexport const packageDir = (name: string): string => `packages/${name.replace(/^@[^/]+\\//, '')}/`;\n\n/** True when a changed file is inside one of the preview packages. */\nexport function touchesPackages(files: readonly string[], packages: readonly string[]): boolean {\n const dirs = packages.map(packageDir);\n return files.some((f) => dirs.some((d) => f.startsWith(d)));\n}\n\n/**\n * Whether a change offers sharing at all: never from a fork (the workflow cannot publish from one) or when the\n * repository has no preview packages configured.\n */\nexport const canShare = (x: { fromFork: boolean; packages: readonly string[] }): boolean => !x.fromFork && x.packages.length > 0;\n\n/**\n * Where the preview of a change stands, from its lifecycle, its changed files and the sticky preview comment. A\n * comment about an older update than the head means the new one is still being prepared: its command is never shown.\n */\nexport function shareState(x: { lifecycle: ChangeLifecycle; files: readonly string[]; packages: readonly string[]; comment: string | null | undefined; headSha: string }): ShareState {\n // Checked first: a change outside the packages never has anything to install, before or after it ships.\n if (!touchesPackages(x.files, x.packages)) return { kind: 'no-packages' };\n const c = readPreviewComment(x.comment);\n if (x.lifecycle === 'merged' || x.lifecycle === 'closed') {\n const kind = x.lifecycle === 'merged' ? 'shipped' : 'closed';\n if (!c || !c.command || c.source === 'none') return { kind, stillWorks: null, command: null };\n // pkg.pr.new keeps every snapshot; the prerelease is deleted when the change ships or closes.\n return { kind, stillWorks: c.source === 'pkg.pr.new' ? true : c.source === 'release' ? false : null, command: c.command };\n }\n if (!c) return { kind: 'building' };\n if (c.sha7 && !x.headSha.startsWith(c.sha7)) return { kind: 'building' };\n if (!c.command || c.source === 'none') return { kind: 'failed' };\n return { kind: 'ready', command: c.command, source: c.source };\n}\n\n/**\n * Whether the change page shows the action: always while the change is open or a draft (the dialog says why there is\n * nothing to install yet), and after it ships or closes only when a preview was posted that a team may have installed.\n */\nexport const showShare = (lifecycle: ChangeLifecycle, s: ShareState): boolean =>\n lifecycle === 'open' || lifecycle === 'draft' || ((s.kind === 'shipped' || s.kind === 'closed') && !!s.command);\n\n/** The dialog's description: the explanation while the change can still be tried, where it stands once finished. */\nexport const shareDescription = (s: ShareState): string =>\n s.kind === 'shipped' || s.kind === 'closed' ? (stateSentence(s) ?? SHARE_EXPLAIN) : SHARE_EXPLAIN;\n\n/** How a product goes back to the released packages. */\nexport const stableCommand = (packages: readonly string[]): string => `npm i ${packages.map((p) => `${p}@latest`).join(' ')}`;\n\n/** The one sentence the dialog shows under its explanation, in designer words. Null when the message says it all. */\nexport function stateSentence(s: ShareState): string | null {\n switch (s.kind) {\n case 'ready':\n return null;\n case 'building':\n return 'The preview version is being prepared. It is usually ready a couple of minutes after each update to the branch.';\n case 'failed':\n return 'The preview version could not be prepared for the latest update. Update the branch to try again, or ask a developer to run it again on GitHub.';\n case 'no-packages':\n return 'This branch does not touch the library tokens or components, so there is no preview version to install.';\n case 'shipped':\n return s.stillWorks === true\n ? 'This branch was merged. Its preview version still installs, and products get it with the next library release.'\n : s.stillWorks === false\n ? 'This branch was merged, so its preview version was removed. Products get it with the next library release.'\n : 'This branch was merged. Products get it with the next library release.';\n case 'closed':\n return s.stillWorks === true\n ? 'This branch was closed without merging. Its preview version still installs, but it will not reach the library.'\n : s.stillWorks === false\n ? 'This branch was closed without merging, so its preview version was removed.'\n : 'This branch was closed without merging.';\n }\n}\n\nexport interface ShareMessageInput {\n title: string;\n state: ShareState;\n packages: readonly string[];\n /** \"Try it in the product\": the admin preview with this change, when GitHub reports one. */\n tryUrl?: string | null | undefined;\n /** The change on GitHub, for the developer. */\n url: string;\n}\n\nexport interface ShareMessage {\n subject: string;\n body: string;\n}\n\nconst quote = (t: string) => `\"${t.trim().replace(/\"/g, \"'\")}\"`;\n\n/**\n * The ready-to-paste message for a developer of a product team: the change, the preview install command, where to\n * see it first, how long the preview lasts and how to go back. Plain text, for a chat or an email. Null when there is\n * nothing to install and nothing to undo (still building, failed, no packages, or never posted).\n */\nexport function shareMessage(x: ShareMessageInput): ShareMessage | null {\n const back = stableCommand(x.packages);\n const s = x.state;\n if (s.kind === 'ready') {\n const lasts =\n s.source === 'pkg.pr.new'\n ? 'This preview stays available. Each update to the change makes a new one: ask me for the latest command.'\n : 'This preview is replaced on each update to the change and removed when it ships or closes: ask me for the latest command if the install fails.';\n return {\n subject: `Try the design system change ${quote(x.title)} before it ships`,\n body: [\n 'Hi,',\n '',\n `Could you try the design system change ${quote(x.title)} in our product before it ships?`,\n ...(x.tryUrl ? ['', `See it in the demo product first: ${x.tryUrl}`] : []),\n '',\n 'Install the preview version in a staging branch (not production):',\n s.command,\n '',\n lasts,\n '',\n 'To go back to the stable version:',\n back,\n '',\n `Details for developers: ${x.url}`,\n ].join('\\n'),\n };\n }\n if ((s.kind === 'shipped' || s.kind === 'closed') && s.command) {\n const what = s.kind === 'shipped' ? `The design system change ${quote(x.title)} has shipped. You get it with the next library release.` : `The design system change ${quote(x.title)} was closed without shipping.`;\n const preview = s.stillWorks === false ? 'Its preview version was removed, so reinstalling it fails.' : s.stillWorks === true ? 'Its preview version still installs, but it is not the released version.' : '';\n return {\n subject: `Design system change ${quote(x.title)} ${s.kind === 'shipped' ? 'has shipped' : 'was closed'}`,\n body: ['Hi,', '', [what, preview].filter(Boolean).join(' '), '', 'If you installed its preview, go back to the stable version:', back, '', `Details for developers: ${x.url}`].join('\\n'),\n };\n }\n return null;\n}\n\n/** \"Open in email\": a mailto link with the subject and body. Nothing is sent by Studio. */\nexport const mailtoHref = (m: ShareMessage): string => `mailto:?subject=${encodeURIComponent(m.subject)}&body=${encodeURIComponent(m.body.replace(/\\r?\\n/g, '\\r\\n'))}`;\n","// \"Try it in the product\" on a branch, shared by Bridge Studio, the MCP server and the CLI: the product preview Vercel\n// built for the branch, opened with the Bridge toolbar (`?bridge=<number>`, apps/admin/src/bridge) on a given screen.\n// The URL is only one GitHub reported (Vercel commit status, deployment or bot comment), never the config template:\n// Vercel shortens long branch aliases, so a template URL can point nowhere.\nimport { resolveBranchPreviews, type BranchPreviewSources, type PreviewApps } from './previews';\n\nexport interface ProductScreen {\n label: string;\n route: string;\n tenant: string;\n theme: string;\n}\n\n/** The admin preview of a change, or null when GitHub reports none (or the build failed, or it comes from a fork). */\nexport function productPreview(apps: PreviewApps, ctx: { branch: string; pr: number; sha: string; fromFork?: boolean }, sources: BranchPreviewSources): string | null {\n if (!apps.admin || ctx.fromFork) return null;\n const admin = resolveBranchPreviews(apps, { branch: ctx.branch, pr: ctx.pr, sha: ctx.sha }, sources).find((p) => p.app === 'admin');\n if (!admin?.url || admin.source === 'template' || admin.state === 'failed') return null;\n return admin.url;\n}\n\n/** The preview with the toolbar on, at that screen (shop and theme in the query, the hash route ra-core reads), else home. */\nexport function tryInProductUrl(preview: string, pr: number, screen: ProductScreen | null): string {\n const url = new URL(preview);\n url.pathname = '/';\n url.search = '';\n url.searchParams.set('bridge', String(pr));\n if (screen) {\n url.searchParams.set('tenant', screen.tenant);\n url.searchParams.set('theme', screen.theme);\n }\n url.hash = screen ? screen.route : '';\n return url.href;\n}\n","// Try 2 to 4 token branches together, the reads and the rules shared by Bridge Studio, the MCP server and the CLI:\n// which branches can be combined (token files only: code would need a real combined build), each branch's own token\n// edits read from GitHub (its start against its current version, token-combine changeEdits), and where the\n// combination opens (the admin demo with the Bridge toolbar, `?bridge=101,118`). Nothing is written anywhere.\nimport type { GitHubClient } from './github-client';\nimport { changeEdits, encodePicks, type ChangeEdits, type CombinePicks, type CombineSource } from './token-combine';\n\nexport const MIN_TOGETHER = 2;\n\nexport const MAX_TOGETHER = 4;\n\n/**\n * Whether a change only edits tokens: token files under the tokens root, the contrast gate and release notes\n * (changesets). Anything else is code. No file read yet (or none) is not a token change.\n */\nexport function onlyTokens(files: string[], tokensRoot: string): boolean {\n const root = `${tokensRoot.replace(/^\\/+|\\/+$/g, '')}/`;\n return files.length > 0 && files.every((f) => (f.startsWith(root) && f.endsWith('.tokens.json')) || /contrast\\.checks\\.json$/.test(f) || f.startsWith('.changeset/'));\n}\n\n/** Token files a change edits, relative to the tokens root. */\nexport function tokenFilesOf(files: string[], tokensRoot: string): string[] {\n const root = `${tokensRoot.replace(/^\\/+|\\/+$/g, '')}/`;\n return files.filter((f) => f.startsWith(root) && f.endsWith('.tokens.json')).map((f) => f.slice(root.length));\n}\n\n/** A list of changes in an address: \"101,118,120\" (commas stay readable). */\nexport const changeList = (numbers: number[]) => numbers.join(',');\n\n/**\n * The admin demo with the Bridge toolbar on the combination: production (no preview holds all of them), the tokens\n * applied live. `bridge-use` carries the picks.\n */\nexport function tryTogetherUrl(admin: string, numbers: number[], picks: CombinePicks): string {\n const url = new URL(admin);\n url.pathname = '/';\n url.hash = '';\n const use = encodePicks(picks);\n url.search = `?bridge=${changeList(numbers)}${use ? `&bridge-use=${encodeURIComponent(use)}` : ''}`;\n return url.href;\n}\n\n/** GitHub lists at most 300 files per compare: past that, a branch cannot be read whole, so it is not combined. */\nexport const COMBINE_COMPARE_LIMIT = 300;\n\nexport interface CombineBranch {\n number: number;\n title: string;\n /** Only token files (and release notes): it can be combined. */\n tokens: boolean;\n /** Its own token edits; null for a code change. */\n edits: ChangeEdits | null;\n}\n\n/**\n * One branch as the combination needs it: one compare against the default branch (the files it edits since it\n * started, and where it started), then its token files at its start and now. Without a token the client reads the\n * public raw host, so visitors spend no API read on file contents.\n */\nexport async function readCombineBranch(gh: GitHubClient, pull: { number: number; title: string; headSha: string }, opts: { base: string; tokensRoot: string }): Promise<CombineBranch> {\n const compare = await gh.compareDetailed(opts.base, pull.headSha);\n const files = compare.files;\n const names = files.flatMap((f) => (f.previous_filename ? [f.filename, f.previous_filename] : [f.filename]));\n const start = compare.mergeBase;\n if (!start || files.length >= COMBINE_COMPARE_LIMIT || !onlyTokens(names, opts.tokensRoot)) return { number: pull.number, title: pull.title, tokens: false, edits: null };\n const root = opts.tokensRoot.replace(/^\\/+|\\/+$/g, '');\n const tokenFiles = files.filter((f) => tokenFilesOf([f.filename], root).length);\n const source: CombineSource = { number: pull.number, base: {}, head: {}, files: tokenFiles.map((f) => tokenFilesOf([f.filename], root)[0]!) };\n await Promise.all(\n tokenFiles.map(async (f) => {\n const rel = tokenFilesOf([f.filename], root)[0]!;\n source.base[rel] = f.status === 'added' ? undefined : await gh.readFile(f.previous_filename ?? f.filename, start);\n source.head[rel] = f.status === 'removed' ? undefined : await gh.readFile(f.filename, pull.headSha);\n }),\n );\n return { number: pull.number, title: pull.title, tokens: true, edits: changeEdits(source) };\n}\n"],"names":["i","t","modesOf","v","o","r","e","c","m","g","s","idOf","d","k","l","n","names","p","q","tokensPath","norm","cl","STEPS","h","text","cs","cell","shape","plural","at","before","after","by","sentences","MARK","u","quote","code","a","lower"],"mappings":";;;;AA4CA,MAAM,WAAW,CAACA,OAAa,GAAGA,GAAE,IAAI,IAAIA,GAAE,QAAQ,EAAE,IAAIA,GAAE,QAAQ,EAAE,IAAIA,GAAE,SAAS,iBAAiBA,GAAE,UAAU,EAAE;AACtH,MAAM,WAAW,CAAC,SAAkB,SAAS,cAAc,cAAc,gBAAgB,IAAI;AAE7F,MAAM,YAAY,CAACC,OAAoBA,GAAE,SAAS,WAAWA,GAAE,KAAK,WAAW,UAAU;AACzF,MAAM,aAAa,CAACA,OAAoBA,GAAE,SAAS,eAAeA,GAAE,SAAS;AAG7E,SAAS,UAAU,OAAqC,QAA0C;AAChG,UAAQ,MAAM,MAAA;AAAA,IACZ,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH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AK,OAAO,QAAQ,OAAO,OAAO,KAAA;AACnK,QAAM,OAAO,KAAK,WAAW,QAAQ,cAAc,EAAE;AACrD,QAAM,aAAa,MAAM,OAAO,CAAC,MAAM,aAAa,CAAC,EAAE,QAAQ,GAAG,IAAI,EAAE,MAAM;AAC9E,QAAM,SAAwB,EAAE,QAAQ,KAAK,QAAQ,MAAM,CAAA,GAAI,MAAM,CAAA,GAAI,OAAO,WAAW,IAAI,CAAC,MAAM,aAAa,CAAC,EAAE,QAAQ,GAAG,IAAI,EAAE,CAAC,CAAE,EAAA;AAC1I,QAAM,QAAQ;AAAA,IACZ,WAAW,IAAI,OAAO,MAAM;AAC1B,YAAM,MAAM,aAAa,CAAC,EAAE,QAAQ,GAAG,IAAI,EAAE,CAAC;AAC9C,aAAO,KAAK,GAAG,IAAI,EAAE,WAAW,UAAU,SAAY,MAAM,GAAG,SAAS,EAAE,qBAAqB,EAAE,UAAU,KAAK;AAChH,aAAO,KAAK,GAAG,IAAI,EAAE,WAAW,YAAY,SAAY,MAAM,GAAG,SAAS,EAAE,UAAU,KAAK,OAAO;AAAA,IACpG,CAAC;AAAA,EAAA;AAEH,SAAO,EAAE,QAAQ,KAAK,QAAQ,OAAO,KAAK,OAAO,QAAQ,MAAM,OAAO,YAAY,MAAM,EAAA;AAC1F;"}
1
+ {"version":3,"file":"index.js","sources":["../src/validators.ts","../src/id-map.ts","../src/token-merge.ts","../src/token-combine.ts","../src/css-overrides.ts","../src/compose.ts","../src/protection.ts","../src/github-client.ts","../src/protection-github.ts","../src/usage.ts","../src/history-github.ts","../src/history-demo.ts","../src/previews-github.ts","../src/ramps.js","../src/brand.ts","../src/docs-draft.ts","../src/change-drafts.ts","../src/docs-ai.ts","../src/explorations.ts","../src/requests.ts","../src/draft-exchange.ts","../src/explorations-github.ts","../src/requests-github.ts","../src/fidelity.ts","../src/fidelity-references.ts","../src/review-gate.ts","../src/library-update.ts","../src/branch-actions.ts","../src/jira.ts","../src/docs-proposal.ts","../src/share-branch.ts","../src/try-in-product.ts","../src/combine-branches.ts","../src/prod-branch-github.ts","../src/token-proposal.ts"],"sourcesContent":["// Guardrails checked before a PR can be opened. They mirror the repo rules (AGENTS.md,\n// docs/ARCHITECTURE.md \"Token tiers\", docs/GOVERNANCE.md) so designers get the answer in Figma\n// instead of a red CI run later.\n//\n// Tier rules (what each tier may alias):\n// primitive literal values, or another primitive\n// brand an alias to a primitive (palette, radius and font roles re-point raw scales)\n// base a literal or a primitive (motion, layers, icon sizes)\n// semantic an alias, never a literal. Colors alias a Brand palette role (palette.*); translucent\n// primitives (color.alpha.*) are the only raw colors allowed. Non-color semantic tokens\n// (focus ring width, elevation) may alias a primitive or a brand role.\n// density an alias to a primitive (space and size scales)\n// component an alias to a semantic, base, density or brand role token, or a primitive scale step\n// (space, type). Never a raw color ramp or a palette role.\n// Brand x theme overrides follow the semantic rule and must override an existing semantic token.\n\nimport { findReferenceProblems } from './resolver';\nimport { type TokenSet, modesOf } from './token-set';\nimport { type LogicalToken, SINGLE_MODE, TIER_AXIS, TIER_NAMES, type Tier, isMultiMode, modeDisplayName } from './types';\nimport { aliasTarget, collectRefs, isAlias } from './values';\nimport { type ContrastPair, type ContrastResult, contextLabel, contrastScope, evaluatePairs } from './wcag';\n\nexport type IssueCode =\n | 'file-problem'\n | 'raw-value'\n | 'alias-tier'\n | 'broken-reference'\n | 'alias-cycle'\n | 'all-scopes'\n | 'missing-mode'\n | 'override-orphan'\n | 'override-shadowed'\n | 'contrast'\n | 'contrast-unresolved'\n | 'type-change';\n\nexport interface Issue {\n code: IssueCode;\n severity: 'error' | 'warning';\n message: string;\n path?: string | undefined;\n mode?: string | undefined;\n}\n\nconst issueKey = (i: Issue) => `${i.code}|${i.path ?? ''}|${i.mode ?? ''}|${i.code === 'file-problem' ? i.message : ''}`;\nconst modeName = (mode: string) => (mode === SINGLE_MODE ? 'all modes' : modeDisplayName(mode));\n\nconst isPalette = (t: LogicalToken) => t.tier === 'brand' && t.path.startsWith('palette.');\nconst isRawColor = (t: LogicalToken) => t.tier === 'primitive' && t.type === 'color';\n\n/** Why `owner` (in `tier`) may not alias `target`, or undefined when the alias is allowed. */\nfunction aliasRule(owner: { tier: Tier; type: string }, target: LogicalToken): string | undefined {\n switch (owner.tier) {\n case 'primitive':\n case 'base':\n case 'brand':\n case 'density':\n return target.tier === 'primitive' ? undefined : `${TIER_NAMES[owner.tier]} tokens point to primitives only`;\n case 'semantic':\n if (owner.type === 'color') {\n if (isPalette(target)) return undefined;\n if (target.tier === 'primitive' && target.path.startsWith('color.alpha.')) return undefined;\n return 'Semantic colors point to a Brand palette role (palette.*) so every brand can re-map them';\n }\n return target.tier === 'primitive' || target.tier === 'brand' ? undefined : 'Semantic tokens point to a Brand role or a primitive';\n case 'component':\n if (isPalette(target) || isRawColor(target)) return 'Component tokens point to semantic tokens, never to a palette role or a raw color';\n return target.tier === 'component' ? 'Component tokens point to semantic tokens, not to other component tokens' : undefined;\n }\n}\n\n/** Tiers whose values must be aliases. */\nconst MUST_ALIAS: Tier[] = ['brand', 'semantic', 'density', 'component'];\n\nfunction checkValue(set: TokenSet, owner: { path: string; tier: Tier; type: string }, value: unknown, mode: string, where: string, issues: Issue[]): void {\n if (!isAlias(value)) {\n if (MUST_ALIAS.includes(owner.tier) && value !== undefined) {\n issues.push({\n code: 'raw-value',\n severity: 'error',\n path: owner.path,\n mode,\n message: `${owner.path} uses a raw value in ${where}. ${TIER_NAMES[owner.tier]} tokens must point to another variable (pick one instead of typing a value).`,\n });\n }\n return;\n }\n const target = set.byPath.get(aliasTarget(value));\n if (!target) return; // reported as a broken reference\n const why = aliasRule(owner, target);\n if (why) {\n issues.push({\n code: 'alias-tier',\n severity: 'error',\n path: owner.path,\n mode,\n message: `${owner.path} points to ${target.path} (${TIER_NAMES[target.tier]}) in ${where}. ${why}.`,\n });\n }\n}\n\n/** All rule violations in a token set. */\nexport function validateSet(set: TokenSet, pairs: ContrastPair[]): { issues: Issue[]; contrast: ContrastResult[] } {\n const issues: Issue[] = [];\n for (const p of set.problems) issues.push({ code: 'file-problem', severity: 'error', message: p });\n\n for (const t of set.tokens.values()) {\n if (t.scopes?.includes('ALL_SCOPES')) {\n issues.push({\n code: 'all-scopes',\n severity: 'error',\n path: t.path,\n message: `${t.path} is offered in every Figma picker (\"All supported properties\"). Pick the specific properties it is meant for in the variable's scoping settings.`,\n });\n }\n const modes = modesOf(set.layout, t.tier);\n for (const mode of modes) {\n const v = t.values[mode];\n if (v === undefined) {\n if (isMultiMode(t.tier)) {\n issues.push({\n code: 'missing-mode',\n severity: 'error',\n path: t.path,\n mode,\n message: `${t.path} has no value in ${modeName(mode)}. ${TIER_NAMES[t.tier]} tokens must exist in every ${TIER_AXIS[t.tier]}.`,\n });\n }\n continue;\n }\n checkValue(set, t, v, mode, modeName(mode), issues);\n }\n }\n\n for (const o of set.overrides) {\n const mode = `${o.brand}.${o.theme}`;\n const where = `${modeDisplayName(o.brand)} ${o.theme} (${o.file})`;\n const base = set.byPath.get(o.path);\n if (!base || base.tier !== 'semantic') {\n issues.push({\n code: 'override-orphan',\n severity: 'error',\n path: o.path,\n mode,\n message: `${o.file} overrides ${o.path}, which is not a semantic token. Remove the override or restore the token.`,\n });\n continue;\n }\n checkValue(set, { path: o.path, tier: 'semantic', type: base.type }, o.value, mode, where, issues);\n for (const ref of collectRefs(o.value)) {\n if (!set.byPath.has(ref)) issues.push({ code: 'broken-reference', severity: 'error', path: o.path, mode, message: `${o.path} points to ${ref}, which does not exist (${where}).` });\n }\n }\n\n const axes = { brand: modesOf(set.layout, 'brand'), theme: modesOf(set.layout, 'semantic'), density: modesOf(set.layout, 'density') };\n for (const p of findReferenceProblems(set.byPath, axes)) {\n issues.push(\n p.kind === 'broken'\n ? {\n code: 'broken-reference',\n severity: 'error',\n path: p.path,\n mode: p.mode,\n message: `${p.path} points to ${p.target}, which does not exist (${modeName(p.mode)}).`,\n }\n : {\n code: 'alias-cycle',\n severity: 'error',\n path: p.path,\n mode: p.mode,\n message: `${p.path} is part of a loop of references: ${p.chain.join(' -> ')} (${modeName(p.mode)}).`,\n },\n );\n }\n\n const contrast = evaluatePairs(set.byPath, pairs, contrastScope(set));\n for (const r of contrast) {\n const path = `${r.pair.foreground} on ${r.pair.background}`;\n const mode = `${r.brand ?? ''}.${r.theme}`;\n if (r.error) {\n issues.push({ code: 'contrast-unresolved', severity: 'warning', path, mode, message: `Contrast of ${path} in ${contextLabel(r)} cannot be checked: ${r.error}.` });\n } else if (r.level === 'fail') {\n issues.push({\n code: 'contrast',\n severity: 'error',\n path,\n mode,\n message: `${path} is ${r.ratio}:1 in ${contextLabel(r)}; contrast.checks.json needs ${r.pair.min}:1 (WCAG AA ${r.pair.kind === 'ui' ? 'for interface elements' : 'for text'}).`,\n });\n }\n }\n return { issues, contrast };\n}\n\nexport interface TypeChange {\n path: string;\n from: string;\n to: string;\n}\n\nexport interface ProposalValidation {\n /** Problems this change introduces. They disable the PR button. */\n blocking: Issue[];\n /** Problems that already exist on main, or soft checks. Shown, not blocking. */\n warnings: Issue[];\n contrastBefore: ContrastResult[];\n contrastAfter: ContrastResult[];\n}\n\n/**\n * Semantic edits that some brand does not see because it overrides that token for the theme\n * (brands/<brand>.<theme>.tokens.json). Not an error: a heads-up that the edit is partial.\n */\nexport function shadowedEdits(set: TokenSet, edits: { path: string; tier: Tier; modes: string[] }[]): Issue[] {\n const out: Issue[] = [];\n for (const e of edits) {\n if (e.tier !== 'semantic') continue;\n for (const o of set.overrides) {\n if (o.path !== e.path || !e.modes.includes(o.theme)) continue;\n out.push({\n code: 'override-shadowed',\n severity: 'warning',\n path: e.path,\n mode: `${o.brand}.${o.theme}`,\n message: `${e.path} is overridden for ${modeDisplayName(o.brand)} in ${o.theme} (${o.file}), so this edit does not change ${modeDisplayName(o.brand)} ${o.theme}. Brand overrides stay code-only.`,\n });\n }\n }\n return out;\n}\n\n/**\n * Validate the files a PR would produce. Errors already present on main are reported as warnings\n * so an unrelated, pre-existing problem does not block a designer's change; everything the change\n * introduces blocks.\n */\nexport function validateProposal(proposed: TokenSet, head: TokenSet, pairs: ContrastPair[], typeChanges: TypeChange[] = []): ProposalValidation {\n const after = validateSet(proposed, pairs);\n const before = validateSet(head, pairs);\n const existing = new Set(before.issues.map(issueKey));\n const blocking: Issue[] = [];\n const warnings: Issue[] = [];\n for (const i of after.issues) {\n if (i.severity === 'warning') warnings.push(i);\n else if (existing.has(issueKey(i))) warnings.push({ ...i, severity: 'warning', message: `Already on main: ${i.message}` });\n else blocking.push(i);\n }\n for (const c of typeChanges) {\n blocking.push({\n code: 'type-change',\n severity: 'error',\n path: c.path,\n message: `${c.path} changed type from ${c.from} to ${c.to}. Type changes are not allowed; create a new token instead.`,\n });\n }\n return { blocking, warnings, contrastBefore: before.contrast, contrastAfter: after.contrast };\n}\n","// Stable identity of tokens across renames.\n//\n// Every variable DS Bridge writes carries a token id in its plugin data. The id is the token's\n// `$extensions[\"com.dsbridge.id\"]` when the file declares one, otherwise \"path:<path>\". Matching is\n// by id first, so renaming a variable in Figma is a rename, not a delete plus an add. Only renamed\n// (or re-identified) tokens get the extension written into Git, which keeps the files lean.\n//\n// Variables created in Figma have no id. They are matched by name, then, as a last resort, a\n// heuristic proposes \"this looks like a rename\" (same type, same values, similar path). Heuristic\n// matches are suggestions only: the user confirms each one.\n\nimport { pathId } from './token-set';\nimport type { LogicalToken } from './types';\nimport { valuesEqual } from './values';\n\nexport interface RenameSuggestion {\n /** Id the Figma variable currently has (derived from its new name). */\n figmaId: string;\n /** Id of the Git token it probably is. */\n gitId: string;\n fromPath: string;\n toPath: string;\n similarity: number;\n}\n\nexport interface ReconcileResult {\n tokens: LogicalToken[];\n /** Figma tokens that adopted a Git id because their names matched (no plugin data yet). */\n adoptedByName: string[];\n suggestions: RenameSuggestion[];\n}\n\nexport function levenshtein(a: string, b: string): number {\n const prev = Array.from({ length: b.length + 1 }, (_, i) => i);\n for (let i = 1; i <= a.length; i++) {\n let diag = prev[0]!;\n prev[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const tmp = prev[j]!;\n prev[j] = Math.min(prev[j]! + 1, prev[j - 1]! + 1, diag + (a[i - 1] === b[j - 1] ? 0 : 1));\n diag = tmp;\n }\n }\n return prev[b.length]!;\n}\n\nexport function pathSimilarity(a: string, b: string): number {\n const ratio = 1 - levenshtein(a, b) / Math.max(a.length, b.length, 1);\n const leafA = a.slice(a.lastIndexOf('.') + 1);\n const leafB = b.slice(b.lastIndexOf('.') + 1);\n return leafA === leafB ? Math.max(ratio, 0.75) : ratio;\n}\n\nexport const SIMILARITY_THRESHOLD = 0.5;\n\nfunction sameContent(a: LogicalToken, b: LogicalToken): boolean {\n if (a.type !== b.type || a.tier !== b.tier) return false;\n const modes = new Set([...Object.keys(a.values), ...Object.keys(b.values)]);\n for (const m of modes) if (!valuesEqual(a.type, a.values[m], b.values[m])) return false;\n return true;\n}\n\n/**\n * Align Figma token ids with Git ids. `git` is every token known on the Git side (base and head).\n * Heuristic candidates are restricted to Git tokens that no Figma variable claims.\n */\nexport function reconcileIds(figma: LogicalToken[], git: LogicalToken[]): ReconcileResult {\n const gitById = new Map<string, LogicalToken>();\n const gitByPath = new Map<string, LogicalToken>();\n for (const t of git) {\n if (!gitById.has(t.id)) gitById.set(t.id, t);\n if (!gitByPath.has(t.path)) gitByPath.set(t.path, t);\n }\n const claimed = new Set(figma.filter((t) => gitById.has(t.id)).map((t) => t.id));\n const adoptedByName: string[] = [];\n const tokens = figma.map((t) => ({ ...t }));\n\n for (const t of tokens) {\n if (gitById.has(t.id)) continue;\n const byName = gitByPath.get(t.path);\n if (byName && !claimed.has(byName.id) && byName.type === t.type) {\n t.id = byName.id;\n claimed.add(byName.id);\n adoptedByName.push(t.id);\n }\n }\n\n const suggestions: RenameSuggestion[] = [];\n const unclaimedGit = [...gitById.values()].filter((g) => !claimed.has(g.id));\n for (const t of tokens) {\n if (gitById.has(t.id)) continue;\n let best: RenameSuggestion | undefined;\n for (const g of unclaimedGit) {\n if (!sameContent(t, g)) continue;\n const similarity = pathSimilarity(t.path, g.path);\n if (similarity < SIMILARITY_THRESHOLD) continue;\n if (!best || similarity > best.similarity) {\n best = { figmaId: t.id, gitId: g.id, fromPath: g.path, toPath: t.path, similarity: Math.round(similarity * 100) / 100 };\n }\n }\n if (best) suggestions.push(best);\n }\n // One suggestion per Git token: keep the most similar.\n const byGit = new Map<string, RenameSuggestion>();\n for (const s of suggestions) {\n const prev = byGit.get(s.gitId);\n if (!prev || s.similarity > prev.similarity) byGit.set(s.gitId, s);\n }\n return { tokens, adoptedByName, suggestions: [...byGit.values()] };\n}\n\n/** Apply the rename suggestions the user confirmed: the Figma token takes the Git id. */\nexport function applyConfirmedRenames(tokens: LogicalToken[], confirmed: RenameSuggestion[]): LogicalToken[] {\n const map = new Map(confirmed.map((s) => [s.figmaId, s.gitId]));\n return tokens.map((t) => (map.has(t.id) ? { ...t, id: map.get(t.id)! } : t));\n}\n\n/**\n * Id to write into `$extensions[\"com.dsbridge.id\"]`: only needed when the id no longer matches\n * the default derived from the path (after a rename). Undefined means \"do not write\".\n */\nexport function idExtensionFor(t: LogicalToken): string | undefined {\n return t.id === pathId(t.path) ? undefined : t.id;\n}\n","// Three-way merge of token files: a change (mine) against the latest library (theirs), from the commit they share\n// (base). Same rules as the Figma sync (diff-engine threeWayDiff): a token changed on one side only takes that side,\n// a token changed on both sides the same way is unchanged, and a token changed on both sides differently is a\n// conflict the designer decides (\"Keep mine\" or \"Use the library's\"). A token removed on one side and changed on the\n// other has no default: the designer must pick.\n//\n// Works file by file on the DTCG text, so each mode (semantic/light, semantic/dark, a brand override file) is merged\n// on its own, and edits go through the format-preserving codec: untouched tokens stay byte for byte as the library\n// has them. Pure: no fetch, no DOM.\n\nimport { emptyTokenFile, flattenTokens, parseTokenFile, removeToken, serializeTokenFile, upsertToken, type TokenDocument } from './dtcg-codec';\nimport { threeWayDiff, type DiffEntry } from './diff-engine';\nimport { pathId } from './token-set';\nimport { EXT_ID, EXT_SCOPES, SINGLE_MODE, type FlatToken, type LogicalToken } from './types';\n\n/** Which side a conflict keeps: this change (\"Keep mine\") or the latest library (\"Use the library's\"). */\nexport type MergeSide = 'mine' | 'theirs';\n\nexport interface TokenMergeConflict {\n /** Stable key for the choice: `<file>#<token id>`. */\n key: string;\n /** Token file, relative to the tokens root. */\n file: string;\n /** Display path: this change's name, else the library's, else the shared one. */\n path: string;\n base?: FlatToken | undefined;\n mine?: FlatToken | undefined;\n theirs?: FlatToken | undefined;\n /** The side that removed the token while the other changed it. Null when both sides kept it. */\n removedOn: MergeSide | null;\n /** \"Keep mine\" by default; null when the token was removed on one side and changed on the other. */\n defaultChoice: MergeSide | null;\n}\n\nexport interface TokenMergePlan {\n /** Token files both sides changed, relative to the tokens root. */\n files: string[];\n conflicts: TokenMergeConflict[];\n /** Tokens only this change touched: applied on top of the library as they are. */\n mineOnly: number;\n /** Tokens only the library touched: kept as the library has them. */\n theirsOnly: number;\n /** Files that could not be read (not JSON): nothing can be merged while there is one. */\n problems: string[];\n}\n\nexport interface TokenMergeInput {\n /** File texts at the commit both sides share. Undefined: the file did not exist there. */\n base: Record<string, string | undefined>;\n /** File texts in the change. */\n mine: Record<string, string | undefined>;\n /** File texts in the latest library. */\n theirs: Record<string, string | undefined>;\n /** Token files both sides changed (the others need no merge). */\n files: string[];\n}\n\nexport type MergeChoices = Record<string, MergeSide | undefined>;\n\ninterface Side {\n doc: TokenDocument | undefined;\n flat: Map<string, FlatToken>;\n logical: Map<string, LogicalToken>;\n}\n\nconst idOf = (f: FlatToken) => {\n const id = f.extensions?.[EXT_ID];\n return typeof id === 'string' && id ? id : pathId(f.path);\n};\n\n/** One flat token as a single-mode logical token, so threeWayDiff compares path, type, value, description and scopes. */\nfunction logical(f: FlatToken): LogicalToken {\n const scopes = f.extensions?.[EXT_SCOPES];\n return {\n id: idOf(f),\n path: f.path,\n type: f.type ?? 'unknown',\n // One file holds one tier: the tier only feeds default scopes, the same on every side.\n tier: 'primitive',\n values: { [SINGLE_MODE]: f.value },\n description: f.description,\n scopes: Array.isArray(scopes) ? scopes.map(String) : undefined,\n files: { [SINGLE_MODE]: f.file },\n };\n}\n\nfunction readSide(file: string, text: string | undefined, problems: string[], label: string): Side {\n const side: Side = { doc: undefined, flat: new Map(), logical: new Map() };\n if (text === undefined) return side;\n try {\n side.doc = parseTokenFile(file, text);\n } catch (err) {\n problems.push(`${file} (${label}) is not valid JSON: ${(err as Error).message}`);\n return side;\n }\n for (const f of flattenTokens(side.doc)) {\n const id = idOf(f);\n side.flat.set(id, f);\n side.logical.set(id, logical(f));\n }\n return side;\n}\n\ninterface FileDiff {\n file: string;\n base: Side;\n mine: Side;\n theirs: Side;\n local: DiffEntry[];\n remote: DiffEntry[];\n conflicts: DiffEntry[];\n}\n\nfunction diffFile(input: TokenMergeInput, file: string, problems: string[]): FileDiff {\n const base = readSide(file, input.base[file], problems, 'shared start');\n const mine = readSide(file, input.mine[file], problems, 'this change');\n const theirs = readSide(file, input.theirs[file], problems, 'latest library');\n const r = threeWayDiff(base.logical, mine.logical, theirs.logical);\n return { file, base, mine, theirs, local: r.local, remote: r.remote, conflicts: r.conflicts };\n}\n\n/** The side that removed a token the other side changed, or null. */\nexport function removedSide(c: { base?: unknown; mine?: unknown; theirs?: unknown }): MergeSide | null {\n if (!c.base) return null;\n if (!c.mine && c.theirs) return 'mine';\n if (!c.theirs && c.mine) return 'theirs';\n return null;\n}\n\n/** \"Keep mine\" by default, except for a token removed on one side and changed on the other: no default there. */\nexport const defaultChoiceFor = (c: { base?: unknown; mine?: unknown; theirs?: unknown }): MergeSide | null => (removedSide(c) ? null : 'mine');\n\n/** What both sides did to the token files they both changed, and which tokens need a decision. */\nexport function planTokenMerge(input: TokenMergeInput): TokenMergePlan {\n const problems: string[] = [];\n const files = [...new Set(input.files)].sort();\n const conflicts: TokenMergeConflict[] = [];\n let mineOnly = 0;\n let theirsOnly = 0;\n for (const file of files) {\n const d = diffFile(input, file, problems);\n mineOnly += d.local.length;\n theirsOnly += d.remote.length;\n for (const e of d.conflicts) {\n const c = { base: d.base.flat.get(e.id), mine: d.mine.flat.get(e.id), theirs: d.theirs.flat.get(e.id) };\n conflicts.push({ key: `${file}#${e.id}`, file, path: (c.mine ?? c.theirs ?? c.base)!.path, ...c, removedOn: removedSide(c), defaultChoice: defaultChoiceFor(c) });\n }\n }\n return { files, conflicts, mineOnly, theirsOnly, problems };\n}\n\n/** The side a conflict keeps: the designer's pick, else its default (null: still to pick). */\nexport const choiceFor = (c: TokenMergeConflict, choices: MergeChoices): MergeSide | null => choices[c.key] ?? c.defaultChoice;\n\n/** Conflicts that still need a pick: removed on one side, changed on the other, and not decided yet. */\nexport function missingChoices(plan: Pick<TokenMergePlan, 'conflicts'>, choices: MergeChoices): TokenMergeConflict[] {\n return plan.conflicts.filter((c) => choiceFor(c, choices) === null);\n}\n\n/** Puts this change's version of a token into the library's file: its value, type, description and extensions. Also used by token-combine. */\nexport function takeMine(doc: TokenDocument, mine: FlatToken | undefined, existing: FlatToken | undefined): boolean {\n if (!mine) return existing ? removeToken(doc, existing.path) : false;\n let changed = false;\n if (existing && existing.path !== mine.path) changed = removeToken(doc, existing.path) || changed;\n // Extension keys the library has and this change does not are removed, so the token reads as in the change.\n const extensions: Record<string, unknown> = {};\n for (const k of Object.keys(existing?.path === mine.path ? (existing.extensions ?? {}) : {})) extensions[k] = undefined;\n Object.assign(extensions, mine.extensions ?? {});\n return upsertToken(doc, mine.path, { type: mine.type, value: mine.value, description: mine.description, extensions }) || changed;\n}\n\nexport interface TokenMergeResult {\n /** Merged text per file (relative to the tokens root); null when the merged file holds no token and is removed. */\n files: Record<string, string | null>;\n /** How many conflicts kept each side. */\n kept: Record<MergeSide, number>;\n}\n\n/**\n * The merged token files: the latest library's text, plus every token only this change touched, plus each conflict\n * as chosen. Throws when a file could not be read or a conflict still needs a pick.\n */\nexport function applyTokenMerge(input: TokenMergeInput, choices: MergeChoices): TokenMergeResult {\n const plan = planTokenMerge(input);\n if (plan.problems.length) throw new Error(plan.problems[0]);\n const missing = missingChoices(plan, choices);\n if (missing.length) throw new Error(`Pick a value for ${missing.map((c) => c.path).join(', ')} first.`);\n const byKey = new Map(plan.conflicts.map((c) => [c.key, c]));\n const kept: Record<MergeSide, number> = { mine: 0, theirs: 0 };\n const files: Record<string, string | null> = {};\n for (const file of plan.files) {\n const d = diffFile(input, file, []);\n const doc = d.theirs.doc ?? emptyTokenFile(file);\n for (const e of d.local) takeMine(doc, d.mine.flat.get(e.id), d.theirs.flat.get(e.id) ?? d.base.flat.get(e.id));\n for (const e of d.conflicts) {\n const side = choiceFor(byKey.get(`${file}#${e.id}`)!, choices)!;\n kept[side]++;\n if (side === 'mine') takeMine(doc, d.mine.flat.get(e.id), d.theirs.flat.get(e.id));\n }\n const empty = flattenTokens(doc).length === 0;\n files[file] = empty && (input.theirs[file] === undefined || input.mine[file] === undefined) ? null : serializeTokenFile(doc);\n }\n return { files, kept };\n}\n","// Try several changes together: the latest library plus the token edits of 2 to 4 open changes, combined in the\n// browser. Nothing is written anywhere: no branch, no commit. Each change's own edits are what it did to its token\n// files since it started (its start against its current version), so a change that is behind the library never\n// undoes the library's newer values. Edits to the same token that agree are applied once; edits that disagree are a\n// conflict the designer settles (\"Use <change>'s\"). Pure: no fetch, no DOM. Studio (Changes, the library views) and\n// the admin's Bridge toolbar both run it.\n\nimport { emptyTokenFile, flattenTokens, parseTokenFile, serializeTokenFile, type TokenDocument } from './dtcg-codec';\nimport { takeMine } from './token-merge';\nimport { pathId } from './token-set';\nimport { EXT_ID, type FlatToken } from './types';\n\n/** What one change brings: its token files where it started and now, and the token files it edits. */\nexport interface CombineSource {\n number: number;\n /** Token file texts where the change started (relative to the tokens root). Undefined: the file did not exist. */\n base: Record<string, string | undefined>;\n /** Token file texts in the change now. Undefined: the change removes the file. */\n head: Record<string, string | undefined>;\n /** Token files the change edits, relative to the tokens root. */\n files: string[];\n}\n\nexport interface CombineEdit {\n /** `<file>#<token id>`: the same token in the same file across changes. */\n key: string;\n file: string;\n /** The token's path in the change (its old path when the change removes it). */\n path: string;\n change: number;\n /** The change's version of the token; undefined when the change removes it. */\n token: FlatToken | undefined;\n}\n\nexport interface ChangeEdits {\n number: number;\n edits: CombineEdit[];\n /** Files that could not be read (not JSON). */\n problems: string[];\n}\n\nconst idOf = (f: FlatToken) => {\n const id = f.extensions?.[EXT_ID];\n return typeof id === 'string' && id ? id : pathId(f.path);\n};\n\nfunction tokensOf(file: string, text: string | undefined, problems: string[], label: string): Map<string, FlatToken> {\n const out = new Map<string, FlatToken>();\n if (text === undefined) return out;\n try {\n for (const t of flattenTokens(parseTokenFile(file, text))) out.set(idOf(t), t);\n } catch (err) {\n problems.push(`${file} (${label}) is not valid JSON: ${(err as Error).message}`);\n }\n return out;\n}\n\n/** What a token is, for comparing two versions of it: its path, type, value and description. */\nconst shape = (t: FlatToken | undefined) => (t ? JSON.stringify([t.path, t.type ?? null, t.value, t.description ?? null]) : 'removed');\n/** What a token shows, for comparing two changes' edits: removed, or its type and value. */\nconst look = (t: FlatToken | undefined) => (t ? JSON.stringify([t.path, t.type ?? null, t.value]) : 'removed');\n\n/** The token edits of one change: every token whose version differs between where the change started and now. */\nexport function changeEdits(src: CombineSource): ChangeEdits {\n const problems: string[] = [];\n const edits: CombineEdit[] = [];\n for (const file of [...new Set(src.files)].sort()) {\n const before = tokensOf(file, src.base[file], problems, 'start');\n const after = tokensOf(file, src.head[file], problems, `change ${src.number}`);\n for (const id of new Set([...before.keys(), ...after.keys()])) {\n const a = before.get(id);\n const b = after.get(id);\n if (shape(a) === shape(b)) continue;\n edits.push({ key: `${file}#${id}`, file, path: (b ?? a)!.path, change: src.number, token: b });\n }\n }\n return { number: src.number, edits, problems };\n}\n\n/** One value a conflicting token can take, and the changes that set it. */\nexport interface CombineOption {\n changes: number[];\n token: FlatToken | undefined;\n}\n\n/** A token two or more changes set differently: the designer picks one change's value. */\nexport interface CombineConflict {\n key: string;\n file: string;\n path: string;\n /** Distinct values, in the order of the changes. */\n options: CombineOption[];\n}\n\n/** The pick of each conflict: the change whose value the combination uses. */\nexport type CombinePicks = Record<string, number>;\n\nexport interface Combination {\n /** Every token file of the latest library, with the combined edits applied (unchanged files as they are). */\n files: Record<string, string>;\n /** The changes combined, in order. */\n included: number[];\n /** Token values the combination edits (one per token and file: a token edited in light and dark counts twice). */\n edits: number;\n /** Tokens the combination edits, by name. */\n tokens: number;\n conflicts: CombineConflict[];\n /** Conflicts without a pick that counts: left at the library's value ('skip') or given the first change's ('first'). */\n missing: CombineConflict[];\n /** Token path -> the changes whose value the combination uses for it. */\n from: Record<string, number[]>;\n problems: string[];\n}\n\n/** Edits grouped by token, in the order of the changes. */\nfunction byToken(changes: ChangeEdits[]): Map<string, CombineEdit[]> {\n const out = new Map<string, CombineEdit[]>();\n for (const c of changes) for (const e of c.edits) out.set(e.key, [...(out.get(e.key) ?? []), e]);\n return out;\n}\n\nfunction optionsOf(edits: CombineEdit[]): CombineOption[] {\n const out: { look: string; option: CombineOption }[] = [];\n for (const e of edits) {\n const l = look(e.token);\n const hit = out.find((o) => o.look === l);\n if (hit) hit.option.changes.push(e.change);\n else out.push({ look: l, option: { changes: [e.change], token: e.token } });\n }\n return out.map((o) => o.option);\n}\n\n/** Tokens that two or more of these changes set differently. */\nexport function combineConflicts(changes: ChangeEdits[]): CombineConflict[] {\n const out: CombineConflict[] = [];\n for (const [key, edits] of byToken(changes)) {\n const options = optionsOf(edits);\n if (options.length > 1) out.push({ key, file: edits[0]!.file, path: edits[0]!.path, options });\n }\n return out;\n}\n\n/** The option a pick selects, or null when the picked change is not among them (not picked, or switched off). */\nexport function pickedOption(c: CombineConflict, picks: CombinePicks): CombineOption | null {\n const n = picks[c.key];\n return n === undefined ? null : (c.options.find((o) => o.changes.includes(n)) ?? null);\n}\n\n/** Conflicts that still need a pick. */\nexport const unpicked = (conflicts: CombineConflict[], picks: CombinePicks) => conflicts.filter((c) => !pickedOption(c, picks));\n\n/**\n * The latest library plus the edits of the included changes (all of them by default, in their order). A conflict\n * uses the picked change's value. Without a pick that counts, `unpicked: 'skip'` (Studio, before opening) leaves the\n * token at the library's value and lists it in `missing`; `'first'` (the toolbar, when a picked change is switched\n * off) uses the first included change's value and still lists it.\n */\nexport function combineChanges(latest: Record<string, string>, changes: ChangeEdits[], picks: CombinePicks = {}, opts: { include?: number[]; unpicked?: 'skip' | 'first' } = {}): Combination {\n const on = opts.include ? changes.filter((c) => opts.include!.includes(c.number)) : changes;\n const problems = on.flatMap((c) => c.problems);\n const groups = byToken(on);\n const conflicts: CombineConflict[] = [];\n const missing: CombineConflict[] = [];\n const from: Record<string, number[]> = {};\n const docs = new Map<string, TokenDocument>();\n const docOf = (file: string): TokenDocument | null => {\n if (docs.has(file)) return docs.get(file)!;\n const text = latest[file];\n let doc: TokenDocument;\n try {\n doc = text === undefined ? emptyTokenFile(file) : parseTokenFile(file, text);\n } catch (err) {\n problems.push(`${file} (latest library) is not valid JSON: ${(err as Error).message}`);\n return null;\n }\n docs.set(file, doc);\n return doc;\n };\n for (const [key, edits] of groups) {\n const options = optionsOf(edits);\n let use: CombineOption | null = options[0]!;\n if (options.length > 1) {\n const conflict: CombineConflict = { key, file: edits[0]!.file, path: edits[0]!.path, options };\n conflicts.push(conflict);\n use = pickedOption(conflict, picks);\n if (!use) {\n missing.push(conflict);\n use = opts.unpicked === 'first' ? options[0]! : null;\n }\n }\n if (!use) continue;\n const doc = docOf(edits[0]!.file);\n if (!doc) continue;\n const existing = flattenTokens(doc).find((t) => idOf(t) === key.slice(key.indexOf('#') + 1));\n // A removal removes the library's token; an edit replaces it (or adds it when the library does not have it).\n takeMine(doc, use.token, existing);\n const path = use.token?.path ?? edits[0]!.path;\n from[path] = [...new Set([...(from[path] ?? []), ...use.changes])];\n }\n const files: Record<string, string> = { ...latest };\n for (const [file, doc] of docs) {\n if (latest[file] === undefined && flattenTokens(doc).length === 0) continue;\n files[file] = serializeTokenFile(doc);\n }\n const tokens = new Set([...groups.values()].map((e) => e[0]!.path)).size;\n return { files, included: on.map((c) => c.number), edits: groups.size, tokens, conflicts, missing, from, problems };\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Picks in an address: `118:semantic/light.tokens.json#path:color.bg.default~120:...`. The change number first, then\n// the conflict key; entries joined by \"~\" (keys hold \":\" and \"#\", never \"~\").\n\nexport function encodePicks(picks: CombinePicks): string {\n return Object.entries(picks)\n .filter(([, n]) => Number.isSafeInteger(n) && n > 0)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, n]) => `${n}:${key}`)\n .join('~');\n}\n\nexport function decodePicks(raw: string | null | undefined): CombinePicks {\n const out: CombinePicks = {};\n for (const part of (raw ?? '').split('~')) {\n const i = part.indexOf(':');\n if (i < 1) continue;\n const n = Number(part.slice(0, i));\n const key = part.slice(i + 1);\n if (/^\\d{1,7}$/.test(part.slice(0, i)) && n > 0 && key.includes('#')) out[key] = n;\n }\n return out;\n}\n","// CSS custom properties that paint a token set over another one: the live preview of a token draft (Studio Tokens),\n// a change shown in Studio Components, and several changes tried together in the admin's Bridge toolbar. Pure.\nimport { resolve, type ResolveContext } from './resolver';\nimport type { TokenSet } from './token-set';\nimport { formatValue, parseColor, rgbaToHex } from './values';\n\n/** CSS value of a resolved DTCG value, the way tokens.css writes it. */\nexport function cssOf(type: string, value: unknown): string | undefined {\n if (value === undefined) return undefined;\n if (type === 'color') {\n const hex = value && typeof value === 'object' ? (value as { hex?: unknown }).hex : undefined;\n const c = parseColor(value);\n if (!c) return undefined;\n if (c.a < 1) return `rgb(${Math.round(c.r * 255)} ${Math.round(c.g * 255)} ${Math.round(c.b * 255)} / ${c.a})`;\n return typeof hex === 'string' ? hex.toLowerCase() : rgbaToHex(c);\n }\n return formatValue(type, value);\n}\n\nexport const cssVarOf = (path: string) => `--${path.replace(/\\./g, '-')}`;\n\n/**\n * CSS custom properties to set on a scope so it renders `proposed` instead of `head`: every token whose resolved value\n * differs in that context. Setting resolved values (not var() references) keeps chains correct even when the original\n * variable is declared on an ancestor.\n */\nexport function previewOverrides(head: TokenSet, proposed: TokenSet, ctx: ResolveContext): Record<string, string> {\n const out: Record<string, string> = {};\n const hctx = { ...ctx, overrides: head.overrideIndex };\n const pctx = { ...ctx, overrides: proposed.overrideIndex };\n for (const t of proposed.byPath.values()) {\n const a = resolve(head.byPath, t.path, hctx);\n const b = resolve(proposed.byPath, t.path, pctx);\n const css = cssOf(t.type, b.value);\n if (css !== undefined && JSON.stringify(a.value) !== JSON.stringify(b.value)) out[cssVarOf(t.path)] = css;\n }\n return out;\n}\n","// Apply accepted token changes onto main's files. Only files whose text actually changes are\n// returned, and inside them only the edited tokens change (layout, key order, other tools'\n// $extensions and untouched values are preserved byte for byte).\n\nimport {\n type TokenDocument,\n emptyTokenFile,\n moveToken,\n parseTokenFile,\n readTokenAt,\n removeToken,\n serializeTokenFile,\n upsertToken,\n} from './dtcg-codec';\nimport { idExtensionFor } from './id-map';\nimport { defaultScopes, effectiveScopes, sameScopes } from './scopes';\nimport { type TokenSet, defaultFile, modeFile } from './token-set';\nimport { EXT_ID, EXT_SCOPES, type LogicalToken, isMultiMode } from './types';\nimport { valuesEqual } from './values';\n\nexport interface AcceptedChange {\n /** Desired state; undefined removes the token. */\n target: LogicalToken | undefined;\n /** State on main (head) before the change; undefined for additions. */\n current: LogicalToken | undefined;\n}\n\nexport interface ComposeResult {\n /** Changed files only: path relative to the tokens directory -> new text. */\n files: Record<string, string>;\n /** Every token file after the change (changed and unchanged), for validation. */\n allFiles: Record<string, string>;\n}\n\nconst modesOf = (t: LogicalToken) => Object.keys(t.values);\n\nexport function composeFiles(head: TokenSet, originals: Record<string, string>, changes: AcceptedChange[]): ComposeResult {\n const docs = new Map<string, TokenDocument>();\n const doc = (file: string): TokenDocument => {\n let d = docs.get(file);\n if (!d) {\n const text = originals[file];\n d = text === undefined ? emptyTokenFile(file) : parseTokenFile(file, text);\n docs.set(file, d);\n }\n return d;\n };\n // Each value goes back to the file of its tier and mode: brands/<brand>, semantic/<theme>,\n // density/<density>, or the single file of a primitive, base or component token.\n const fileFor = (t: LogicalToken, mode: string, current?: LogicalToken) =>\n current?.files[mode] ??\n t.files[mode] ??\n (isMultiMode(t.tier) ? modeFile(head.layout, t.tier, mode) : undefined) ??\n defaultFile(t.tier, t.path, head.options.dirs);\n\n for (const { target, current } of changes) {\n if (!target) {\n if (current) for (const mode of modesOf(current)) removeToken(doc(fileFor(current, mode)), current.path);\n continue;\n }\n const renamed = !!current && current.path !== target.path;\n if (current) {\n for (const mode of modesOf(current)) {\n const d = doc(fileFor(current, mode));\n if (target.values[mode] === undefined) removeToken(d, current.path);\n else if (renamed) moveToken(d, current.path, target.path);\n }\n }\n\n const targetScopes = effectiveScopes(target);\n const scopesExt = sameScopes(targetScopes, defaultScopes(target.path, target.type, target.tier)) ? undefined : targetScopes;\n const scopesChanged = !current || !sameScopes(targetScopes, effectiveScopes(current));\n const descChanged = (target.description ?? '').trim() !== (current?.description ?? '').trim();\n\n for (const mode of modesOf(target)) {\n const d = doc(fileFor(target, mode, current));\n const existing = readTokenAt(d, target.path);\n const currentValue = current?.values[mode];\n // Keep main's exact spelling when the value is equal (Figma returns float noise).\n const value = currentValue !== undefined && valuesEqual(target.type, target.values[mode], currentValue) ? currentValue : target.values[mode];\n const extensions: Record<string, unknown> = {};\n if (scopesChanged) extensions[EXT_SCOPES] = scopesExt;\n if (renamed || !existing) extensions[EXT_ID] = idExtensionFor(target);\n upsertToken(d, target.path, {\n type: target.type,\n value,\n description: descChanged || !existing ? target.description : existing.description,\n extensions,\n });\n }\n }\n\n const files: Record<string, string> = {};\n const allFiles: Record<string, string> = { ...originals };\n for (const [file, d] of docs) {\n const text = serializeTokenFile(d);\n allFiles[file] = text;\n if (text !== originals[file]) files[file] = text;\n }\n return { files, allFiles };\n}\n","// Library protection: Bridge is the only way into the default branch. Whatever writes (Claude Code, Claude Design,\n// a developer, the MCP server), the change lands on a branch and reaches the default branch through a reviewed pull\n// request. GitHub enforces it with a repository ruleset on the default branch; this module builds that ruleset and\n// reads whether the default branch is protected, from rulesets and from classic branch protection.\n//\n// Pure: no fetch, no DOM. The GitHub reads live in github-client.ts (listRulesets, getRuleset, getBranchProtection,\n// listCheckRuns); Studio, the CLI and the MCP server share these functions.\n\n/** A ruleset rule as GitHub returns and accepts it. */\nexport interface RulesetRule {\n type: string;\n parameters?: Record<string, unknown>;\n}\n\nexport interface RulesetBypassActor {\n actor_id: number | null;\n actor_type: 'RepositoryRole' | 'Team' | 'Integration' | 'OrganizationAdmin' | 'DeployKey';\n bypass_mode: 'always' | 'pull_request';\n}\n\n/** A repository ruleset (GET /repos/{o}/{r}/rulesets/{id}). The list endpoint leaves out `rules`. */\nexport interface Ruleset {\n id?: number;\n name: string;\n target?: 'branch' | 'tag' | 'push' | string;\n enforcement: 'active' | 'evaluate' | 'disabled' | string;\n conditions?: { ref_name?: { include?: string[]; exclude?: string[] } } | null;\n rules?: RulesetRule[];\n bypass_actors?: RulesetBypassActor[];\n /** Where the ruleset is edited on GitHub. */\n html_url?: string;\n _links?: { html?: { href?: string } };\n}\n\n/** The body of POST /repos/{o}/{r}/rulesets. */\nexport interface RulesetPayload {\n name: string;\n target: 'branch';\n enforcement: 'active';\n conditions: { ref_name: { include: string[]; exclude: string[] } };\n rules: RulesetRule[];\n bypass_actors: RulesetBypassActor[];\n}\n\n/**\n * Classic branch protection (GET /repos/{o}/{r}/branches/{b}/protection), the fields Bridge reads.\n * `null` means the branch has none; `undefined` means it could not be read (no token, no admin access).\n */\nexport interface ClassicProtection {\n required_pull_request_reviews?: { required_approving_review_count?: number } | null;\n required_status_checks?: { contexts?: string[]; checks?: { context: string }[] } | null;\n allow_force_pushes?: { enabled: boolean } | null;\n allow_deletions?: { enabled: boolean } | null;\n}\n\n/** What protecting the library takes, in the order Studio names them. */\nexport type ProtectionPart = 'review' | 'checks' | 'history' | 'deletion';\nexport const PROTECTION_PARTS: readonly ProtectionPart[] = ['review', 'checks', 'history', 'deletion'];\n\nexport type ProtectionKind = 'protected' | 'partial' | 'unprotected' | 'unknown';\n\nexport interface ProtectionState {\n kind: ProtectionKind;\n /** Parts not enforced on the default branch (empty when protected; every part when unprotected or unknown). */\n missing: ProtectionPart[];\n /** The Bridge ruleset (by name), when one exists, active or not: \"Complete protection\" updates it in place. */\n bridgeRulesetId?: number;\n /** Where to see the rule that protects the branch on GitHub, when one does. */\n url?: string;\n}\n\n/** The name Bridge gives its ruleset. Bridge finds it again by this name. */\nexport const protectionRulesetName = (defaultBranch: string) => `Protect the library (${defaultBranch})`;\n\n/** GitHub's built-in repository role id for \"Admin\", used in bypass_actors. */\nexport const ADMIN_ROLE_ID = 5;\n\nexport interface ProtectionOptions {\n /** Check names that must pass before a merge (see requiredCheckNames). Empty: no checks rule. */\n checks: string[];\n /** Approvals a pull request needs. Never below 1. */\n approvals: number;\n /** Let repository admins merge a pull request without its approvals (the owner override). */\n adminBypass: boolean;\n}\n\n/**\n * The ruleset that protects the library. Choices:\n * - Target `~DEFAULT_BRANCH`, not a branch name: it follows a rename of the default branch.\n * - `deletion` and `non_fast_forward`: nobody deletes the default branch or rewrites its history.\n * - `pull_request` with at least 1 approval: every change goes through a reviewed pull request, direct pushes are\n * refused whoever pushes. Stale approvals are dismissed on a new push, so what was approved is what merges.\n * Code owner review and \"approval of the most recent push\" stay off: CODEOWNERS often holds placeholders, and a\n * team of two must still be able to ship.\n * - `required_status_checks`: the CI jobs that ran on recent pull requests must pass. Not strict (the branch does\n * not have to be up to date), which keeps merges from queueing behind each other.\n * - Bypass: repository admins in `pull_request` mode only. They keep the owner override (merge a pull request\n * whose approvals are missing) but cannot push to the default branch either.\n */\nexport function protectionRuleset(config: { repo?: { defaultBranch?: string } | undefined } | null | undefined, opts: ProtectionOptions): RulesetPayload {\n const branch = config?.repo?.defaultBranch ?? 'main';\n const approvals = Math.max(1, Math.floor(Number.isFinite(opts.approvals) ? opts.approvals : 1));\n const checks = [...new Set(opts.checks.map((c) => c.trim()).filter(Boolean))];\n const rules: RulesetRule[] = [\n { type: 'deletion' },\n { type: 'non_fast_forward' },\n {\n type: 'pull_request',\n parameters: {\n required_approving_review_count: approvals,\n dismiss_stale_reviews_on_push: true,\n require_code_owner_review: false,\n require_last_push_approval: false,\n required_review_thread_resolution: false,\n },\n },\n ];\n if (checks.length) {\n rules.push({\n type: 'required_status_checks',\n parameters: {\n strict_required_status_checks_policy: false,\n required_status_checks: checks.map((context) => ({ context })),\n },\n });\n }\n return {\n name: protectionRulesetName(branch),\n target: 'branch',\n enforcement: 'active',\n conditions: { ref_name: { include: ['~DEFAULT_BRANCH'], exclude: [] } },\n rules,\n bypass_actors: opts.adminBypass ? [{ actor_id: ADMIN_ROLE_ID, actor_type: 'RepositoryRole', bypass_mode: 'pull_request' }] : [],\n };\n}\n\n/** Minimal check run shape (github-client CheckRun fits). `app` is the GitHub App slug when known. */\nexport interface CheckRunLike {\n name: string;\n status?: string;\n conclusion: string | null;\n app?: string | undefined;\n}\n\nconst isVercel = (r: CheckRunLike) => /vercel/i.test(r.app ?? '') || /^vercel\\b/i.test(r.name);\nconst ran = (r: CheckRunLike) => r.conclusion !== 'skipped' && r.conclusion !== 'cancelled' && r.conclusion !== 'stale';\n\n/**\n * The check names to require, read from the repository's own CI, never hardcoded: the check runs of the default\n * branch's latest commit, without Vercel (deploy previews, not tests) and without skipped ones. When the head of a\n * recent pull request is given, only checks that also ran there are kept: a job that runs on pushes to the default\n * branch only (a release job) never reports on a pull request, and requiring it would block every merge.\n */\nexport function requiredCheckNames(defaultBranchRuns: CheckRunLike[], pullRequestRuns?: CheckRunLike[]): string[] {\n const names = [...new Set(defaultBranchRuns.filter((r) => !isVercel(r) && ran(r)).map((r) => r.name))];\n if (!pullRequestRuns?.length) return names;\n const onPulls = new Set(pullRequestRuns.filter((r) => !isVercel(r)).map((r) => r.name));\n return names.filter((n) => onPulls.has(n));\n}\n\n/** Converts a ref pattern (fnmatch: `*` within a segment, `**` across) to a RegExp. */\nfunction refPattern(pattern: string): RegExp {\n const src = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*\\*/g, '\\u0000')\n .replace(/\\*/g, '[^/]*')\n .replace(/\\?/g, '[^/]')\n .replace(/\\u0000/g, '.*');\n return new RegExp(`^${src}$`);\n}\n\n/** True when a branch ruleset's conditions cover the default branch. */\nexport function rulesetTargetsDefault(ruleset: Ruleset, defaultBranch: string): boolean {\n if (ruleset.target && ruleset.target !== 'branch') return false;\n const ref = `refs/heads/${defaultBranch}`;\n const hit = (p: string) => p === '~ALL' || p === '~DEFAULT_BRANCH' || p === ref || p === defaultBranch || refPattern(p.startsWith('refs/') ? p : `refs/heads/${p}`).test(ref);\n const cond = ruleset.conditions?.ref_name;\n // A repository ruleset with no ref condition applies to nothing; GitHub requires one.\n if (!cond) return false;\n if ((cond.exclude ?? []).some(hit)) return false;\n return (cond.include ?? []).some(hit);\n}\n\nconst count = (v: unknown) => (typeof v === 'number' ? v : 0);\n\n/** The parts one ruleset enforces (active rulesets only; \"evaluate\" only reports). */\nfunction rulesetParts(ruleset: Ruleset): Set<ProtectionPart> {\n const parts = new Set<ProtectionPart>();\n if (ruleset.enforcement !== 'active') return parts;\n for (const rule of ruleset.rules ?? []) {\n if (rule.type === 'deletion') parts.add('deletion');\n if (rule.type === 'non_fast_forward') parts.add('history');\n if (rule.type === 'pull_request' && count(rule.parameters?.required_approving_review_count) >= 1) parts.add('review');\n if (rule.type === 'required_status_checks' && Array.isArray(rule.parameters?.required_status_checks) && (rule.parameters.required_status_checks as unknown[]).length > 0) parts.add('checks');\n }\n return parts;\n}\n\n/** The parts classic branch protection enforces. Force pushes and deletions are refused unless allowed. */\nfunction classicParts(p: ClassicProtection): Set<ProtectionPart> {\n const parts = new Set<ProtectionPart>();\n if (count(p.required_pull_request_reviews?.required_approving_review_count) >= 1) parts.add('review');\n if (((p.required_status_checks?.contexts?.length ?? 0) || (p.required_status_checks?.checks?.length ?? 0)) > 0) parts.add('checks');\n if (!p.allow_force_pushes?.enabled) parts.add('history');\n if (!p.allow_deletions?.enabled) parts.add('deletion');\n return parts;\n}\n\nconst rulesetUrl = (r: Ruleset) => r.html_url ?? r._links?.html?.href;\n\n/**\n * Whether the default branch is protected, from full rulesets (with `rules`; null when they could not be read) and\n * classic branch protection (null when the branch has none, undefined when it could not be read).\n * - protected: review, checks, no history rewrite and no deletion are all enforced.\n * - partial: some of them are.\n * - unprotected: none of them, and both sources were read.\n * - unknown: nothing could be read, or nothing was found in one source while the other could not be read.\n */\nexport function protectionState(rulesets: Ruleset[] | null | undefined, branchProtection: ClassicProtection | null | undefined, defaultBranch: string): ProtectionState {\n const bridge = rulesets?.find((r) => r.name === protectionRulesetName(defaultBranch));\n const extra = bridge?.id !== undefined ? { bridgeRulesetId: bridge.id } : {};\n const covered = new Set<ProtectionPart>();\n let url: string | undefined;\n for (const r of rulesets ?? []) {\n if (!rulesetTargetsDefault(r, defaultBranch)) continue;\n const parts = rulesetParts(r);\n if (parts.size && !url) url = rulesetUrl(r);\n parts.forEach((p) => covered.add(p));\n }\n if (branchProtection) classicParts(branchProtection).forEach((p) => covered.add(p));\n const missing = PROTECTION_PARTS.filter((p) => !covered.has(p));\n const withUrl = url ? { url } : {};\n if (!missing.length) return { kind: 'protected', missing, ...extra, ...withUrl };\n const unreadable = rulesets == null || branchProtection === undefined;\n if (covered.size === 0) return { kind: unreadable ? 'unknown' : 'unprotected', missing, ...extra };\n return { kind: 'partial', missing, ...extra, ...withUrl };\n}\n\n/** Plain words for each part, for designers: no \"ruleset\", \"branch\" or \"force push\". */\nexport const PROTECTION_PART_PHRASE: Record<ProtectionPart, string> = {\n review: 'changes can skip review',\n checks: 'checks do not have to pass',\n history: 'past changes can be rewritten',\n deletion: 'the library can be deleted',\n};\n\nconst joinAnd = (xs: string[]) => (xs.length <= 1 ? (xs[0] ?? '') : `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`);\n\n/** The one sentence Studio, the CLI and the MCP server show for a protection state. */\nexport function protectionSentence(state: ProtectionState): string {\n switch (state.kind) {\n case 'protected':\n return 'Protected: every change goes through review.';\n case 'unprotected':\n return 'Your library can be changed without review.';\n case 'partial': {\n const s = joinAnd(state.missing.map((p) => PROTECTION_PART_PHRASE[p]));\n return `Partly protected: ${s}.`;\n }\n default:\n return 'Protection status unknown: GitHub did not let this token read it.';\n }\n}\n","// Minimal GitHub REST client over fetch. The token is passed in; nothing is read from the\n// environment. Talks to api.github.com (the Figma plugin manifest allows nothing else) and, for\n// token-less reads of public repos, raw.githubusercontent.com, which has no hourly API limit.\n// Bulk reads go through the git trees and blobs endpoints; single files can use the contents API.\n//\n// Writes refuse protected branches (main, master and whatever the caller adds) whatever the caller\n// asks: the client is the last guard between an agent and the default branch.\n\nimport { type BridgeConfig, CONFIG_FILE, ConfigError, DEFAULT_TOKEN_PATHS, loadConfig } from './config';\nimport { assertSafeBranch, DEFAULT_PROTECTED_BRANCHES, ProtectedBranchError } from './governance';\nimport type { ClassicProtection, Ruleset, RulesetPayload } from './protection';\n\n/**\n * What an auth failure means for the token:\n * - \"rejected\": GitHub refused the token itself (401). It was revoked, regenerated or has expired; every call\n * with it will fail until it is replaced.\n * - \"missing-permission\": the token works but lacks a permission this call needs (403 \"Resource not accessible\n * by personal access token\", or a permission GitHub names in X-Accepted-GitHub-Permissions).\n * Undefined for everything else, including rate limits and a missing token.\n */\nexport type GitHubAuthState = 'rejected' | 'missing-permission';\n\n/** Fine-grained token permission names, as GitHub spells them (issues, pull_requests, contents...). */\nexport type GitHubPermission = string;\n\nexport interface GitHubErrorInfo {\n auth?: GitHubAuthState | undefined;\n /** The permission the call needed, when GitHub or the endpoint tells (only with auth \"missing-permission\"). */\n permission?: GitHubPermission | undefined;\n}\n\nexport class GitHubError extends Error {\n /** Set when the failure is about the token: rejected (401) or missing a permission (403). */\n readonly auth: GitHubAuthState | undefined;\n /** With auth \"missing-permission\": the permission the call needed, when known. */\n readonly permission: GitHubPermission | undefined;\n\n constructor(\n readonly status: number,\n message: string,\n readonly detail?: string,\n info: GitHubErrorInfo = {},\n ) {\n super(message);\n this.name = 'GitHubError';\n this.auth = info.auth;\n this.permission = info.permission;\n }\n}\n\n/** True when `err` says GitHub refused the token itself (revoked, regenerated or expired). */\nexport const isTokenRejected = (err: unknown): boolean => err instanceof GitHubError && err.auth === 'rejected';\n\n/** True when `err` says the token works but lacks a permission for that call. */\nexport const isMissingPermission = (err: unknown): boolean => err instanceof GitHubError && err.auth === 'missing-permission';\n\nconst PERMISSION_LABELS: Record<string, string> = {\n issues: 'Issues',\n pull_requests: 'Pull requests',\n contents: 'Contents',\n checks: 'Checks',\n statuses: 'Commit statuses',\n metadata: 'Metadata',\n actions: 'Actions',\n deployments: 'Deployments',\n workflows: 'Workflows',\n administration: 'Administration',\n};\n\n/** \"pull_requests\" -> \"Pull requests\", as GitHub labels it on the token page. */\nexport function permissionLabel(permission: GitHubPermission): string {\n return PERMISSION_LABELS[permission] ?? permission.replace(/_/g, ' ').replace(/^./, (c) => c.toUpperCase());\n}\n\n/** Where a fine-grained token's permissions are edited. */\nexport const TOKEN_SETTINGS_URL = 'https://github.com/settings/personal-access-tokens';\n\n/** The one sentence for a token GitHub no longer accepts. */\nexport const TOKEN_REJECTED_MESSAGE = 'Your GitHub token stopped working. It was revoked, regenerated or has expired: replace it with a new one.';\n\n/**\n * \"This token cannot create issues. Add Issues: Read and write on GitHub.\" `action` is a verb phrase\n * (\"create issues\"); without it the sentence names only the permission.\n */\nexport function missingPermissionMessage(permission: GitHubPermission | undefined, action?: string): string {\n const what = action ? `This token cannot ${action}.` : 'This token is missing a permission for this.';\n if (!permission) return `${what} Check its repository permissions on GitHub (Contents and Pull requests need Read and write).`;\n return `${what} Add ${permissionLabel(permission)}: Read and write on GitHub.`;\n}\n\n/**\n * The permission a refused call needed. GitHub names it in X-Accepted-GitHub-Permissions (\"issues=write\",\n * alternatives split by \";\"); otherwise the endpoint says it (/issues, /pulls, /contents, /git...).\n */\nexport function requiredPermission(path: string, acceptedHeader?: string | null): GitHubPermission | undefined {\n if (acceptedHeader) {\n const first = acceptedHeader.split(';')[0]!.split(',').map((p) => p.trim().split('=')[0]!.trim()).filter((p) => p && p !== 'metadata');\n if (first.length) return first[0];\n }\n const p = path.replace(/[?#].*$/, '');\n if (/\\/repos\\/[^/]+\\/[^/]+\\/(issues|labels|milestones)(\\/|$)/.test(p)) return 'issues';\n if (/\\/repos\\/[^/]+\\/[^/]+\\/pulls(\\/|$)/.test(p)) return 'pull_requests';\n if (/\\/repos\\/[^/]+\\/[^/]+\\/(rulesets(\\/|$)|branches\\/.+\\/protection$)/.test(p)) return 'administration';\n if (/\\/repos\\/[^/]+\\/[^/]+\\/(contents|git|commits|branches|merges)(\\/|$)/.test(p)) return 'contents';\n if (/\\/repos\\/[^/]+\\/[^/]+\\/(check-runs|check-suites)(\\/|$)/.test(p)) return 'checks';\n if (/\\/repos\\/[^/]+\\/[^/]+\\/statuses(\\/|$)/.test(p)) return 'statuses';\n if (/\\/repos\\/[^/]+\\/[^/]+\\/deployments(\\/|$)/.test(p)) return 'deployments';\n if (/\\/repos\\/[^/]+\\/[^/]+\\/actions(\\/|$)/.test(p)) return 'actions';\n return undefined;\n}\n\nconst PERMISSION_DENIED = /not accessible by (personal access token|integration)|must have (admin|push|write) (rights|access)|write access to repository not granted|permission to .* denied/i;\n\n/**\n * Classifies a GitHub error response for the token. 401 with a token sent = rejected. 403 (not a rate limit,\n * not archived) where GitHub names a permission or says the resource is not accessible = missing permission.\n */\nexport function classifyAuth(\n status: number,\n detail: string,\n opts: { path?: string; acceptedPermissions?: string | null; withToken?: boolean } = {},\n): GitHubErrorInfo {\n if (status === 401 && opts.withToken !== false) return { auth: 'rejected' };\n if (status !== 403 || /rate limit|archived/i.test(detail)) return {};\n if (opts.acceptedPermissions || PERMISSION_DENIED.test(detail)) {\n return { auth: 'missing-permission', permission: requiredPermission(opts.path ?? '', opts.acceptedPermissions) };\n }\n return {};\n}\n\nexport interface RepoInfo {\n fullName: string;\n defaultBranch: string;\n private: boolean;\n permissions: { admin?: boolean; push?: boolean; pull?: boolean } | undefined;\n}\n\nexport interface TreeEntry {\n path: string;\n type: 'blob' | 'tree' | 'commit';\n sha: string;\n mode: string;\n}\n\nexport interface CompareResult {\n status: string;\n aheadBy: number;\n behindBy: number;\n files: { filename: string; status: string }[];\n}\n\nexport interface PullRequest {\n number: number;\n url: string;\n title: string;\n draft: boolean;\n headRef: string;\n}\n\nexport interface Review {\n id: number;\n user: string | undefined;\n state: string;\n body: string;\n submittedAt?: string | undefined;\n}\n\nexport interface PullRequestSummary {\n number: number;\n title: string;\n /** \"open\", \"closed\" or \"merged\". */\n state: string;\n draft: boolean;\n author: string;\n headRef: string;\n headSha: string;\n baseRef: string;\n labels: string[];\n url: string;\n updatedAt: string;\n /** Description, when the list endpoint returns it (component change requests read \"Closes #n\" from it). */\n body?: string | undefined;\n}\n\nexport interface ClientOptions {\n /** API base, for GitHub Enterprise or tests. */\n apiUrl?: string;\n /** Raw file host used for token-less reads. */\n rawUrl?: string;\n /** Branches no write may target. Default main and master; the repo's default branch belongs here too. */\n protectedBranches?: string[];\n /** When set, branches this client creates must start with it (agents use \"bridge/\"). */\n branchPrefix?: string;\n /**\n * How a person adds a token where this client runs, for the rate-limit message without one (\"set GITHUB_TOKEN in\n * the MCP server config\"). Default: \"add a GitHub token\".\n */\n tokenHint?: string;\n}\n\n/**\n * The sentence for GitHub's exhausted hourly limit. With a token, the token's own limit is used up: wait. Without one,\n * the shared limit for anonymous reads is (60 an hour per address): say how to get a higher one.\n */\nexport function rateLimitMessage(x: { withToken: boolean; resetsAt?: Date; tokenHint?: string }): string {\n const when = x.resetsAt ? ` It resets at ${x.resetsAt.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}.` : '';\n if (x.withToken) return `GitHub's hourly request limit for this token is used up.${when} Try again after that.`;\n const hint = x.tokenHint ?? 'add a GitHub token';\n return `GitHub's hourly limit for requests without a token (60 an hour) is used up.${when} To keep going now, ${hint}: a token gets 5,000 requests an hour.`;\n}\n\n/** A file in a new commit: text content, or null to delete it. */\nexport interface CommitFile {\n path: string;\n content: string | null;\n}\n\nexport interface CheckRun {\n id: number;\n name: string;\n status: string;\n conclusion: string | null;\n url: string | undefined;\n /** Slug of the GitHub App that reported it (\"github-actions\", \"vercel\"), when GitHub says. */\n app?: string | undefined;\n}\n\nexport interface CommitSummary {\n sha: string;\n parents: string[];\n /** ISO date the commit landed (committer date). */\n date: string;\n /** GitHub login when known, else the git author name. */\n author: string;\n message: string;\n}\n\nexport interface PullRequestFile {\n filename: string;\n status: string;\n additions: number;\n deletions: number;\n}\n\nexport type FetchLike = (url: string, init?: { method?: string; headers?: Record<string, string>; body?: string }) => Promise<{\n ok: boolean;\n status: number;\n headers?: { get(name: string): string | null };\n json(): Promise<unknown>;\n text(): Promise<string>;\n}>;\n\nexport interface RetryPolicy {\n /** Attempts for idempotent calls (GET, and content-addressed blob/tree/commit creation). */\n attempts: number;\n /** First backoff in ms; doubles each retry. */\n baseDelayMs: number;\n sleep: (ms: number) => Promise<void>;\n}\n\nconst DEFAULT_RETRY: RetryPolicy = { attempts: 3, baseDelayMs: 600, sleep: (ms) => new Promise((r) => setTimeout(r, ms)) };\n\n/** Transient failures worth retrying: network errors, 5xx, and secondary rate limits. */\nconst isTransient = (status: number, detail: string) => status === 0 || status >= 500 || status === 429 || (status === 403 && /secondary rate limit/i.test(detail));\n\nconst API = 'https://api.github.com';\nconst RAW = 'https://raw.githubusercontent.com';\n\n/** \"owner/name\", a github.com URL or an SSH remote. */\nexport function parseRepo(repo: string): { owner: string; name: string } {\n const m = /^\\s*(?:https?:\\/\\/github\\.com\\/|git@github\\.com:)?([A-Za-z0-9-]+)\\/([A-Za-z0-9._-]+?)(?:\\.git)?\\/?\\s*$/.exec(repo);\n if (!m) throw new Error(`\"${repo}\" is not a repository. Use the form owner/name.`);\n return { owner: m[1]!, name: m[2]! };\n}\n\nexport function utf8ToBase64(text: string): string {\n const bytes = new TextEncoder().encode(text);\n let bin = '';\n for (const b of bytes) bin += String.fromCharCode(b);\n return btoa(bin);\n}\n\nexport function base64ToUtf8(b64: string): string {\n const bin = atob(b64.replace(/\\s/g, ''));\n const bytes = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);\n return new TextDecoder('utf-8').decode(bytes);\n}\n\nconst encodeRef = (ref: string) => ref.split('/').map(encodeURIComponent).join('/');\n\nexport class GitHubClient {\n readonly owner: string;\n readonly name: string;\n private readonly blobCache = new Map<string, string>();\n private readonly api: string;\n private readonly protectedBranches: string[];\n\n constructor(\n repo: string,\n private readonly token: string,\n private readonly fetchImpl: FetchLike = (url, init) => fetch(url, init),\n private readonly retry: RetryPolicy = DEFAULT_RETRY,\n private readonly options: ClientOptions = {},\n ) {\n const r = parseRepo(repo);\n this.owner = r.owner;\n this.name = r.name;\n this.api = (options.apiUrl ?? API).replace(/\\/$/, '');\n this.protectedBranches = options.protectedBranches ?? DEFAULT_PROTECTED_BRANCHES;\n }\n\n /** \"owner/name\". */\n get fullName() {\n return `${this.owner}/${this.name}`;\n }\n\n /** Whether a token was given (without one, every write is refused before any request). */\n get canWrite() {\n return Boolean(this.token);\n }\n\n /** Throws unless `branch` may be written: not protected, not the base, and with the agent prefix when set. */\n assertWritableBranch(branch: string, base?: string): void {\n try {\n assertSafeBranch(branch, { protectedBranches: this.protectedBranches, base, branchPrefix: this.options.branchPrefix });\n } catch (err) {\n if (err instanceof ProtectedBranchError) throw new GitHubError(403, err.message, 'protected-branch');\n throw err;\n }\n }\n\n private assertToken(what: string): void {\n if (!this.token) throw new GitHubError(401, `${what} needs a GitHub token (contents and pull requests, read and write, on this repository only). Without one Bridge is read-only.`, 'no-token');\n }\n\n private get repoPath() {\n return `/repos/${this.owner}/${this.name}`;\n }\n\n private async request<T>(method: string, path: string, body?: unknown, retryable = method === 'GET'): Promise<T> {\n const attempts = retryable ? Math.max(1, this.retry.attempts) : 1;\n for (let attempt = 1; ; attempt++) {\n try {\n return await this.once<T>(method, path, body);\n } catch (err) {\n const e = err as GitHubError;\n if (attempt >= attempts || !(e instanceof GitHubError) || !isTransient(e.status, e.detail ?? '')) throw err;\n await this.retry.sleep(this.retry.baseDelayMs * 2 ** (attempt - 1));\n }\n }\n }\n\n private async once<T>(method: string, path: string, body?: unknown): Promise<T> {\n const headers: Record<string, string> = {\n Accept: 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n };\n if (this.token) headers.Authorization = `Bearer ${this.token}`;\n if (body !== undefined) headers['Content-Type'] = 'application/json';\n let res: Awaited<ReturnType<FetchLike>>;\n try {\n res = await this.fetchImpl(`${this.api}${path}`, { method, headers, ...(body !== undefined ? { body: JSON.stringify(body) } : {}) });\n } catch (err) {\n throw new GitHubError(0, 'Could not reach GitHub. Check your connection, then try again.', (err as Error).message);\n }\n if (res.status === 204) return undefined as T;\n if (!res.ok) {\n let detail = '';\n try {\n const data = (await res.json()) as { message?: string; errors?: ({ message?: string } | string)[] };\n detail = [data.message, ...(data.errors ?? []).map((e) => (typeof e === 'string' ? e : e.message))].filter(Boolean).join(' ');\n } catch {\n detail = '';\n }\n const remaining = res.headers?.get('x-ratelimit-remaining');\n const reset = res.headers?.get('x-ratelimit-reset');\n if ((res.status === 403 || res.status === 429) && remaining === '0') {\n const resetsAt = reset ? new Date(Number(reset) * 1000) : undefined;\n throw new GitHubError(429, rateLimitMessage({ withToken: Boolean(this.token), resetsAt, tokenHint: this.options.tokenHint }), detail);\n }\n const info = classifyAuth(res.status, detail, {\n path,\n acceptedPermissions: res.headers?.get('x-accepted-github-permissions'),\n withToken: Boolean(this.token),\n });\n throw new GitHubError(res.status, friendlyMessage(res.status, detail, info), detail, info);\n }\n return (await res.json()) as T;\n }\n\n async getRepo(): Promise<RepoInfo> {\n const r = await this.request<{ full_name: string; default_branch: string; private: boolean; permissions?: RepoInfo['permissions'] }>(\n 'GET',\n this.repoPath,\n );\n return { fullName: r.full_name, defaultBranch: r.default_branch, private: r.private, permissions: r.permissions };\n }\n\n /** Commit sha a branch points to, or undefined when the branch does not exist. */\n async getBranchSha(branch: string): Promise<string | undefined> {\n try {\n const r = await this.request<{ object: { sha: string } }>('GET', `${this.repoPath}/git/ref/heads/${encodeRef(branch)}`);\n return r.object.sha;\n } catch (err) {\n if (err instanceof GitHubError && err.status === 404) return undefined;\n throw err;\n }\n }\n\n async getCommitTree(commitSha: string): Promise<string> {\n const r = await this.request<{ tree: { sha: string } }>('GET', `${this.repoPath}/git/commits/${commitSha}`);\n return r.tree.sha;\n }\n\n async getTree(treeSha: string, recursive = true): Promise<{ entries: TreeEntry[]; truncated: boolean }> {\n const r = await this.request<{ tree: TreeEntry[]; truncated: boolean }>(\n 'GET',\n `${this.repoPath}/git/trees/${treeSha}${recursive ? '?recursive=1' : ''}`,\n );\n return { entries: r.tree, truncated: r.truncated };\n }\n\n async getBlobText(sha: string): Promise<string> {\n const cached = this.blobCache.get(sha);\n if (cached !== undefined) return cached;\n const r = await this.request<{ content: string; encoding: string }>('GET', `${this.repoPath}/git/blobs/${sha}`);\n const text = r.encoding === 'base64' ? base64ToUtf8(r.content) : r.content;\n this.blobCache.set(sha, text);\n return text;\n }\n\n async compare(base: string, head: string): Promise<CompareResult> {\n const r = await this.request<{ status: string; ahead_by: number; behind_by: number; files?: { filename: string; status: string }[] }>(\n 'GET',\n `${this.repoPath}/compare/${base}...${head}`,\n );\n return { status: r.status, aheadBy: r.ahead_by, behindBy: r.behind_by, files: (r.files ?? []).map((f) => ({ filename: f.filename, status: f.status })) };\n }\n\n // --- History (read only) ----------------------------------------------------------------------\n\n /** Commits on a ref, newest first, optionally only those touching `path` (a file or directory). */\n async listCommits(opts: { sha?: string; path?: string; perPage?: number; page?: number } = {}): Promise<CommitSummary[]> {\n const q = new URLSearchParams();\n if (opts.sha) q.set('sha', opts.sha);\n if (opts.path) q.set('path', opts.path);\n q.set('per_page', String(Math.min(100, opts.perPage ?? 30)));\n if (opts.page) q.set('page', String(opts.page));\n const r = await this.request<Record<string, any>[]>('GET', `${this.repoPath}/commits?${q}`);\n return r.map(toCommitSummary);\n }\n\n /** One commit: message, author, date and parents. */\n async getCommitInfo(sha: string): Promise<CommitSummary> {\n return toCommitSummary(await this.request<Record<string, any>>('GET', `${this.repoPath}/commits/${encodeRef(sha)}`));\n }\n\n /** Pull requests a commit belongs to (merged ones first): how a commit on main finds its PR. */\n async listPullRequestsForCommit(sha: string): Promise<(PullRequestSummary & { body: string; mergedAt?: string; mergeCommitSha?: string })[]> {\n const r = await this.request<Record<string, any>[]>('GET', `${this.repoPath}/commits/${encodeRef(sha)}/pulls`);\n return r\n .map((p) => ({ ...toSummary(p), body: p.body ?? '', ...(p.merged_at ? { mergedAt: p.merged_at as string } : {}), ...(p.merge_commit_sha ? { mergeCommitSha: p.merge_commit_sha as string } : {}) }))\n .sort((a, b) => Number(Boolean(b.mergedAt)) - Number(Boolean(a.mergedAt)));\n }\n\n /** Tags with the commit they point to, newest first as GitHub lists them. */\n async listTags(perPage = 30): Promise<{ name: string; sha: string }[]> {\n const r = await this.request<{ name: string; commit: { sha: string } }[]>('GET', `${this.repoPath}/tags?per_page=${Math.min(100, perPage)}`);\n return r.map((t) => ({ name: t.name, sha: t.commit.sha }));\n }\n\n async createBlob(content: string): Promise<string> {\n // Blobs, trees and commits are content-addressed: retrying a create is harmless.\n const r = await this.request<{ sha: string }>('POST', `${this.repoPath}/git/blobs`, { content, encoding: 'utf-8' }, true);\n return r.sha;\n }\n\n /** A tree on top of `baseTree`. Each file gives a blob `sha`, inline `content`, or `sha: null` to delete. */\n async createTree(baseTree: string, files: ({ path: string; sha: string | null } | { path: string; content: string })[]): Promise<string> {\n const r = await this.request<{ sha: string }>('POST', `${this.repoPath}/git/trees`, {\n base_tree: baseTree,\n tree: files.map((f) => ({ path: f.path, mode: '100644', type: 'blob', ...('content' in f ? { content: f.content } : { sha: f.sha }) })),\n }, true);\n return r.sha;\n }\n\n async createCommit(message: string, tree: string, parents: string[]): Promise<string> {\n const r = await this.request<{ sha: string }>('POST', `${this.repoPath}/git/commits`, { message, tree, parents }, true);\n return r.sha;\n }\n\n /** Create a new branch. Refuses protected branches; GitHub refuses existing ones, so nothing is overwritten. */\n async createBranch(branch: string, sha: string): Promise<void> {\n this.assertWritableBranch(branch);\n await this.request('POST', `${this.repoPath}/git/refs`, { ref: `refs/heads/${branch}`, sha });\n }\n\n /** Fast-forward a branch. Never forces: a concurrent push makes this fail instead of losing work. */\n async updateBranch(branch: string, sha: string): Promise<void> {\n this.assertWritableBranch(branch);\n await this.request('PATCH', `${this.repoPath}/git/refs/heads/${encodeRef(branch)}`, { sha, force: false });\n }\n\n /**\n * One commit with `files` on top of `base`, on the new branch `branch`. The branch is created, never\n * moved, so an existing branch is never overwritten. Refuses protected branches and the base itself.\n */\n async commitToNewBranch(input: { base: string; branch: string; message: string; files: CommitFile[] }): Promise<{ sha: string; branch: string }> {\n this.assertToken('Creating a branch');\n this.assertWritableBranch(input.branch, input.base);\n const baseSha = await this.getBranchSha(input.base);\n if (!baseSha) throw new GitHubError(404, `Base branch \"${input.base}\" not found.`);\n const baseTree = await this.getCommitTree(baseSha);\n const tree = await this.createTree(baseTree, input.files.map((f) => (f.content === null ? { path: f.path, sha: null } : { path: f.path, content: f.content })));\n const sha = await this.createCommit(input.message, tree, [baseSha]);\n await this.createBranch(input.branch, sha);\n return { sha, branch: input.branch };\n }\n\n /** The same client (token, fetch, retry, protected branches) with another required branch prefix (`explore/`). */\n withBranchPrefix(branchPrefix: string | undefined): GitHubClient {\n return new GitHubClient(this.fullName, this.token, this.fetchImpl, this.retry, { ...this.options, protectedBranches: this.protectedBranches, branchPrefix });\n }\n\n /**\n * One commit with `files` on top of an existing branch, fast-forwarded (never forced). Refuses protected\n * branches and, with a branch prefix, branches without it: explorations take token edits this way.\n */\n async commitToBranch(input: { branch: string; message: string; files: CommitFile[] }): Promise<{ sha: string; branch: string }> {\n this.assertToken('Committing to a branch');\n this.assertWritableBranch(input.branch);\n const head = await this.getBranchSha(input.branch);\n if (!head) throw new GitHubError(404, `Branch \"${input.branch}\" not found. Start it first.`);\n const baseTree = await this.getCommitTree(head);\n const tree = await this.createTree(baseTree, input.files.map((f) => (f.content === null ? { path: f.path, sha: null } : { path: f.path, content: f.content })));\n const sha = await this.createCommit(input.message, tree, [head]);\n await this.updateBranch(input.branch, sha);\n return { sha, branch: input.branch };\n }\n\n /**\n * Marks a draft pull request ready for review. REST cannot unset `draft`, so this is the GraphQL mutation\n * markPullRequestReadyForReview, with the same token (pull requests: write).\n */\n async markReadyForReview(n: number): Promise<void> {\n this.assertToken('Marking a pull request ready for review');\n const pr = await this.request<{ node_id?: string; draft?: boolean }>('GET', `${this.repoPath}/pulls/${n}`);\n if (pr.draft === false) return;\n if (!pr.node_id) throw new GitHubError(422, `Pull request #${n} has no node id: mark it ready for review on GitHub.`);\n const r = await this.request<{ data?: unknown; errors?: { message?: string }[] }>('POST', '/graphql', {\n query: 'mutation($id: ID!) { markPullRequestReadyForReview(input: { pullRequestId: $id }) { pullRequest { number isDraft } } }',\n variables: { id: pr.node_id },\n });\n if (r?.errors?.length) {\n const detail = r.errors.map((e) => e.message).filter(Boolean).join(' ');\n throw new GitHubError(422, `GitHub refused to mark #${n} ready for review${detail ? `: ${detail}` : '.'} Use \"Ready for review\" on GitHub instead.`, detail);\n }\n }\n\n /**\n * Turns an open pull request back into a draft: the GraphQL mutation convertPullRequestToDraft (REST cannot set\n * `draft` either), same token. No-op when it is already a draft.\n */\n async convertToDraft(n: number): Promise<void> {\n this.assertToken('Turning a pull request back into a draft');\n const pr = await this.request<{ node_id?: string; draft?: boolean; state?: string }>('GET', `${this.repoPath}/pulls/${n}`);\n if (pr.draft === true) return;\n if (pr.state && pr.state !== 'open') throw new GitHubError(422, `Pull request #${n} is ${pr.state}: only an open one can go back to draft.`);\n if (!pr.node_id) throw new GitHubError(422, `Pull request #${n} has no node id: convert it to draft on GitHub.`);\n const r = await this.request<{ data?: unknown; errors?: { message?: string }[] }>('POST', '/graphql', {\n query: 'mutation($id: ID!) { convertPullRequestToDraft(input: { pullRequestId: $id }) { pullRequest { number isDraft } } }',\n variables: { id: pr.node_id },\n });\n if (r?.errors?.length) {\n const detail = r.errors.map((e) => e.message).filter(Boolean).join(' ');\n throw new GitHubError(422, `GitHub refused to turn #${n} back into a draft${detail ? `: ${detail}` : '.'} Use \"Convert to draft\" on GitHub instead.`, detail);\n }\n }\n\n async createPullRequest(input: { title: string; head: string; base: string; body: string; draft: boolean }): Promise<PullRequest> {\n this.assertWritableBranch(input.head, input.base);\n const r = await this.request<{ number: number; html_url: string; title: string; draft?: boolean; head: { ref: string } }>(\n 'POST',\n `${this.repoPath}/pulls`,\n input,\n );\n return { number: r.number, url: r.html_url, title: r.title, draft: !!r.draft, headRef: r.head.ref };\n }\n\n async findOpenPullRequest(branch: string): Promise<PullRequest | undefined> {\n const r = await this.request<{ number: number; html_url: string; title: string; draft?: boolean; head: { ref: string } }[]>(\n 'GET',\n `${this.repoPath}/pulls?state=open&head=${encodeURIComponent(`${this.owner}:${branch}`)}`,\n );\n const pr = r[0];\n return pr ? { number: pr.number, url: pr.html_url, title: pr.title, draft: !!pr.draft, headRef: pr.head.ref } : undefined;\n }\n\n /** Best effort: labels need the repo to allow it; failure is not fatal. */\n async addLabels(issueNumber: number, labels: string[]): Promise<boolean> {\n try {\n await this.request('POST', `${this.repoPath}/issues/${issueNumber}/labels`, { labels });\n return true;\n } catch {\n return false;\n }\n }\n\n async addComment(issueNumber: number, body: string): Promise<void> {\n await this.request('POST', `${this.repoPath}/issues/${issueNumber}/comments`, { body });\n }\n\n /** Comments on an issue or pull request, oldest first (first 100: the sticky preview comment is posted early). */\n async listIssueComments(issueNumber: number): Promise<{ id: number; body: string; author: string; updatedAt: string }[]> {\n const r = await this.request<{ id: number; body?: string | null; user?: { login: string } | null; updated_at: string }[]>('GET', `${this.repoPath}/issues/${issueNumber}/comments?per_page=100`);\n return r.map((c) => ({ id: c.id, body: c.body ?? '', author: c.user?.login ?? 'unknown', updatedAt: c.updated_at }));\n }\n\n // --- Issues (component change requests) ---------------------------------------------------\n\n async createIssue(input: { title: string; body: string; labels?: string[]; assignees?: string[] }): Promise<IssueSummary> {\n const r = await this.request<RawIssue>('POST', `${this.repoPath}/issues`, {\n title: input.title,\n body: input.body,\n ...(input.labels?.length ? { labels: input.labels } : {}),\n ...(input.assignees?.length ? { assignees: input.assignees } : {}),\n });\n return toIssue(r);\n }\n\n /** Issues (not pull requests) with a label, newest first. */\n async listIssues(opts: { label?: string; state?: 'open' | 'closed' | 'all'; perPage?: number } = {}): Promise<IssueSummary[]> {\n const q = new URLSearchParams({ state: opts.state ?? 'all', per_page: String(opts.perPage ?? 50), sort: 'created', direction: 'desc' });\n if (opts.label) q.set('labels', opts.label);\n const r = await this.request<RawIssue[]>('GET', `${this.repoPath}/issues?${q}`);\n return r.filter((i) => !i.pull_request).map(toIssue);\n }\n\n async getIssue(n: number): Promise<IssueSummary> {\n return toIssue(await this.request<RawIssue>('GET', `${this.repoPath}/issues/${n}`));\n }\n\n /** Edits an issue: its body, or closes it with a reason (\"not_planned\" for a declined request). */\n async updateIssue(n: number, patch: { body?: string; state?: 'open' | 'closed'; state_reason?: 'completed' | 'not_planned' | 'reopened' }): Promise<IssueSummary> {\n this.assertToken('Editing an issue');\n return toIssue(await this.request<RawIssue>('PATCH', `${this.repoPath}/issues/${n}`, patch));\n }\n\n /** Adds people to an issue's assignees (GitHub ignores logins that cannot be assigned: the result says who is). */\n async addAssignees(n: number, logins: string[]): Promise<string[]> {\n this.assertToken('Assigning an issue');\n const r = await this.request<{ assignees?: { login: string }[] | null }>('POST', `${this.repoPath}/issues/${n}/assignees`, { assignees: logins });\n return (r.assignees ?? []).map((a) => a.login);\n }\n\n /** People with at least `permission` on the repository (reading the list needs push access). First 100. */\n async listCollaborators(permission: 'pull' | 'triage' | 'push' | 'maintain' | 'admin' = 'push'): Promise<{ login: string; avatarUrl: string }[]> {\n const r = await this.request<{ login: string; avatar_url?: string }[]>('GET', `${this.repoPath}/collaborators?permission=${permission}&per_page=100`);\n return r.map((c) => ({ login: c.login, avatarUrl: c.avatar_url ?? '' }));\n }\n\n /** Whether a token is sent with each request (TeamReader). */\n get hasToken(): boolean {\n return Boolean(this.token);\n }\n\n /** Every page of a list endpoint (per_page 100), up to `maxPages`. */\n private async paginate<T>(path: string, maxPages = 20): Promise<T[]> {\n const out: T[] = [];\n const sep = path.includes('?') ? '&' : '?';\n for (let page = 1; page <= maxPages; page++) {\n const r = await this.request<T[]>('GET', `${path}${sep}per_page=100&page=${page}`);\n out.push(...r);\n if (r.length < 100) break;\n }\n return out;\n }\n\n /** Every member login of an organization team (needs read:org, or Members: Read on a fine-grained token). */\n async listTeamMembers(org: string, slug: string): Promise<string[]> {\n const r = await this.paginate<{ login: string }>(`/orgs/${encodeURIComponent(org)}/teams/${encodeURIComponent(slug)}/members`);\n return r.map((m) => m.login);\n }\n\n /** A user's membership of a team: \"active\", \"pending\", or null when GitHub says they are not a member (404). */\n async getTeamMembership(org: string, slug: string, login: string): Promise<'active' | 'pending' | null> {\n try {\n const r = await this.request<{ state: string }>('GET', `/orgs/${encodeURIComponent(org)}/teams/${encodeURIComponent(slug)}/memberships/${encodeURIComponent(login)}`);\n return r.state === 'active' ? 'active' : 'pending';\n } catch (err) {\n if (err instanceof GitHubError && err.status === 404) return null;\n throw err;\n }\n }\n\n /** \"User\" or \"Organization\" for a login, null when GitHub does not know it. */\n async getAccountType(login: string): Promise<'User' | 'Organization' | null> {\n try {\n const r = await this.request<{ type?: string }>('GET', `/users/${encodeURIComponent(login)}`);\n return r.type === 'Organization' ? 'Organization' : r.type === 'User' ? 'User' : null;\n } catch (err) {\n if (err instanceof GitHubError && err.status === 404) return null;\n throw err;\n }\n }\n\n /** The organization's teams this token can see. */\n async listOrgTeams(org: string): Promise<{ slug: string; name: string }[]> {\n const r = await this.paginate<{ slug: string; name: string }>(`/orgs/${encodeURIComponent(org)}/teams`);\n return r.map((t) => ({ slug: t.slug, name: t.name }));\n }\n\n /** Create or update a binary file (base64 content) on a branch, e.g. a Figma export attached to a request. */\n async putBase64File(input: { path: string; base64: string; branch: string; message: string }): Promise<string> {\n this.assertWritableBranch(input.branch);\n const r = await this.request<{ commit: { sha: string } }>('PUT', `${this.repoPath}/contents/${encodeRef(input.path)}`, {\n message: input.message,\n content: input.base64,\n branch: input.branch,\n });\n return r.commit.sha;\n }\n\n // --- Contents API: single files -----------------------------------------------------------\n\n /** Text of one file at a ref (branch, tag or sha), or undefined when it does not exist. */\n async getFileText(path: string, ref?: string): Promise<string | undefined> {\n try {\n const q = ref ? `?ref=${encodeURIComponent(ref)}` : '';\n const r = await this.request<{ content?: string; encoding?: string; sha: string; type: string }>('GET', `${this.repoPath}/contents/${encodeRef(path)}${q}`);\n if (r.type !== 'file') return undefined;\n if (r.encoding === 'base64' && r.content !== undefined) return base64ToUtf8(r.content);\n return r.content;\n } catch (err) {\n if (err instanceof GitHubError && err.status === 404) return undefined;\n throw err;\n }\n }\n\n /**\n * Text and blob sha of one file at a ref, or undefined when it does not exist. The sha is what an update or a\n * delete must send back (optimistic concurrency: GitHub answers 409 when the file changed since).\n */\n async getFile(path: string, ref?: string): Promise<{ text: string; sha: string } | undefined> {\n try {\n const q = ref ? `?ref=${encodeURIComponent(ref)}` : '';\n const r = await this.request<{ content?: string; encoding?: string; sha: string; type: string }>('GET', `${this.repoPath}/contents/${encodeRef(path)}${q}`);\n if (r.type !== 'file') return undefined;\n const text = r.encoding === 'base64' && r.content !== undefined ? base64ToUtf8(r.content) : (r.content ?? '');\n return { text, sha: r.sha };\n } catch (err) {\n if (err instanceof GitHubError && err.status === 404) return undefined;\n throw err;\n }\n }\n\n /**\n * Base64 content of a binary file at a ref (an image), or undefined when it does not exist or is too large for the\n * contents API to inline (over 1 MB).\n */\n async getFileBase64(path: string, ref?: string): Promise<{ base64: string; size: number } | undefined> {\n try {\n const q = ref ? `?ref=${encodeURIComponent(ref)}` : '';\n const r = await this.request<{ content?: string; encoding?: string; size?: number; type: string }>('GET', `${this.repoPath}/contents/${encodeRef(path)}${q}`);\n if (r.type !== 'file' || r.encoding !== 'base64' || !r.content) return undefined;\n return { base64: r.content.replace(/\\s+/g, ''), size: r.size ?? 0 };\n } catch (err) {\n if (err instanceof GitHubError && err.status === 404) return undefined;\n throw err;\n }\n }\n\n /** Entries of one folder at a ref (contents API), or an empty list when the folder does not exist. */\n async listDirectory(path: string, ref?: string): Promise<{ name: string; path: string; type: string; sha: string; size: number }[]> {\n try {\n const q = ref ? `?ref=${encodeURIComponent(ref)}` : '';\n const r = await this.request<unknown>('GET', `${this.repoPath}/contents/${encodeRef(path)}${q}`);\n if (!Array.isArray(r)) return [];\n return (r as { name: string; path: string; type: string; sha: string; size?: number }[]).map((e) => ({ name: e.name, path: e.path, type: e.type, sha: e.sha, size: e.size ?? 0 }));\n } catch (err) {\n if (err instanceof GitHubError && err.status === 404) return [];\n throw err;\n }\n }\n\n /** Deletes one file on a branch in its own commit (contents API). `sha` is the file's blob sha. */\n async deleteFile(input: { path: string; branch: string; message: string; sha: string }): Promise<string> {\n this.assertToken('Deleting a file');\n this.assertWritableBranch(input.branch);\n const r = await this.request<{ commit: { sha: string } }>('DELETE', `${this.repoPath}/contents/${encodeRef(input.path)}`, {\n message: input.message,\n branch: input.branch,\n sha: input.sha,\n });\n return r.commit.sha;\n }\n\n /** Create or update one file on a branch in its own commit (contents API). Returns the commit sha. */\n async putFile(input: { path: string; content: string; branch: string; message: string; sha?: string | undefined }): Promise<string> {\n this.assertWritableBranch(input.branch);\n const r = await this.request<{ commit: { sha: string } }>('PUT', `${this.repoPath}/contents/${encodeRef(input.path)}`, {\n message: input.message,\n content: utf8ToBase64(input.content),\n branch: input.branch,\n ...(input.sha ? { sha: input.sha } : {}),\n });\n return r.commit.sha;\n }\n\n /**\n * Text of a file at a ref, or undefined. Without a token, public repos are read from the raw host (no\n * hourly API limit); with one, through the contents API (private repos work).\n */\n async readFile(path: string, ref: string): Promise<string | undefined> {\n if (this.token) return this.getFileText(path, ref);\n const url = `${(this.options.rawUrl ?? RAW).replace(/\\/$/, '')}/${this.owner}/${this.name}/${encodeRef(ref)}/${encodeRef(path)}`;\n let res: Awaited<ReturnType<FetchLike>>;\n try {\n res = await this.fetchImpl(url, {});\n } catch (err) {\n throw new GitHubError(0, 'Could not reach GitHub. Check your connection, then try again.', (err as Error).message);\n }\n if (res.status === 404) return undefined;\n if (!res.ok) throw new GitHubError(res.status, friendlyMessage(res.status, ''), `raw ${path}@${ref}`);\n return res.text();\n }\n\n /** The repository's default branch. */\n async getDefaultBranch(): Promise<string> {\n return (await this.getRepo()).defaultBranch;\n }\n\n /** Every file path at a ref (branch, tag or sha), one API call. */\n async listFiles(ref: string): Promise<string[]> {\n const r = await this.request<{ tree: { path: string; type: string }[]; truncated: boolean }>('GET', `${this.repoPath}/git/trees/${encodeRef(ref)}?recursive=1`);\n if (r.truncated) throw new GitHubError(413, 'The repository tree is too large to read in one request.');\n return r.tree.filter((e) => e.type === 'blob').map((e) => e.path);\n }\n\n // --- Pull requests, reviews, checks ---------------------------------------------------------\n\n async listPullRequests(state: 'open' | 'closed' | 'all' = 'open'): Promise<PullRequestSummary[]> {\n const r = await this.request<Record<string, any>[]>('GET', `${this.repoPath}/pulls?state=${state}&per_page=50&sort=updated&direction=desc`);\n return r.map(toSummary);\n }\n\n /** Commit statuses and check runs of a commit, folded into one state. */\n async getChecks(sha: string): Promise<{ state: 'success' | 'failure' | 'pending' | 'none'; checks: { name: string; status: string; conclusion: string | null }[] }> {\n const [combined, runs] = await Promise.all([\n this.request<{ statuses: { context: string; state: string }[] }>('GET', `${this.repoPath}/commits/${encodeRef(sha)}/status`).catch(() => ({ statuses: [] })),\n this.listCheckRuns(sha).catch(() => [] as CheckRun[]),\n ]);\n const checks = [\n ...runs.map((c) => ({ name: c.name, status: c.status, conclusion: c.conclusion })),\n ...combined.statuses.map((s) => ({ name: s.context, status: s.state === 'pending' ? 'in_progress' : 'completed', conclusion: s.state === 'pending' ? null : s.state })),\n ];\n const failing = checks.some((c) => c.conclusion && !['success', 'neutral', 'skipped'].includes(c.conclusion));\n const pending = checks.some((c) => c.status !== 'completed');\n return { state: !checks.length ? 'none' : failing ? 'failure' : pending ? 'pending' : 'success', checks };\n }\n\n /** Commit statuses of a commit, newest first (Vercel reports each project as \"Vercel – <project>\"). */\n async listCommitStatuses(sha: string): Promise<{ context: string; state: string; target_url: string | null; description: string | null }[]> {\n const r = await this.request<{ context: string; state: string; target_url?: string | null; description?: string | null }[]>('GET', `${this.repoPath}/commits/${encodeRef(sha)}/statuses?per_page=100`);\n return r.map((s) => ({ context: s.context, state: s.state, target_url: s.target_url ?? null, description: s.description ?? null }));\n }\n\n /**\n * GitHub deployments of a commit with their latest status (environment \"Preview – <project>\", environment_url the\n * preview). Latest per environment only, so it costs one read plus one per environment.\n */\n async listDeployments(sha: string): Promise<{ id: number; environment: string; state: string | null; environmentUrl: string | null }[]> {\n const list = await this.request<{ id: number; environment: string; created_at?: string }[]>('GET', `${this.repoPath}/deployments?sha=${encodeURIComponent(sha)}&per_page=30`);\n const latest = new Map<string, { id: number; environment: string }>();\n for (const d of list) if (!latest.has(d.environment)) latest.set(d.environment, d);\n return Promise.all(\n [...latest.values()].map(async (d) => {\n const st = await this.request<{ state: string; environment_url?: string | null; target_url?: string | null }[]>('GET', `${this.repoPath}/deployments/${d.id}/statuses?per_page=1`).catch(() => []);\n const s = st[0];\n return { id: d.id, environment: d.environment, state: s?.state ?? null, environmentUrl: s?.environment_url || null };\n }),\n );\n }\n\n async getPullRequest(n: number): Promise<PullRequest & PullRequestSummary & { body: string; mergeable: boolean | null; requestedReviewers: string[] }> {\n const r = await this.request<Record<string, any>>('GET', `${this.repoPath}/pulls/${n}`);\n return { ...toSummary(r), body: r.body ?? '', mergeable: r.mergeable ?? null, requestedReviewers: ((r.requested_reviewers ?? []) as { login: string }[]).map((x) => x.login) };\n }\n\n async listPullRequestFiles(n: number): Promise<PullRequestFile[]> {\n const r = await this.request<{ filename: string; status: string; additions: number; deletions: number }[]>('GET', `${this.repoPath}/pulls/${n}/files?per_page=100`);\n return r.map((f) => ({ filename: f.filename, status: f.status, additions: f.additions, deletions: f.deletions }));\n }\n\n async updatePullRequest(n: number, patch: { title?: string; body?: string; state?: 'open' | 'closed' }): Promise<void> {\n await this.request('PATCH', `${this.repoPath}/pulls/${n}`, patch);\n }\n\n async listReviews(n: number): Promise<Review[]> {\n const r = await this.request<{ id: number; user?: { login: string }; state: string; body: string | null; submitted_at?: string }[]>('GET', `${this.repoPath}/pulls/${n}/reviews`);\n return r.map((x) => ({ id: x.id, user: x.user?.login, state: x.state, body: x.body ?? '', ...(x.submitted_at ? { submittedAt: x.submitted_at } : {}) }));\n }\n\n /** Submit a review. `COMMENT` works for any collaborator; approving your own PR is refused by GitHub. */\n async createReview(n: number, input: { event: 'COMMENT' | 'APPROVE' | 'REQUEST_CHANGES'; body: string }): Promise<Review> {\n this.assertToken('Reviewing a pull request');\n const r = await this.request<{ id: number; user?: { login: string }; state: string; body: string | null }>('POST', `${this.repoPath}/pulls/${n}/reviews`, input);\n return { id: r.id, user: r.user?.login, state: r.state, body: r.body ?? '' };\n }\n\n async listCheckRuns(ref: string): Promise<CheckRun[]> {\n const r = await this.request<{ check_runs: { id: number; name: string; status: string; conclusion: string | null; html_url?: string; app?: { slug?: string } | null }[] }>(\n 'GET',\n `${this.repoPath}/commits/${encodeRef(ref)}/check-runs`,\n );\n return r.check_runs.map((c) => ({ id: c.id, name: c.name, status: c.status, conclusion: c.conclusion, url: c.html_url, ...(c.app?.slug ? { app: c.app.slug } : {}) }));\n }\n\n /** Rulesets that apply to the repository, without their rules (GET /rulesets; read access is enough). */\n async listRulesets(): Promise<Ruleset[]> {\n const r = await this.request<(Ruleset & { _links?: { html?: { href?: string } } })[]>('GET', `${this.repoPath}/rulesets?includes_parents=true&per_page=100`);\n return r.map(withRulesetUrl);\n }\n\n /** One ruleset with its rules. */\n async getRuleset(id: number): Promise<Ruleset> {\n return withRulesetUrl(await this.request<Ruleset>('GET', `${this.repoPath}/rulesets/${id}`));\n }\n\n /** Creates a repository ruleset. Needs admin on the repo (fine-grained token: Administration read and write). */\n async createRuleset(payload: RulesetPayload): Promise<Ruleset> {\n this.assertToken('Protecting the library');\n return withRulesetUrl(await this.request<Ruleset>('POST', `${this.repoPath}/rulesets`, payload));\n }\n\n /** Replaces a repository ruleset (same permissions as createRuleset). */\n async updateRuleset(id: number, payload: RulesetPayload): Promise<Ruleset> {\n this.assertToken('Protecting the library');\n return withRulesetUrl(await this.request<Ruleset>('PUT', `${this.repoPath}/rulesets/${id}`, payload));\n }\n\n /**\n * Classic branch protection of `branch`: the settings, null when the branch has none (404), undefined when this\n * token cannot read them (403: the endpoint needs admin). On a 403 the public branch summary still tells\n * whether the branch is protected at all: `protected: false` means there is nothing to read, so null.\n */\n async getBranchProtection(branch: string): Promise<ClassicProtection | null | undefined> {\n try {\n return await this.request<ClassicProtection>('GET', `${this.repoPath}/branches/${encodeRef(branch)}/protection`);\n } catch (err) {\n if (!(err instanceof GitHubError)) throw err;\n if (err.status === 404) return null;\n if (err.status === 403 || err.status === 401) {\n const b = await this.request<{ protected?: boolean }>('GET', `${this.repoPath}/branches/${encodeRef(branch)}`).catch(() => undefined);\n return b?.protected === false ? null : undefined;\n }\n throw err;\n }\n }\n\n /** Create a check run (needs a GitHub App token; personal tokens are refused by GitHub). */\n async createCheckRun(input: {\n name: string;\n headSha: string;\n status?: 'queued' | 'in_progress' | 'completed';\n conclusion?: 'success' | 'failure' | 'neutral' | 'cancelled' | 'skipped' | 'timed_out' | 'action_required';\n output?: { title: string; summary: string; text?: string };\n }): Promise<CheckRun> {\n const r = await this.request<{ id: number; name: string; status: string; conclusion: string | null; html_url?: string }>('POST', `${this.repoPath}/check-runs`, {\n name: input.name,\n head_sha: input.headSha,\n ...(input.status ? { status: input.status } : {}),\n ...(input.conclusion ? { conclusion: input.conclusion } : {}),\n ...(input.output ? { output: input.output } : {}),\n });\n return { id: r.id, name: r.name, status: r.status, conclusion: r.conclusion, url: r.html_url };\n }\n\n async removeLabel(issueNumber: number, label: string): Promise<void> {\n await this.request('DELETE', `${this.repoPath}/issues/${issueNumber}/labels/${encodeURIComponent(label)}`);\n }\n\n // --- branch actions shared by Studio, the MCP server and the CLI (branch-actions.ts) ---\n\n /** The account the token belongs to (GET /user). Needs a token. */\n async getViewer(): Promise<{ login: string }> {\n this.assertToken('Reading who you are on GitHub');\n const r = await this.request<{ login: string }>('GET', '/user');\n return { login: r.login };\n }\n\n /** The repository's merge settings and the viewer's permissions (unknown settings count as allowed). */\n async getMergeSettings(): Promise<{ allow_squash_merge?: boolean; allow_merge_commit?: boolean; allow_rebase_merge?: boolean; permissions?: { admin?: boolean; maintain?: boolean; push?: boolean } }> {\n return this.request('GET', this.repoPath);\n }\n\n /**\n * Merges a pull request, only at `sha` (GitHub refuses when the branch moved meanwhile). The repository's branch\n * rules still apply: GitHub refuses a merge they block, whatever Bridge says.\n */\n async mergePullRequest(n: number, input: { method: 'squash' | 'merge' | 'rebase'; sha: string; commitMessage?: string | undefined }): Promise<{ sha: string; merged: boolean }> {\n this.assertToken('Merging a branch');\n const r = await this.request<{ sha: string; merged: boolean }>('PUT', `${this.repoPath}/pulls/${n}/merge`, {\n merge_method: input.method,\n sha: input.sha,\n ...(input.commitMessage !== undefined && input.method !== 'rebase' ? { commit_message: input.commitMessage } : {}),\n });\n return { sha: r?.sha ?? '', merged: r?.merged ?? true };\n }\n\n /** GitHub's \"Update branch\": merges the base into the pull request, only when its head is still `expectedHeadSha`. */\n async updatePullRequestBranch(n: number, expectedHeadSha: string): Promise<void> {\n this.assertToken('Updating a branch from main');\n await this.request('PUT', `${this.repoPath}/pulls/${n}/update-branch`, { expected_head_sha: expectedHeadSha });\n }\n\n /**\n * Merges the branch `head` into the branch `base` (GitHub's merges API): a merge commit on `base`, or nothing when\n * `base` already has every commit of `head`. A conflict throws a GitHubError with status 409. Refuses protected\n * branches and, with a branch prefix, a `base` without it.\n */\n async mergeIntoBranch(base: string, head: string, message: string): Promise<{ status: 'merged' | 'up-to-date'; sha: string | null }> {\n this.assertToken('Merging a branch into another');\n this.assertWritableBranch(base);\n const r = await this.request<{ sha?: string } | undefined>('POST', `${this.repoPath}/merges`, { base, head, commit_message: message });\n return r?.sha ? { status: 'merged', sha: r.sha } : { status: 'up-to-date', sha: null };\n }\n\n /** Posts a comment on an issue or pull request and returns its id and link. */\n async createIssueComment(n: number, body: string): Promise<{ id: number; url: string }> {\n this.assertToken('Commenting');\n const r = await this.request<{ id: number; html_url: string }>('POST', `${this.repoPath}/issues/${n}/comments`, { body });\n return { id: r.id, url: r.html_url };\n }\n\n /** Replaces the text of a comment. */\n async updateIssueComment(id: number, body: string): Promise<void> {\n this.assertToken('Editing a comment');\n await this.request('PATCH', `${this.repoPath}/issues/comments/${id}`, { body });\n }\n\n /** Submits a review on a given commit (the head the reviewer saw); the body may be empty for an approval. */\n async submitReview(n: number, input: { event: 'COMMENT' | 'APPROVE' | 'REQUEST_CHANGES'; body?: string | undefined; commitId?: string | undefined }): Promise<Review> {\n this.assertToken('Reviewing a branch');\n const r = await this.request<{ id: number; user?: { login: string }; state: string; body: string | null }>('POST', `${this.repoPath}/pulls/${n}/reviews`, {\n event: input.event,\n ...(input.body ? { body: input.body } : {}),\n ...(input.commitId ? { commit_id: input.commitId } : {}),\n });\n return { id: r.id, user: r.user?.login, state: r.state, body: r.body ?? '' };\n }\n\n /** Line comments of a pull request (review threads), oldest first. */\n async listReviewComments(n: number): Promise<{ id: number; body: string; author: string; path: string; line: number | null; inReplyTo: number | null; url: string; createdAt: string }[]> {\n const r = await this.request<{ id: number; body?: string | null; user?: { login: string } | null; path: string; line?: number | null; in_reply_to_id?: number; html_url: string; created_at: string }[]>(\n 'GET',\n `${this.repoPath}/pulls/${n}/comments?per_page=100`,\n );\n return r.map((c) => ({ id: c.id, body: c.body ?? '', author: c.user?.login ?? 'unknown', path: c.path, line: c.line ?? null, inReplyTo: c.in_reply_to_id ?? null, url: c.html_url, createdAt: c.created_at }));\n }\n\n /** Asks these people to review a pull request. */\n async requestReviewers(n: number, logins: string[]): Promise<void> {\n this.assertToken('Asking for a review');\n await this.request('POST', `${this.repoPath}/pulls/${n}/requested_reviewers`, { reviewers: logins });\n }\n\n /** Takes these people off the requested reviewers. */\n async removeRequestedReviewers(n: number, logins: string[]): Promise<void> {\n this.assertToken('Changing the requested reviewers');\n await this.request('DELETE', `${this.repoPath}/pulls/${n}/requested_reviewers`, { reviewers: logins });\n }\n\n /** Replies in the thread of a line comment. */\n async replyToReviewComment(n: number, commentId: number, body: string): Promise<{ id: number; url: string }> {\n this.assertToken('Replying to a comment');\n const r = await this.request<{ id: number; html_url: string }>('POST', `${this.repoPath}/pulls/${n}/comments/${commentId}/replies`, { body });\n return { id: r.id, url: r.html_url };\n }\n\n /**\n * What `head` adds on top of `base`, with what library sync needs: the shared start (merge base), the base\n * commit and its tree, how far behind, and the files with their previous names.\n */\n async compareDetailed(base: string, head: string): Promise<{\n behindBy: number;\n aheadBy: number;\n mergeBase: string | null;\n baseSha: string | null;\n baseTree: string | null;\n files: { filename: string; status: string; previous_filename?: string | undefined }[];\n }> {\n const r = await this.request<{\n ahead_by: number;\n behind_by: number;\n merge_base_commit?: { sha?: string };\n base_commit?: { sha?: string; commit?: { tree?: { sha?: string } } };\n files?: { filename: string; status: string; previous_filename?: string }[];\n }>('GET', `${this.repoPath}/compare/${encodeRef(base)}...${encodeRef(head)}`);\n return {\n behindBy: r.behind_by,\n aheadBy: r.ahead_by,\n mergeBase: r.merge_base_commit?.sha ?? null,\n baseSha: r.base_commit?.sha ?? null,\n baseTree: r.base_commit?.commit?.tree?.sha ?? null,\n files: (r.files ?? []).map((f) => ({ filename: f.filename, status: f.status, ...(f.previous_filename ? { previous_filename: f.previous_filename } : {}) })),\n };\n }\n\n /** A tree on top of `baseTree` from entries with their own file mode (blob sha, inline content, or sha null to delete). */\n async createTreeEntries(baseTree: string, entries: ({ path: string; mode: string; sha: string | null } | { path: string; mode: string; content: string })[]): Promise<string> {\n const r = await this.request<{ sha: string }>('POST', `${this.repoPath}/git/trees`, { base_tree: baseTree, tree: entries.map((e) => ({ ...e, type: 'blob' })) }, true);\n return r.sha;\n }\n}\n\nfunction toCommitSummary(c: Record<string, any>): CommitSummary {\n return {\n sha: c.sha,\n parents: (c.parents ?? []).map((p: { sha: string }) => p.sha),\n date: c.commit?.committer?.date ?? c.commit?.author?.date ?? '',\n author: c.author?.login ?? c.commit?.author?.name ?? 'unknown',\n message: c.commit?.message ?? '',\n };\n}\n\nfunction toSummary(r: Record<string, any>): PullRequestSummary & PullRequest {\n return {\n number: r.number,\n title: r.title,\n state: r.merged_at || r.merged ? 'merged' : r.state,\n draft: Boolean(r.draft),\n author: r.user?.login ?? 'unknown',\n headRef: r.head?.ref,\n headSha: r.head?.sha,\n baseRef: r.base?.ref,\n labels: (r.labels ?? []).map((l: { name: string }) => l.name),\n url: r.html_url,\n updatedAt: r.updated_at,\n ...(typeof r.body === 'string' ? { body: r.body } : {}),\n };\n}\n\nexport function friendlyMessage(status: number, detail: string, info: GitHubErrorInfo = {}): string {\n if (info.auth === 'rejected') return TOKEN_REJECTED_MESSAGE;\n if (info.auth === 'missing-permission') return missingPermissionMessage(info.permission);\n switch (status) {\n case 401:\n return 'GitHub rejected the token. It may be expired or mistyped: create a new one and save it in Settings.';\n case 403:\n if (/rate limit/i.test(detail)) return 'GitHub is limiting requests right now. Wait a minute, then try again.';\n if (/archived/i.test(detail)) return 'This repository is archived and read-only.';\n return 'The token does not have permission for this. It needs \"Contents: read and write\" and \"Pull requests: read and write\" on this repository.';\n case 404:\n return 'Repository, branch or file not found, or the token cannot see this repository.';\n case 409:\n return 'GitHub reported a conflict (the branch moved while saving). Scan again, then retry.';\n case 429:\n return 'GitHub is limiting requests right now. Wait a minute, then try again.';\n case 422:\n return `GitHub refused the request${detail ? `: ${detail}` : '.'}`;\n default:\n return `GitHub error ${status}${detail ? `: ${detail}` : ''}`;\n }\n}\n\nexport interface RepoFiles {\n commitSha: string;\n treeSha: string;\n /** Token files relative to the tokens root. */\n files: Record<string, string>;\n /** Contents of the contrast checks file (tokens.contrastChecks in the config), when present. */\n contrastChecks: string | undefined;\n /** bridge.config.json at the repository root, parsed; undefined when the repo has none. */\n config: BridgeConfig | undefined;\n /** bridge.config.json as written, for minimal-diff edits (a new brand); undefined when the repo has none. */\n configText?: string | undefined;\n /** Tokens root actually used (from the config when present, else the fallback). */\n tokensPath: string;\n /** Problems reading the config (it is then ignored and the fallback is used). */\n warnings: string[];\n}\n\n/**\n * Read every *.tokens.json under the tokens root, plus the contrast checks file, at a commit.\n * The tokens root and the checks file come from bridge.config.json at the repository root when it\n * exists; otherwise from `fallbackTokensPath` and the default layout.\n */\nexport async function loadRepoFiles(client: GitHubClient, commitSha: string, fallbackTokensPath: string): Promise<RepoFiles> {\n const treeSha = await client.getCommitTree(commitSha);\n const { entries, truncated } = await client.getTree(treeSha, true);\n if (truncated) throw new Error('The repository tree is too large to read in one request.');\n const warnings: string[] = [];\n let config: BridgeConfig | undefined;\n let configText: string | undefined;\n const configEntry = entries.find((e) => e.type === 'blob' && e.path === CONFIG_FILE);\n if (configEntry) {\n try {\n configText = await client.getBlobText(configEntry.sha);\n config = loadConfig(configText);\n } catch (err) {\n warnings.push(err instanceof ConfigError ? `${err.message}. Using ${fallbackTokensPath} instead.` : `${CONFIG_FILE} could not be read.`);\n }\n }\n const tokensPath = (config?.tokens.root ?? fallbackTokensPath).replace(/^\\/+|\\/+$/g, '');\n const checksFile = config?.tokens.contrastChecks ?? DEFAULT_TOKEN_PATHS.contrastChecks;\n const prefix = tokensPath + '/';\n const wanted = entries.filter(\n (e) => e.type === 'blob' && e.path.startsWith(prefix) && (e.path.endsWith('.tokens.json') || e.path === prefix + checksFile),\n );\n if (!wanted.some((e) => e.path.endsWith('.tokens.json'))) throw new Error(`No *.tokens.json files found under ${tokensPath} at ${commitSha.slice(0, 7)}.`);\n const files: Record<string, string> = {};\n let contrastChecks: string | undefined;\n // Small concurrency limit: friendly to rate limits, still quick for a handful of files.\n const queue = [...wanted];\n const worker = async () => {\n for (let e = queue.shift(); e; e = queue.shift()) {\n const text = await client.getBlobText(e.sha);\n const rel = e.path.slice(prefix.length);\n if (rel === checksFile) contrastChecks = text;\n else files[rel] = text;\n }\n };\n await Promise.all([worker(), worker(), worker(), worker()]);\n return { commitSha, treeSha, files, contrastChecks, config, ...(config ? { configText } : {}), tokensPath, warnings };\n}\n\n/** Lifts the ruleset's GitHub page (`_links.html.href`) to `html_url`. */\nfunction withRulesetUrl(r: Ruleset): Ruleset {\n const href = r._links?.html?.href;\n return href && !r.html_url ? { ...r, html_url: href } : r;\n}\n\nexport interface IssueSummary {\n number: number;\n title: string;\n body: string;\n url: string;\n state: 'open' | 'closed';\n stateReason: string | null;\n labels: string[];\n author: string;\n createdAt: string;\n updatedAt: string;\n}\n\ninterface RawIssue {\n number: number;\n title: string;\n body: string | null;\n html_url: string;\n state: 'open' | 'closed';\n state_reason?: string | null;\n labels: (string | { name?: string })[];\n user?: { login?: string } | null;\n created_at: string;\n updated_at: string;\n pull_request?: unknown;\n}\n\nfunction toIssue(r: RawIssue): IssueSummary {\n return {\n number: r.number,\n title: r.title,\n body: r.body ?? '',\n url: r.html_url,\n state: r.state,\n stateReason: r.state_reason ?? null,\n labels: r.labels.map((l) => (typeof l === 'string' ? l : (l.name ?? ''))).filter(Boolean),\n author: r.user?.login ?? '',\n createdAt: r.created_at,\n updatedAt: r.updated_at,\n };\n}\n","// Library protection over the GitHub client: read the state of the default branch, read the checks to require,\n// and create (or complete) the Bridge ruleset. Studio, the CLI and the MCP server call these.\n\nimport { GitHubError, type GitHubClient } from './github-client';\nimport { type ProtectionOptions, protectionRuleset, type ProtectionState, protectionState, requiredCheckNames, type Ruleset } from './protection';\n\n/**\n * The protection of `defaultBranch`. Rulesets are listed (read access is enough), then read one by one for their\n * rules; classic branch protection is read too. Whatever cannot be read counts as unknown, never as unprotected.\n */\nexport async function loadProtection(client: GitHubClient, defaultBranch: string): Promise<ProtectionState> {\n const rulesets = await client\n .listRulesets()\n // Disabled rulesets enforce nothing: kept as listed (the Bridge one is still found by name, to update it).\n .then((list) => Promise.all(list.map((r) => (r.enforcement === 'disabled' || r.id === undefined ? r : client.getRuleset(r.id)))))\n // Any failure (no access, a repo GitHub hides behind a 404, rate limit) leaves the state unknown.\n .catch((): Ruleset[] | null => null);\n const classic = await client.getBranchProtection(defaultBranch).catch(() => undefined);\n return protectionState(rulesets, classic, defaultBranch);\n}\n\n/** The checks to require: the default branch's latest check runs, kept to those the last merged pull request ran. */\nexport async function loadRequiredChecks(client: GitHubClient, defaultBranch: string): Promise<string[]> {\n const onDefault = await client.listCheckRuns(defaultBranch).catch(() => []);\n const merged = await client\n .listPullRequests('closed')\n .then((prs) => prs.find((p) => p.state === 'merged' && p.baseRef === defaultBranch))\n .catch(() => undefined);\n const onPull = merged?.headSha ? await client.listCheckRuns(merged.headSha).catch(() => []) : [];\n return requiredCheckNames(onDefault, onPull);\n}\n\n/**\n * Turns protection on: creates the Bridge ruleset, or replaces it when one with its name exists (Complete\n * protection). Needs a token with admin on the repository; GitHub's refusal is thrown as a GitHubError.\n */\nexport async function protectLibrary(\n client: GitHubClient,\n defaultBranch: string,\n opts: Partial<ProtectionOptions> & { state?: ProtectionState } = {},\n): Promise<Ruleset> {\n const checks = opts.checks ?? (await loadRequiredChecks(client, defaultBranch));\n const payload = protectionRuleset({ repo: { defaultBranch } }, { checks, approvals: opts.approvals ?? 1, adminBypass: opts.adminBypass ?? true });\n const id = opts.state?.bridgeRulesetId;\n return id !== undefined ? client.updateRuleset(id, payload) : client.createRuleset(payload);\n}\n\n/** GitHub's message when the plan does not allow rulesets on a private repository. */\nconst PLAN_REFUSED = /upgrade to github (pro|team)|make this repository public|not available for private repositories/i;\n\n/** True when GitHub refused the ruleset because of the repository's plan, not the token. */\nexport const isPlanRefusal = (err: unknown) => err instanceof GitHubError && (err.status === 403 || err.status === 422) && PLAN_REFUSED.test(`${err.detail ?? ''} ${err.message}`);\n\n/** Where rulesets are managed on GitHub. */\nexport const rulesSettingsUrl = (owner: string, repo: string) => `https://github.com/${owner}/${repo}/settings/rules`;\n\n/**\n * The one sentence for a refused \"Protect the library\": the plan, the token's permission, or admin access.\n * Null for any other failure (the caller shows GitHub's message).\n */\nexport function protectRefusal(err: unknown): string | null {\n if (!(err instanceof GitHubError)) return null;\n if (isPlanRefusal(err)) return \"GitHub's plan for this private repository does not include protection rules. Upgrade the plan or make the repository public, then try again.\";\n // \"Must have admin rights\": the person is not an admin, whatever the token allows.\n if (/admin rights/i.test(`${err.detail ?? ''}`)) return 'Only a repository admin can protect the library. Ask an admin, or set it up in GitHub settings.';\n if (err.auth === 'missing-permission') return 'This token cannot change the protection. Add Administration: Read and write to the token on GitHub, then try again.';\n if (err.status === 403 || err.status === 404) return 'Only a repository admin can protect the library. Ask an admin, or set it up in GitHub settings.';\n return null;\n}\n","// Usage index: which CSS custom properties each component module reads, and which other components it renders.\n// Pure text scanning (no CSS or TypeScript parser), so it runs in Node, the browser and the Figma sandbox alike.\n// Used by visual impact analysis to go from changed tokens and files to the components (and stories) to look at.\n\nexport interface UsageFile {\n /** Repo-relative path with forward slashes. */\n path: string;\n text: string;\n}\n\nexport interface UsageModule {\n /** Component folder name, e.g. \"Button\". */\n id: string;\n dir: string;\n files: string[];\n /** CSS custom properties read with var(), sorted. Includes locally defined ones. */\n vars: string[];\n /** Other components this one imports from its source (stories and tests excluded), sorted. */\n imports: string[];\n /** Components that only its stories import (e.g. a Button inside an Alert story), sorted. */\n storyImports: string[];\n}\n\nexport interface UsageIndex {\n componentsDir: string;\n modules: Record<string, UsageModule>;\n /** CSS custom property -> modules that read it. */\n byVar: Record<string, string[]>;\n /** CSS custom properties read by files outside the component folders (global styles, theme). */\n globalVars: Record<string, string[]>;\n}\n\nconst VAR_RE = /var\\(\\s*(--[A-Za-z0-9_-]+)/g;\nconst IMPORT_RE = /(?:import|export)\\s[^'\"]*?from\\s*['\"]([^'\"]+)['\"]|import\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g;\n\n/** CSS custom properties read with `var(--x)` in a stylesheet or a style string, in order of first use. */\nexport function cssVarsIn(text: string): string[] {\n const out = new Set<string>();\n for (const m of text.matchAll(VAR_RE)) out.add(m[1]!);\n return [...out];\n}\n\n/** Module specifiers a TS/JS file imports or re-exports. */\nexport function importsIn(text: string): string[] {\n const out = new Set<string>();\n for (const m of text.matchAll(IMPORT_RE)) out.add((m[1] ?? m[2])!);\n return [...out];\n}\n\nconst norm = (p: string) => p.replace(/\\\\/g, '/').replace(/\\/+$/, '');\nconst isStory = (p: string) => /\\.stories\\.[cm]?[jt]sx?$/.test(p);\nconst isTest = (p: string) => /\\.(test|spec)\\.[cm]?[jt]sx?$/.test(p);\nconst isCss = (p: string) => /\\.(css|scss|less)$/.test(p);\nconst isScript = (p: string) => /\\.[cm]?[jt]sx?$/.test(p);\n\n/** Resolves a relative specifier from a file to the component folder it lands in, if any. */\nfunction componentOf(from: string, spec: string, componentsDir: string): string | null {\n if (!spec.startsWith('.')) return null;\n const parts = from.split('/').slice(0, -1);\n for (const seg of spec.split('/')) {\n if (seg === '.' || seg === '') continue;\n if (seg === '..') parts.pop();\n else parts.push(seg);\n }\n const abs = parts.join('/');\n if (!abs.startsWith(`${componentsDir}/`)) return null;\n return abs.slice(componentsDir.length + 1).split('/')[0] || null;\n}\n\n/** The component folder a repo path belongs to, or null when it is outside `componentsDir`. */\nexport function componentForPath(path: string, componentsDir: string): string | null {\n const dir = norm(componentsDir);\n const p = norm(path);\n if (!p.startsWith(`${dir}/`)) return null;\n const rest = p.slice(dir.length + 1).split('/');\n return rest.length >= 2 ? rest[0]! : null;\n}\n\n/**\n * Builds the index from the files of a component library. `componentsDir` holds one folder per component\n * (`<dir>/<Name>/...`); every other file is \"global\" (styles, theme, story helpers) and only its CSS\n * variables are recorded.\n */\nexport function buildUsageIndex(files: UsageFile[], componentsDir: string): UsageIndex {\n const dir = norm(componentsDir);\n const modules: Record<string, UsageModule> = {};\n const vars = new Map<string, Set<string>>();\n const imports = new Map<string, Set<string>>();\n const storyImports = new Map<string, Set<string>>();\n const globalVars: Record<string, string[]> = {};\n const get = (m: Map<string, Set<string>>, k: string) => m.get(k) ?? m.set(k, new Set()).get(k)!;\n\n for (const f of files) {\n const path = norm(f.path);\n const id = componentForPath(path, dir);\n if (!id) {\n if (isCss(path)) {\n const v = cssVarsIn(f.text);\n if (v.length) globalVars[path] = v.sort();\n }\n continue;\n }\n const mod = (modules[id] ??= { id, dir: `${dir}/${id}`, files: [], vars: [], imports: [], storyImports: [] });\n mod.files.push(path);\n if (isTest(path)) continue;\n // Inline styles in TSX can read variables too (style={{ color: 'var(--x)' }}).\n for (const v of cssVarsIn(f.text)) get(vars, id).add(v);\n if (!isScript(path)) continue;\n for (const spec of importsIn(f.text)) {\n const dep = componentOf(path, spec, dir);\n if (!dep || dep === id) continue;\n get(isStory(path) ? storyImports : imports, id).add(dep);\n }\n }\n\n const byVar: Record<string, string[]> = {};\n for (const mod of Object.values(modules)) {\n mod.files.sort();\n mod.vars = [...(vars.get(mod.id) ?? [])].sort();\n mod.imports = [...(imports.get(mod.id) ?? [])].sort();\n mod.storyImports = [...(storyImports.get(mod.id) ?? [])].filter((d) => !mod.imports.includes(d)).sort();\n for (const v of mod.vars) (byVar[v] ??= []).push(mod.id);\n }\n for (const k of Object.keys(byVar)) byVar[k]!.sort();\n return { componentsDir: dir, modules, byVar, globalVars };\n}\n\nexport interface ImpactedModule {\n id: string;\n /** Why: \"uses --color-feedback-danger-solid\", \"file changed: ...\", \"renders Button\". */\n reasons: string[];\n /** True when reached only through another component it renders. */\n indirect: boolean;\n}\n\nexport interface ModuleImpact {\n modules: ImpactedModule[];\n /** Global stylesheets that read a changed variable. */\n globalHits: { file: string; vars: string[] }[];\n}\n\n/**\n * Components affected by changed CSS variables and changed files, closed over \"renders\": when Button changes,\n * every component that imports Button changes too.\n */\nexport function impactedModules(index: UsageIndex, input: { vars?: string[]; files?: string[] }): ModuleImpact {\n const reasons = new Map<string, { reasons: string[]; indirect: boolean }>();\n const add = (id: string, reason: string, indirect: boolean) => {\n const r = reasons.get(id);\n if (r) {\n if (!r.reasons.includes(reason)) r.reasons.push(reason);\n r.indirect &&= indirect;\n } else reasons.set(id, { reasons: [reason], indirect });\n };\n const changedVars = new Set(input.vars ?? []);\n for (const v of changedVars) for (const id of index.byVar[v] ?? []) add(id, `uses ${v}`, false);\n for (const f of input.files ?? []) {\n const id = componentForPath(f, index.componentsDir);\n if (id && index.modules[id]) add(id, `file changed: ${norm(f)}`, false);\n }\n // Reverse \"renders\" edges, breadth first so the closest reason is listed first.\n const renderedBy = new Map<string, string[]>();\n for (const m of Object.values(index.modules)) for (const d of m.imports) (renderedBy.get(d) ?? renderedBy.set(d, []).get(d)!).push(m.id);\n const queue = [...reasons.keys()];\n while (queue.length) {\n const id = queue.shift()!;\n for (const parent of renderedBy.get(id) ?? []) {\n const known = reasons.has(parent);\n add(parent, `renders ${id}`, true);\n if (!known) queue.push(parent);\n }\n }\n const globalHits = Object.entries(index.globalVars)\n .map(([file, vs]) => ({ file, vars: vs.filter((v) => changedVars.has(v)) }))\n .filter((g) => g.vars.length > 0);\n const modules = [...reasons.entries()].map(([id, r]) => ({ id, reasons: r.reasons, indirect: r.indirect })).sort((a, b) => Number(a.indirect) - Number(b.indirect) || a.id.localeCompare(b.id));\n return { modules, globalHits };\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Token usage: which tokens are in use. One definition for every surface (Overview, Checks, the token explorer).\n\nexport interface UsageToken {\n path: string;\n /** CSS custom property the token builds to, e.g. \"--color-bg-default\". */\n cssVar: string;\n /** Token paths this token resolves through, in any mode (its alias chains). May include the token itself. */\n refs: readonly string[];\n}\n\nexport interface TokenReads {\n /** CSS custom property -> components that read it (UsageIndex.byVar). */\n byVar?: Record<string, readonly string[]>;\n /** Global stylesheet -> CSS custom properties it reads (UsageIndex.globalVars): base styles, app shell, theme. */\n globalVars?: Record<string, readonly string[]>;\n}\n\nexport interface TokenUsage {\n /** Paths of every token in use. */\n used: Set<string>;\n /** Paths read directly with var(), by a component or a global stylesheet. */\n direct: Set<string>;\n}\n\n/**\n * A token is in use when a component stylesheet or a global stylesheet (base styles, the app shell) reads its\n * variable, or when a token in use aliases it, at any depth and in any mode. Everything else is unused.\n */\nexport function tokenUsage(tokens: readonly UsageToken[], reads: TokenReads): TokenUsage {\n const readVars = new Set<string>();\n for (const [v, mods] of Object.entries(reads.byVar ?? {})) if (mods.length) readVars.add(v);\n for (const vars of Object.values(reads.globalVars ?? {})) for (const v of vars) readVars.add(v);\n const byPath = new Map(tokens.map((t) => [t.path, t]));\n const direct = new Set(tokens.filter((t) => readVars.has(t.cssVar)).map((t) => t.path));\n const used = new Set<string>();\n const queue = [...direct];\n while (queue.length) {\n const p = queue.pop()!;\n if (used.has(p)) continue;\n used.add(p);\n for (const r of byPath.get(p)?.refs ?? []) if (!used.has(r) && byPath.has(r)) queue.push(r);\n }\n return { used, direct };\n}\n","// History from GitHub over REST, in the browser or Node: commits that touched the tokens root on a ref,\n// the pull request each one belongs to, token files at each side of the change (blobs cached by sha, so\n// files that did not change are read once), changesets the change added, tags and the CHANGELOG.\n\nimport type { BridgeConfig } from './config';\nimport type { GitHubClient, TreeEntry } from './github-client';\nimport { type HistoryBackend, type HistoryCommit, type HistoryReport, buildReport, collectHistory, mergeReleases, packageDirCandidates, parseChangelog, releasesFromTags } from './history';\nimport { selectTokenFiles } from './layered';\n\nexport function gitHubHistoryBackend(client: GitHubClient, config: BridgeConfig, opts: { concurrency?: number } = {}): HistoryBackend & { tree(sha: string): Promise<TreeEntry[]> } {\n const trees = new Map<string, Promise<TreeEntry[]>>();\n const tree = (sha: string) => {\n let t = trees.get(sha);\n if (!t) {\n t = client.getCommitTree(sha).then((ts) => client.getTree(ts, true)).then((r) => r.entries);\n trees.set(sha, t);\n }\n return t;\n };\n const root = config.tokens.root.replace(/\\/$/, '');\n const prefix = root === '.' || !root ? '' : `${root}/`;\n const limit = Math.max(1, opts.concurrency ?? 4);\n const pool = async <T, R>(items: T[], fn: (x: T) => Promise<R>): Promise<R[]> => {\n const out: R[] = new Array(items.length);\n let i = 0;\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {\n for (let k = i++; k < items.length; k = i++) out[k] = await fn(items[k]!);\n }));\n return out;\n };\n\n return {\n tree,\n async listCommits({ ref, paths, limit: max }) {\n const commits: HistoryCommit[] = [];\n for (let page = 1; commits.length < max && page <= 10; page++) {\n const batch = await client.listCommits({ sha: ref, path: paths[0], perPage: Math.min(100, max), page });\n for (const c of batch) {\n const [subject, ...rest] = c.message.split('\\n');\n commits.push({ sha: c.sha, parents: c.parents, date: c.date, author: c.author, subject: subject ?? '', body: rest.join('\\n').trim() });\n }\n if (batch.length < Math.min(100, max)) break;\n }\n const list = commits.slice(0, max);\n // The pull request of each commit. A branch commit of a merged PR is replaced by the PR's merge commit,\n // so the entry diffs the whole PR as it landed.\n const merges = new Map<string, Promise<HistoryCommit | undefined>>();\n const enriched = await pool(list, async (c) => {\n const prs = await client.listPullRequestsForCommit(c.sha).catch(() => []);\n const pr = prs.find((p) => p.mergedAt && p.baseRef === ref) ?? prs.find((p) => p.mergedAt);\n if (!pr) return c;\n const prInfo = { number: pr.number, title: pr.title, url: pr.url, author: pr.author, ...(pr.mergedAt ? { mergedAt: pr.mergedAt } : {}), body: pr.body };\n if (pr.mergeCommitSha && pr.mergeCommitSha !== c.sha) {\n let m = merges.get(pr.mergeCommitSha);\n if (!m) {\n m = client.getCommitInfo(pr.mergeCommitSha).then(\n (info) => {\n const [subject, ...rest] = info.message.split('\\n');\n return { sha: info.sha, parents: info.parents, date: pr.mergedAt ?? info.date, author: info.author, subject: subject ?? '', body: rest.join('\\n').trim() };\n },\n () => undefined,\n );\n merges.set(pr.mergeCommitSha, m);\n }\n const merge = await m;\n if (merge) return { ...merge, pr: prInfo };\n }\n return { ...c, ...(pr.mergedAt ? { date: pr.mergedAt } : {}), pr: prInfo };\n });\n return enriched;\n },\n async tokenFiles(sha) {\n const entries = await tree(sha);\n const blobs = entries.filter((e) => e.type === 'blob' && e.path.startsWith(prefix));\n const picked = new Set(selectTokenFiles(config, blobs.map((e) => e.path)));\n const wanted = blobs.filter((e) => picked.has(prefix ? e.path.slice(prefix.length) : e.path));\n const texts = await pool(wanted, async (e) => [prefix ? e.path.slice(prefix.length) : e.path, await client.getBlobText(e.sha)] as const);\n return new Map(texts);\n },\n async changesetPaths(sha) {\n const dir = config.changesets?.dir.replace(/\\/$/, '');\n if (!dir) return [];\n return (await tree(sha)).filter((e) => e.type === 'blob' && e.path.startsWith(`${dir}/`)).map((e) => e.path);\n },\n async readFile(sha, path) {\n const e = (await tree(sha)).find((x) => x.type === 'blob' && x.path === path);\n return e ? client.getBlobText(e.sha) : null;\n },\n };\n}\n\n/** The whole history report for a GitHub repo: entries, releases (tags and CHANGELOG), timeline. */\nexport async function loadGitHubHistory(client: GitHubClient, config: BridgeConfig, opts: { ref?: string; limit?: number; onProgress?: (done: number, total: number) => void } = {}): Promise<HistoryReport> {\n const ref = opts.ref ?? config.repo?.defaultBranch ?? (await client.getDefaultBranch());\n const limit = opts.limit ?? 30;\n const backend = gitHubHistoryBackend(client, config);\n let listed = 0;\n const counted: HistoryBackend = { ...backend, listCommits: async (o) => {\n const r = await backend.listCommits(o);\n listed = r.length;\n return r;\n } };\n const entries = await collectHistory(config, counted, { ref, limit, ...(opts.onProgress ? { onProgress: opts.onProgress } : {}) });\n const head = await client.getBranchSha(ref).catch(() => undefined);\n let changelog: ReturnType<typeof parseChangelog> = [];\n let currentVersion: string | undefined;\n if (head) {\n const files = await backend.tree(head).catch(() => [] as TreeEntry[]);\n for (const dir of packageDirCandidates(config)) {\n const p = (f: string) => (dir ? `${dir}/${f}` : f);\n const cl = files.find((e) => e.path === p('CHANGELOG.md'));\n const pkg = files.find((e) => e.path === p('package.json'));\n if (!cl && !pkg) continue;\n if (cl) changelog = parseChangelog(await client.getBlobText(cl.sha));\n if (pkg) {\n try {\n const json = JSON.parse(await client.getBlobText(pkg.sha)) as { name?: string; version?: string };\n if (!config.changesets || json.name === config.changesets.package) currentVersion = json.version;\n } catch {\n /* not JSON: no version */\n }\n }\n break;\n }\n }\n const tagList = await client.listTags(30).catch(() => []);\n const tagReleases = releasesFromTags(tagList, config.changesets?.package);\n // Tag dates cost one request each: only the ten newest.\n await Promise.all(\n tagReleases.slice(0, 10).map(async (r) => {\n if (!r.sha) return;\n const info = await client.getCommitInfo(r.sha).catch(() => undefined);\n if (info?.date) r.date = info.date;\n }),\n );\n const releases = mergeReleases(changelog, tagReleases);\n return buildReport({ source: 'github', label: `${client.fullName}@${ref}`, ref, entries, releases, ...(currentVersion ? { currentVersion } : {}), truncated: listed >= limit });\n}\n","// Demo history: fixture entries built backwards from the CURRENT token files, so a revert or a restore\n// planned on them runs against the real base branch. For showing the History UI on a repo with little\n// history. Every entry is flagged `demo`, has no PR link, and the report says `demo: true`: surfaces show\n// it only behind an explicit, labelled toggle and never as real history.\n\nimport type { BridgeConfig } from './config';\nimport { type HistoryEntry, type HistoryReport, buildHistoryEntry, buildReport } from './history';\nimport { LayeredTokenSet } from './layered';\nimport { type TokenEdit, applyTokenEdits } from './token-edits';\n\ninterface DemoStep {\n pr: number;\n title: string;\n why: string;\n author: string;\n date: string;\n /** The values BEFORE this step; the values after it are whatever the next state holds. */\n before: TokenEdit[];\n}\n\nconst STEPS: DemoStep[] = [\n { pr: 101, title: 'Darken muted text for small sizes', why: 'Muted captions at 12px read too light on subtle surfaces in usability tests.', author: 'demo-designer', date: '2026-07-08T09:30:00Z', before: [{ op: 'set', path: 'color.text.muted', file: 'semantic/light.tokens.json', value: '{palette.neutral.500}' }] },\n { pr: 102, title: 'Rounder buttons', why: 'Buttons move to the control radius so they match inputs and selects.', author: 'demo-engineer', date: '2026-07-21T14:10:00Z', before: [{ op: 'set', path: 'button.radius', file: 'components/button.tokens.json', value: '{radius.inset}' }] },\n { pr: 104, title: 'Clarify the alert radius description', why: 'The description now says why alerts use the container radius.', author: 'demo-engineer', date: '2026-08-19T08:00:00Z', before: [{ op: 'set', path: 'alert.radius', file: 'components/feedback.tokens.json', description: 'Alert corner radius.' }] },\n { pr: 106, title: 'Muted text one step lighter', why: 'Muted text competed with body text in dense tables; one step lighter still passes 4.5:1.', author: 'demo-designer', date: '2026-09-30T16:45:00Z', before: [{ op: 'set', path: 'color.text.muted', file: 'semantic/light.tokens.json', value: '{palette.neutral.700}' }] },\n];\n\nexport const DEMO_RELEASES = [\n { version: '1.1.0', date: '2026-07-25T12:00:00Z' },\n { version: '1.2.0', date: '2026-08-25T12:00:00Z' },\n];\n\n/** Demo history over the current files. Steps whose tokens this repo does not have are left out. */\nexport function demoHistory(config: BridgeConfig, current: Map<string, string>): HistoryReport {\n const states: Map<string, string>[] = [current];\n const kept: DemoStep[] = [];\n for (const step of [...STEPS].reverse()) {\n try {\n const prev = applyTokenEdits(new LayeredTokenSet(config, states[0]!), step.before).files;\n states.unshift(prev);\n kept.unshift(step);\n } catch {\n /* this repo has no such token: skip the step */\n }\n }\n const entries: HistoryEntry[] = [];\n kept.forEach((step, i) => {\n const e = buildHistoryEntry({\n config,\n commit: { sha: `demo${String(step.pr).padStart(36, '0')}`, parents: [`demo${String(step.pr - 1).padStart(36, '0')}`], date: step.date, author: step.author, subject: step.title, body: step.why, pr: { number: step.pr, title: step.title, author: step.author, mergedAt: step.date, body: step.why } },\n before: states[i]!,\n after: states[i + 1]!,\n demo: true,\n });\n if (e) entries.push(e);\n });\n return { ...buildReport({ source: 'demo', label: 'Demo history (fixture data)', ref: 'demo', entries, releases: DEMO_RELEASES, truncated: false }), demo: true };\n}\n","// Real branch preview URLs read from GitHub: the deployments and commit statuses of the head commit and the Vercel\n// bot comment on the pull request, resolved by `resolveBranchPreviews` (previews.ts). Shared by the plugin, Studio,\n// the MCP server and the CLI, so none of them shows a guessed URL. See docs/PREVIEWS.md.\n\nimport type { BridgeConfig } from './config';\nimport type { GitHubClient } from './github-client';\nimport { resolveBranchPreviews, type BranchPreview, type PreviewApps } from './previews';\n\nexport interface BranchPreviewOptions {\n /** Branch and head commit when the caller knows them (skips reading the pull request). */\n branch?: string | undefined;\n sha?: string | undefined;\n /** The pull request's comments when the caller already read them (skips one read). */\n comments?: { body?: string | null | undefined }[] | undefined;\n}\n\n/**\n * The preview of each app configured in `previews.apps` for a pull request (by number) or a commit (by sha): the URL\n * Vercel reports (deployments, then commit statuses, then its PR comment), the template only when Vercel cannot have\n * shortened it, and whether the build of that commit is ready. A failed read leaves that source out, never throws for it.\n */\nexport async function branchPreviewUrls(gh: GitHubClient, ref: number | string, config: Pick<BridgeConfig, 'previews'> | { previews?: { apps?: PreviewApps | undefined } | undefined } | undefined, opts: BranchPreviewOptions = {}): Promise<BranchPreview[]> {\n const apps: PreviewApps = config?.previews?.apps ?? {};\n if (!Object.values(apps).some(Boolean)) return [];\n let pr: number | undefined;\n let branch = opts.branch;\n let sha = opts.sha;\n if (typeof ref === 'number') {\n pr = ref;\n if (!branch || !sha) {\n const p = await gh.getPullRequest(ref);\n branch ??= p.headRef;\n sha ??= p.headSha;\n }\n } else {\n sha = ref;\n if (!branch || !opts.comments) {\n const open = (await gh.listPullRequestsForCommit(ref).catch(() => [])).find((p) => p.state === 'open');\n if (open) {\n pr = open.number;\n branch ??= open.headRef;\n }\n }\n }\n const [comments, statuses, deployments] = await Promise.all([\n opts.comments ? Promise.resolve(opts.comments) : pr !== undefined ? gh.listIssueComments(pr).catch(() => []) : Promise.resolve([]),\n sha ? gh.listCommitStatuses(sha).catch(() => []) : Promise.resolve([]),\n sha ? gh.listDeployments(sha).catch(() => []) : Promise.resolve([]),\n ]);\n return resolveBranchPreviews(apps, { branch: branch ?? '', ...(pr !== undefined ? { pr } : {}), ...(sha ? { sha } : {}) }, { comments, statuses, deployments });\n}\n","// The Bridge ramp engine: OKLCH color ramps on one shared lightness ladder (docs/DESIGN-LANGUAGE.md, section 4).\n// Pure and dependency-free, written as plain JavaScript so two very different callers run the same code:\n// packages/tokens/scripts/ramps.mjs regenerates src/primitives/color.tokens.json (plain Node, no build)\n// @bridge-ds/core planNewBrand generates the palette of a new brand (plugin, docs site, CLI, MCP)\n// Types live next to it in ramps.d.ts. Change the algorithm here and both stay in step.\n\n/** Ramp steps, lightest first. */\nexport const STEPS = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];\n\n/** OKLCH lightness of every step: the same step has the same perceived lightness whatever the hue. */\nexport const LIGHTNESS = { 50: 0.975, 100: 0.952, 200: 0.912, 300: 0.85, 400: 0.735, 500: 0.63, 600: 0.53, 700: 0.445, 800: 0.36, 900: 0.27, 950: 0.205 };\n\n/** Chroma bell: share of the peak chroma per step, peaking around 500 and 600. */\nexport const BELL = { 50: 0.12, 100: 0.22, 200: 0.4, 300: 0.62, 400: 0.85, 500: 1, 600: 1, 700: 0.92, 800: 0.8, 900: 0.62, 950: 0.5 };\n\n/** Bridge's ink anchors (Line, Ink secondary, Ink): pinned in the bridge neutral by scripts/ramps.mjs. */\nexport const NEUTRAL_ANCHORS = { 200: '#E3E8EE', 600: '#5B6672', 900: '#15202B' };\n\n/** How far a pinned brand hex may sit from its ladder step before the ramp stops reading as one family. */\nexport const PIN_TOLERANCE = 0.04;\n\n/** Chroma curve of a colored ramp (primary, status, accents). */\nexport const bellChroma = (peak) => (s) => peak * BELL[s];\n\n/** Chroma curve of a neutral ramp (ink, slate): nearly grey at the light end, a visible hue at the dark end. */\nexport const neutralChroma =\n (scale = 1, low = 0.004, base = 0.01, slope = 0.022) =>\n (s) =>\n (s <= 100 ? low : base + slope * (s / 950)) * scale;\n\nexport function oklchToLinear(L, C, h) {\n const hr = (h * Math.PI) / 180;\n const a = C * Math.cos(hr);\n const b = C * Math.sin(hr);\n const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;\n const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;\n const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;\n return [\n 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,\n -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,\n -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,\n ];\n}\n\nconst encode = (x) => {\n const c = Math.min(1, Math.max(0, x));\n return c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055;\n};\nconst decode = (x) => (x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4);\n\n/** sRGB (0..1 components) of an OKLCH color, gamut-mapped by lowering chroma until it fits. */\nexport function oklch(L, C, h) {\n let c = C;\n let lin = oklchToLinear(L, c, h);\n for (let i = 0; i < 60 && !lin.every((x) => x >= -0.0005 && x <= 1.0005); i++) {\n c *= 0.95;\n lin = oklchToLinear(L, c, h);\n }\n return lin.map(encode);\n}\n\n/** OKLCH of an sRGB color (0..1 components). Hue is 0 for greys. */\nexport function toOklch(rgb) {\n const [r, g, b] = rgb.map(decode);\n const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);\n const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);\n const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);\n const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s;\n const A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;\n const B = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;\n const C = Math.sqrt(A * A + B * B);\n const h = C < 1e-6 ? 0 : ((Math.atan2(B, A) * 180) / Math.PI + 360) % 360;\n return { L, C, h };\n}\n\nexport const isHex = (s) => typeof s === 'string' && /^#[0-9a-f]{6}$/i.test(s.trim());\nexport const fromHex = (hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255);\nexport const round3 = (x) => Math.round(x * 1000) / 1000;\nexport const toHex = (rgb) => '#' + rgb.map((x) => Math.round(x * 255).toString(16).padStart(2, '0')).join('');\n\n/** DTCG 2025.10 color value in the house form: { colorSpace, components, hex, alpha? }. */\nexport function dtcgColor(rgb, alpha) {\n const v = { colorSpace: 'srgb', components: rgb.map(round3), hex: toHex(rgb) };\n if (alpha !== undefined) v.alpha = alpha;\n return v;\n}\n\n/**\n * One ramp: step -> sRGB. `chroma(step)` and `offset(step)` shape it; `pins` replace steps with exact brand hexes,\n * so named brand colors survive regeneration.\n */\nexport function generateRamp({ hue, chroma, offset = () => 0, pins = {} }) {\n const out = {};\n for (const s of STEPS) {\n const pin = pins[s];\n out[s] = pin ? fromHex(pin) : oklch(LIGHTNESS[s] + offset(s), chroma(s), hue);\n }\n return out;\n}\n\n/** Ladder step whose lightness is closest to an sRGB color. */\nexport function nearestStep(rgb) {\n const { L } = toOklch(rgb);\n let best = STEPS[0];\n for (const s of STEPS) if (Math.abs(LIGHTNESS[s] - L) < Math.abs(LIGHTNESS[best] - L)) best = s;\n return best;\n}\n\n/**\n * A colored ramp anchored on a brand hex: hue from the hex, peak chroma so the curve passes through it, and the\n * hex pinned at `pinStep` (or at its nearest step). `distance` is how far the hex sits from the ladder lightness\n * of the pinned step; above PIN_TOLERANCE the ramp is no longer monotonic around the pin.\n */\nexport function anchoredRamp(hex, pinStep) {\n const rgb = fromHex(hex);\n const { L, C, h } = toOklch(rgb);\n const step = pinStep ?? nearestStep(rgb);\n const peak = Math.min(0.24, Math.max(0.02, C / BELL[step]));\n return { hue: h, peak, step, distance: Math.abs(L - LIGHTNESS[step]), ramp: generateRamp({ hue: h, chroma: bellChroma(peak), pins: { [step]: hex.toUpperCase() } }) };\n}\n\n/**\n * Lightness offsets of a generated neutral: the steps text and lines use sit exactly where Bridge's ink anchors\n * sit, so muted text (600) keeps its contrast on zones and subtle backgrounds in every new brand.\n */\nexport function neutralOffset() {\n const off = {};\n for (const [s, hex] of Object.entries(NEUTRAL_ANCHORS)) off[s] = toOklch(fromHex(hex)).L - LIGHTNESS[s];\n return (s) => off[s] ?? 0;\n}\n\n/** A neutral ramp tinted by a hex: hue from the hex, chroma scaled by how tinted it is (0 for a pure grey). */\nexport function tintedNeutral(hex) {\n const rgb = fromHex(hex);\n const { C, h } = toOklch(rgb);\n const ref = neutralChroma()(nearestStep(rgb));\n const scale = C < 0.004 ? 0 : Math.min(2.5, C / ref);\n return { hue: h, scale, ramp: generateRamp({ hue: h, chroma: neutralChroma(scale), offset: neutralOffset() }) };\n}\n","// New brands: one planner shared by the CLI (`bridge brand create`), the MCP server (bridge_plan_brand,\n// bridge_propose_brand), the Figma plugin (a new mode in the Brand collection) and the docs site Studio.\n//\n// A brand only re-points palette roles, radius roles, font roles and typography families (docs/DESIGN-LANGUAGE.md,\n// \"Second brand\"). planNewBrand copies a starting brand (or the default brand's structure for \"blank\"), fills\n// the primary, accent, link and neutral palette roles with ramps from the shared ramp engine (ramps.js, the\n// code packages/tokens/scripts/ramps.mjs runs), copies the starting brand's theme overrides when it has any,\n// adds the slug to modes.brand in bridge.config.json and runs the contrast gate for the new brand in every theme.\n// Nothing is written: the result lists files, contrast, validation, risk tier and a PR body; each surface decides\n// where the files go (a local branch, a remote pull request), never to the default branch.\n\nimport { CONFIG_FILE, type BridgeConfig, loadConfig, tokensPath, toConfigJson } from './config';\nimport { formatChangeset } from './changeset';\nimport { type Combo, type LayerIssue, LayeredTokenSet, validateLayered } from './layered';\nimport { type LayeredContrastResult, checkLayeredPair } from './layered-review';\nimport { RISK_LABELS, type RiskResult, classifyRisk } from './risk';\nimport { type Step, LIGHTNESS, PIN_TOLERANCE, STEPS, anchoredRamp, bellChroma, dtcgColor, fromHex, generateRamp, isHex, neutralChroma, neutralOffset, tintedNeutral, toOklch } from './ramps';\nimport { coerceValue } from './token-edits';\nimport { type ContrastPair, parseContrastChecks } from './wcag';\n\n// --- inputs -----------------------------------------------------------------------------------------------\n\n/** A ramp anchor: a \"#rrggbb\" brand color (pinned in the ramp) or an OKLCH hue in degrees (0..360). */\nexport type HueInput = string | number;\n\nexport interface BrandRadiusInput {\n /** px, on the radius scale (0, 2, 4, 6, 10, 12, 16, 20). */\n inset?: number;\n control?: number;\n container?: number;\n overlay?: number;\n}\n\nexport interface BrandFontsInput {\n /** Display and headings (typography display, h1, h2). A curated font id, see BRAND_FONTS. */\n heading?: string;\n /** Body, UI and captions (typography h3, body, ui, caption). */\n text?: string;\n}\n\nexport interface NewBrandInput {\n /** Lowercase letters, digits and single dashes, 2 to 24 characters: \"acme\", \"north-star\". */\n slug: string;\n /** Display name. Default: the slug in title case. */\n name?: string;\n /** Existing brand to start from, or \"blank\" (the default brand's structure, neutral type and no overrides). */\n from: string;\n /** Primary ramp (also accent and link unless set in `colors`). A hex is pinned at the step primary actions use. */\n primaryHue?: HueInput;\n /** Neutral ramp: text, lines, canvases. A hex tints it with its hue; a pure grey gives a pure grey ramp. */\n neutralHue?: HueInput;\n /** \"More colors\": separate ramps for accent (signal, focus ring) and link. */\n colors?: { accent?: HueInput; link?: HueInput };\n radius?: BrandRadiusInput;\n fonts?: BrandFontsInput;\n /** Exact values for brand tokens, by path (palette.primary.600, radius.control...): hex, \"12px\", \"{alias}\" or DTCG. */\n overrides?: Record<string, unknown>;\n}\n\n/** What the planner reads: the repo's config, its token files (relative to tokens.root) and contrast pairs. */\nexport interface BrandSource {\n config: BridgeConfig;\n /** bridge.config.json as written; edited with a minimal diff. Without it the canonical form is written. */\n configText?: string | undefined;\n files: Map<string, string> | Record<string, string>;\n /** contrast.checks.json text. */\n contrastText?: string | undefined;\n}\n\n// --- curated choices --------------------------------------------------------------------------------------\n\nexport interface BrandFont {\n id: string;\n label: string;\n /** Primitive token the role aliases. */\n token: string;\n /** Where it reads well: headings only (a display serif) or both. */\n use: 'heading' | 'both';\n}\n\n/** The short list the Studio offers. Every font here is self-hosted by @bridge-ds/tokens/fonts.css. */\nexport const BRAND_FONTS: BrandFont[] = [\n { id: 'fraunces', label: 'Fraunces', token: 'font.family.fraunces', use: 'heading' },\n { id: 'instrument-sans', label: 'Instrument Sans', token: 'font.family.instrument-sans', use: 'both' },\n { id: 'plex-sans', label: 'IBM Plex Sans', token: 'font.family.plex-sans', use: 'both' },\n { id: 'system', label: 'System UI', token: 'font.family.system', use: 'both' },\n];\n\nexport interface RadiusPreset {\n id: string;\n label: string;\n hint: string;\n radius: Required<BrandRadiusInput>;\n}\n\nexport const RADIUS_PRESETS: RadiusPreset[] = [\n { id: 'soft', label: 'Soft', hint: 'Rounded, like Bridge', radius: { inset: 6, control: 12, container: 20, overlay: 20 } },\n { id: 'balanced', label: 'Balanced', hint: 'Tighter, like Ocean', radius: { inset: 4, control: 10, container: 16, overlay: 20 } },\n { id: 'crisp', label: 'Crisp', hint: 'Near square corners', radius: { inset: 2, control: 4, container: 6, overlay: 10 } },\n];\n\nconst HEADING_ROLES = ['display', 'h1', 'h2'];\nconst TEXT_ROLES = ['h3', 'body', 'ui', 'caption'];\nconst RADIUS_ROLES = ['inset', 'control', 'container', 'overlay'] as const;\nconst RESERVED = new Set(['default', 'base', 'all', 'none', 'new', 'blank', 'primitives', 'semantic', 'components', 'density']);\nexport const BRAND_SLUG_RE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\nconst DEFAULT_PRIMARY_CHROMA = 0.14;\n\n// --- outputs ----------------------------------------------------------------------------------------------\n\nexport interface PlannedFile {\n /** Repo-relative path. */\n path: string;\n action: 'create' | 'modify';\n content: string;\n}\n\nexport interface BrandIssue {\n level: 'error' | 'warning';\n code: string;\n message: string;\n path?: string;\n file?: string;\n}\n\nexport interface BrandSwatch {\n step: number;\n hex: string;\n}\n\nexport interface BrandContrastSummary {\n /** Pairs checked for the new brand, every theme. */\n checks: number;\n passing: number;\n failing: LayeredContrastResult[];\n /** Every result for the new brand, for tables. */\n results: LayeredContrastResult[];\n themes: string[];\n}\n\nexport interface NewBrandPlan {\n ok: boolean;\n slug: string;\n name: string;\n from: string;\n title: string;\n /** Suggested branch name (governance.branchPrefix + brand-<slug>). */\n branch: string;\n files: PlannedFile[];\n /** Token files after the change, relative to tokens.root (feed it to brandPreviewVariables or a LayeredTokenSet). */\n tokenFiles: Record<string, string>;\n /** bridge.config.json after the change, as text. */\n configText: string;\n /** Primary, neutral (and accent, link when they differ) ramps of the new brand, resolved. */\n ramps: Record<string, BrandSwatch[]>;\n /** Step of the primary ramp that primary actions use in the light theme (where a hex primary is pinned). */\n actionStep: number;\n contrast: BrandContrastSummary;\n /** Slug, input and DTCG problems. Errors block a proposal. */\n issues: BrandIssue[];\n risk: RiskResult & { bump: 'minor' };\n changeset?: { path: string; content: string } | undefined;\n}\n\n// --- helpers ----------------------------------------------------------------------------------------------\n\ntype Json = Record<string, unknown>;\nconst isObj = (x: unknown): x is Json => !!x && typeof x === 'object' && !Array.isArray(x);\nconst fileMap = (f: BrandSource['files']) => (f instanceof Map ? new Map(f) : new Map(Object.entries(f)));\nexport const brandDisplayName = (slug: string) => slug.split('-').filter(Boolean).map((w) => w[0]!.toUpperCase() + w.slice(1)).join(' ');\n\n/** The layer patterns brands use: the brand file and the optional brand x theme overrides. */\nfunction brandLayers(config: BridgeConfig): { brand?: string; override?: string; overrideAxis?: string } {\n const out: { brand?: string; override?: string; overrideAxis?: string } = {};\n for (const l of config.tokens.layers) {\n const ph = (l.files.match(/\\{([^}]+)\\}/g) ?? []).map((p) => p.slice(1, -1));\n if (!ph.includes('brand')) continue;\n if (ph.length === 1 && !out.brand) out.brand = l.files;\n else if (ph.length === 2 && !out.override) {\n out.override = l.files;\n out.overrideAxis = ph.find((p) => p !== 'brand');\n }\n }\n return out;\n}\nconst fill = (pattern: string, combo: Combo) => pattern.replace(/\\{([^}]+)\\}/g, (_, k: string) => combo[k] ?? `{${k}}`);\n\nfunction setAt(doc: Json, path: string, node: Json) {\n const keys = path.split('.');\n let cur = doc;\n for (const k of keys.slice(0, -1)) {\n if (!isObj(cur[k])) cur[k] = {};\n cur = cur[k] as Json;\n }\n const last = keys[keys.length - 1]!;\n const prev = isObj(cur[last]) ? (cur[last] as Json) : {};\n cur[last] = { ...prev, ...node };\n}\nfunction getAt(doc: Json, path: string): Json | undefined {\n let cur: unknown = doc;\n for (const k of path.split('.')) cur = isObj(cur) ? cur[k] : undefined;\n return isObj(cur) ? cur : undefined;\n}\n/** $type of a token in a doc, inherited from its groups. */\nfunction typeAt(doc: Json, path: string): string | undefined {\n let cur: unknown = doc;\n let type: string | undefined;\n for (const k of path.split('.')) {\n if (!isObj(cur)) return type;\n if (typeof cur.$type === 'string') type = cur.$type;\n cur = cur[k];\n }\n return isObj(cur) && typeof cur.$type === 'string' ? cur.$type : type;\n}\n\n/** Ramp for a hue input: a hex is pinned (at `pinStep`), a number is generated with the default chroma. */\nfunction rampFor(input: HueInput, pinStep: Step | undefined, kind: 'color' | 'neutral'): { ramp: Record<number, number[]>; issue?: BrandIssue; anchor: string } {\n if (typeof input === 'number' || (typeof input === 'string' && /^\\d+(\\.\\d+)?$/.test(input.trim()))) {\n const hue = ((Number(input) % 360) + 360) % 360;\n const ramp = kind === 'neutral' ? generateRamp({ hue, chroma: neutralChroma(), offset: neutralOffset() }) : generateRamp({ hue, chroma: bellChroma(DEFAULT_PRIMARY_CHROMA) });\n return { ramp, anchor: `OKLCH hue ${Math.round(hue)}` };\n }\n const hex = String(input).trim();\n if (!isHex(hex)) throw new Error(`\"${hex}\" is not a color. Use #rrggbb or a hue in degrees (0 to 360).`);\n if (kind === 'neutral') {\n const n = tintedNeutral(hex);\n return { ramp: n.ramp, anchor: `${hex.toUpperCase()} (hue ${Math.round(n.hue)})` };\n }\n const a = anchoredRamp(hex, pinStep);\n const issue: BrandIssue | undefined =\n a.distance > PIN_TOLERANCE\n ? {\n level: 'warning',\n code: 'pin-off-ladder',\n message: `${hex.toUpperCase()} is ${a.distance > 0.12 ? 'much ' : ''}${toOklch(fromHex(hex)).L > LIGHTNESS[a.step] ? 'lighter' : 'darker'} than the ${a.step} step it is pinned to, so the ramp around it will not read as one family. Primary actions use this step: pick a ${a.step >= 600 ? 'deeper' : 'lighter'} color.`,\n }\n : undefined;\n return { ramp: a.ramp, anchor: `${hex.toUpperCase()} pinned at ${a.step}`, ...(issue ? { issue } : {}) };\n}\n\n/** Points a palette role at a primitive ramp: palette.<role>.<step> -> {color.<ramp>.<step>} (two tiers, never literals). */\nfunction aliasRamp(doc: Json, role: string, ramp: string, description: string) {\n const group = getAt(doc, `palette.${role}`);\n if (!group) return;\n for (const s of STEPS) {\n if (!(String(s) in group)) continue;\n setAt(doc, `palette.${role}.${s}`, { $value: `{color.${ramp}.${s}}` });\n }\n group.$description = description;\n}\n\n/** Primitive ramps a new brand adds: ramp name -> description and DTCG color per step. */\ntype PrimitiveRamps = Map<string, { description: string; steps: Map<number, unknown> }>;\n\n/** Inserts `slug` into modes.brand.values (or modes.brands) with a minimal text change. */\nexport function addBrandToConfigText(text: string, slug: string): string {\n const canonical = /(\"brand\"\\s*:\\s*\\{\\s*\"values\"\\s*:\\s*\\[)([^\\]]*)(\\])/;\n const flat = /(\"brands\"\\s*:\\s*\\[)([^\\]]*)(\\])/;\n for (const re of [canonical, flat]) {\n const m = re.exec(text);\n if (!m) continue;\n const items = m[2]!.trim();\n const sep = items.includes('\\n') ? `,${/\\n(\\s*)\"/.exec(m[2]!)?.[0]?.replace(/\"$/, '') ?? ' '}` : ', ';\n return text.slice(0, m.index) + m[1] + (items ? `${m[2]!.replace(/\\s*$/, '')}${sep}\"${slug}\"` : `\"${slug}\"`) + (m[2]!.match(/\\s*$/)?.[0] ?? '') + m[3] + text.slice(m.index + m[0].length);\n }\n throw new Error('bridge.config.json has no modes.brand.values list to add the brand to.');\n}\n\n// --- listing ----------------------------------------------------------------------------------------------\n\nexport interface BrandSummary {\n slug: string;\n name: string;\n default: boolean;\n file: string;\n description?: string;\n /** Resolved color.action.primary.bg in the default theme, when the repo has it. */\n primary?: string;\n /** Theme override files the brand has. */\n overrides: string[];\n}\n\nexport function listBrands(source: BrandSource): BrandSummary[] {\n const { config } = source;\n const files = fileMap(source.files);\n const set = new LayeredTokenSet(config, files);\n const layers = brandLayers(config);\n const brandAxis = config.axes.brand;\n if (!brandAxis || !layers.brand) return [];\n return brandAxis.values.map((slug) => {\n const file = fill(layers.brand!, { brand: slug });\n let doc: Json = {};\n try {\n doc = JSON.parse(files.get(file) ?? '{}') as Json;\n } catch {\n /* reported by validation */\n }\n const meta = isObj(doc.$extensions) && isObj(doc.$extensions['dev.bridge.brand']) ? (doc.$extensions['dev.bridge.brand'] as Json) : {};\n const combo = set.normalizeCombo({ brand: slug });\n const primary = set.resolve('color.action.primary.bg', combo);\n const overrides = layers.override ? (config.axes[layers.overrideAxis!]?.values ?? []).map((v) => fill(layers.override!, { brand: slug, [layers.overrideAxis!]: v })).filter((f) => files.has(f)) : [];\n return {\n slug,\n name: typeof meta.name === 'string' ? meta.name : brandDisplayName(slug),\n default: slug === brandAxis.default,\n file: tokensPath(config, file),\n ...(typeof doc.$description === 'string' ? { description: doc.$description } : {}),\n ...(primary.css && !primary.error ? { primary: primary.css } : {}),\n overrides: overrides.map((f) => tokensPath(config, f)),\n };\n });\n}\n\n// --- planning ---------------------------------------------------------------------------------------------\n\n/** Problems with a slug before anything is generated (the Studio uses it as you type). */\nexport function checkBrandSlug(config: BridgeConfig, files: BrandSource['files'], slug: string): BrandIssue[] {\n const out: BrandIssue[] = [];\n const s = slug.trim();\n if (!s) return [{ level: 'error', code: 'slug-empty', message: 'Give the brand a name.' }];\n if (s.length < 2 || s.length > 24 || !BRAND_SLUG_RE.test(s)) out.push({ level: 'error', code: 'slug-format', message: 'Use 2 to 24 lowercase letters, digits and single dashes, starting with a letter: \"acme\" or \"north-star\".' });\n const taken = Object.values(config.axes).flatMap((a) => a.values);\n if (config.axes.brand?.values.includes(s)) out.push({ level: 'error', code: 'slug-taken', message: `A brand called \"${s}\" already exists. Pick another name or edit that brand.` });\n else if (taken.includes(s) || RESERVED.has(s)) out.push({ level: 'error', code: 'slug-reserved', message: `\"${s}\" is a reserved mode name. Pick another name.` });\n const layer = brandLayers(config).brand;\n const map = fileMap(files);\n if (layer && !config.axes.brand?.values.includes(s) && map.has(fill(layer, { brand: s }))) out.push({ level: 'error', code: 'slug-file-exists', message: `${tokensPath(config, fill(layer, { brand: s }))} already exists. Pick another name or add it to bridge.config.json.` });\n return out;\n}\n\nexport function planNewBrand(source: BrandSource, input: NewBrandInput): NewBrandPlan {\n const { config } = source;\n const files = fileMap(source.files);\n const issues: BrandIssue[] = [];\n const slug = input.slug.trim();\n const name = input.name?.trim() || brandDisplayName(slug);\n const layers = brandLayers(config);\n const brandAxis = config.axes.brand;\n if (!brandAxis || !layers.brand) throw new Error('This repo has no brand mode: bridge.config.json needs modes.brand and a tokens layer with {brand}.');\n issues.push(...checkBrandSlug(config, files, slug));\n\n const from = input.from?.trim() || brandAxis.default;\n const blank = from === 'blank';\n if (!blank && !brandAxis.values.includes(from)) throw new Error(`Unknown brand \"${from}\" to start from. Brands: ${brandAxis.values.join(', ')} (or \"blank\").`);\n const template = blank ? brandAxis.default : from;\n const templateFile = fill(layers.brand, { brand: template });\n const templateText = files.get(templateFile);\n if (!templateText) throw new Error(`${tokensPath(config, templateFile)} is missing.`);\n const doc = JSON.parse(templateText) as Json;\n const before = new LayeredTokenSet(config, files);\n\n // Step that primary actions use in the light (default) theme of the starting brand: a hex primary is pinned there.\n const chain = before.resolve('color.action.primary.bg', before.normalizeCombo({ brand: template })).chain;\n const actionStep = Number(/^palette\\.primary\\.(\\d+)$/.exec(chain.find((c) => /^palette\\.primary\\.\\d+$/.test(c)) ?? '')?.[1] ?? 600) as Step;\n\n const anchors: Record<string, string> = {};\n const safeRamp = (role: string, hue: HueInput, kind: 'color' | 'neutral', pin?: Step) => {\n try {\n const r = rampFor(hue, pin, kind);\n if (r.issue) issues.push({ ...r.issue, path: `palette.${role}` });\n anchors[role] = r.anchor;\n return r.ramp;\n } catch (e) {\n issues.push({ level: 'error', code: 'invalid-color', message: (e as Error).message, path: `palette.${role}` });\n return undefined;\n }\n };\n // Generated ramps become primitives (color.<slug>-<role>.<step>); the brand file only aliases them.\n const prims: PrimitiveRamps = new Map();\n const addRamp = (role: string, ramp: Record<number, number[]>, description: string) => {\n const steps = new Map<number, unknown>(STEPS.map((st) => [st, dtcgColor(ramp[st]!)]));\n prims.set(`${slug}-${role}`, { description, steps });\n return `${slug}-${role}`;\n };\n if (input.primaryHue !== undefined && input.primaryHue !== '') {\n const ramp = safeRamp('primary', input.primaryHue, 'color', actionStep);\n if (ramp) {\n const r = addRamp('primary', ramp, `${name} primary. Generated by Bridge from ${anchors.primary}.`);\n aliasRamp(doc, 'primary', r, `${name} primary.`);\n if (input.colors?.accent === undefined) aliasRamp(doc, 'accent', r, `${name} accent: the primary ramp.`);\n if (input.colors?.link === undefined) aliasRamp(doc, 'link', r, `${name} links: the primary ramp.`);\n }\n }\n for (const role of ['accent', 'link'] as const) {\n const hue = input.colors?.[role];\n if (hue === undefined || hue === '') continue;\n const ramp = safeRamp(role, hue, 'color');\n if (ramp) aliasRamp(doc, role, addRamp(role, ramp, `${name} ${role}. Generated by Bridge from ${anchors[role]}.`), `${name} ${role}.`);\n }\n if (input.neutralHue !== undefined && input.neutralHue !== '') {\n const ramp = safeRamp('neutral', input.neutralHue, 'neutral');\n if (ramp) aliasRamp(doc, 'neutral', addRamp('neutral', ramp, `${name} neutral. Generated by Bridge from ${anchors.neutral}.`), `${name} neutral.`);\n }\n\n // Radius roles: aliases of the radius scale.\n const scale = new Map<number, string>();\n for (const [path, defs] of before.view(before.defaultCombo)) {\n const m = /^radius\\.([\\w-]+)$/.exec(path);\n const v = defs[defs.length - 1]!.value;\n if (m && isObj(v) && typeof v.value === 'number' && v.unit === 'px' && !getAt(doc, path)) scale.set(v.value, m[1]!);\n }\n const radius = input.radius ?? (blank ? RADIUS_PRESETS[0]!.radius : undefined);\n if (radius) {\n for (const role of RADIUS_ROLES) {\n const px = radius[role];\n if (px === undefined) continue;\n const step = scale.get(px);\n if (!step) issues.push({ level: 'error', code: 'radius-off-scale', message: `radius.${role} ${px}px is not on the radius scale (${[...scale.keys()].filter((x) => x < 9999).sort((a, b) => a - b).join(', ')} px).`, path: `radius.${role}` });\n else if (getAt(doc, `radius.${role}`)) setAt(doc, `radius.${role}`, { $value: `{radius.${step}}` });\n }\n }\n\n // Font roles and typography families.\n const fonts = input.fonts ?? (blank ? { heading: 'instrument-sans', text: 'instrument-sans' } : undefined);\n const fontToken = (id: string | undefined, role: string) => {\n if (!id) return undefined;\n const f = BRAND_FONTS.find((x) => x.id === id || x.token === id);\n const token = f?.token ?? (id.startsWith('font.family.') ? id : `font.family.${id}`);\n if (!before.view(before.defaultCombo).has(token) || ['font.family.sans', 'font.family.display', 'font.family.mono'].includes(token)) {\n issues.push({ level: 'error', code: 'unknown-font', message: `\"${id}\" is not a font this repo self-hosts. Pick one of: ${BRAND_FONTS.map((x) => x.label).join(', ')}.`, path: `font.family.${role}` });\n return undefined;\n }\n return token;\n };\n const heading = fontToken(fonts?.heading, 'display');\n const text = fontToken(fonts?.text, 'sans');\n if (heading && getAt(doc, 'font.family.display')) setAt(doc, 'font.family.display', { $value: `{${heading}}` });\n if (text && getAt(doc, 'font.family.sans')) setAt(doc, 'font.family.sans', { $value: `{${text}}` });\n for (const r of HEADING_ROLES) if (heading && getAt(doc, `typography.${r}.family`)) setAt(doc, `typography.${r}.family`, { $value: `{${heading}}` });\n for (const r of TEXT_ROLES) if (text && getAt(doc, `typography.${r}.family`)) setAt(doc, `typography.${r}.family`, { $value: `{${text}}` });\n\n // Exact values (the Figma plugin sends every variable of the new mode).\n for (const [path, raw] of Object.entries(input.overrides ?? {})) {\n const node = getAt(doc, path);\n if (!node || !('$value' in node)) {\n issues.push({ level: 'error', code: 'unknown-token', message: `${path} is not a token of the ${template} brand file, so a new brand cannot set it.`, path });\n continue;\n }\n setAt(doc, path, { $value: coerceValue(raw, typeAt(doc, path), node.$value) });\n }\n\n // Exact colors (Figma values, overrides) are hoisted too: a literal palette color becomes the primitive\n // color.<slug>-<role>.<step> and the role aliases it, so brand files never hold literal values.\n const palette = getAt(doc, 'palette');\n for (const [role, group] of Object.entries(palette ?? {})) {\n if (role.startsWith('$') || !isObj(group)) continue;\n for (const [step, node] of Object.entries(group)) {\n if (step.startsWith('$') || !isObj(node) || !('$value' in node) || typeof node.$value === 'string') continue;\n const ramp = `${slug}-${role}`;\n const entry = prims.get(ramp) ?? { description: `${name} ${role}. Exact values set when the brand was created.`, steps: new Map<number, unknown>() };\n entry.steps.set(Number(step), node.$value);\n prims.set(ramp, entry);\n setAt(doc, `palette.${role}.${step}`, { $value: `{color.${ramp}.${step}}` });\n }\n }\n const primDir = config.tokens.tiers.primitive?.[0]?.replace(/\\/$/, '') ?? config.tokens.primitives;\n const primFile = `${primDir}/${slug}.tokens.json`;\n if (prims.size && files.has(primFile)) issues.push({ level: 'error', code: 'slug-file-exists', message: `${tokensPath(config, primFile)} already exists. Pick another name.` });\n for (const r of prims.keys()) if (before.allPaths().some((p) => p.startsWith(`color.${r}.`))) issues.push({ level: 'error', code: 'ramp-exists', message: `A primitive ramp color.${r} already exists. Pick another name.` });\n\n doc.$description = `${name}: created with Bridge, started from ${blank ? 'a blank brand' : brandDisplayName(from)}.`;\n doc.$extensions = { ...(isObj(doc.$extensions) ? doc.$extensions : {}), 'dev.bridge.brand': { name, from, ...(Object.keys(anchors).length ? { anchors } : {}) } };\n // Keep $description and $extensions on top, like the hand-written brand files.\n const { $description, $extensions, ...rest } = doc;\n const brandFile = fill(layers.brand, { brand: slug });\n const nextFiles = new Map(files);\n const created: string[] = [];\n if (prims.size) {\n const color: Json = { $type: 'color' };\n for (const [r, { description, steps }] of prims) {\n const ramp: Json = { $description: description };\n for (const st of [...steps.keys()].sort((a, b) => a - b)) ramp[String(st)] = { $value: steps.get(st) };\n color[r] = ramp;\n }\n const prim = { $description: `${name} brand ramps, generated by Bridge (@bridge-ds/core ramp engine). Never used by components directly: brands/${slug}.tokens.json maps them to palette roles.`, color };\n nextFiles.set(primFile, `${JSON.stringify(prim, null, 2)}\\n`);\n created.push(primFile);\n }\n created.push(brandFile);\n nextFiles.set(brandFile, `${JSON.stringify({ $description, $extensions, ...rest }, null, 2)}\\n`);\n\n // Theme overrides of the starting brand come along: they point at palette roles, so they follow the new ramps.\n if (!blank && layers.override && layers.overrideAxis) {\n for (const v of config.axes[layers.overrideAxis]?.values ?? []) {\n const src = fill(layers.override, { brand: from, [layers.overrideAxis]: v });\n const text = files.get(src);\n if (!text) continue;\n const o = JSON.parse(text) as Json;\n const out = { ...o, $description: `${name} overrides on top of semantic/${v}, copied from ${brandDisplayName(from)}.` };\n const dst = fill(layers.override, { brand: slug, [layers.overrideAxis]: v });\n nextFiles.set(dst, `${JSON.stringify(out, null, 2)}\\n`);\n created.push(dst);\n }\n }\n\n // bridge.config.json: modes.brand += slug.\n const baseConfigText = source.configText ?? `${JSON.stringify(toConfigJson(config), null, 2)}\\n`;\n let configText = baseConfigText;\n let nextConfig = config;\n try {\n configText = addBrandToConfigText(baseConfigText, slug);\n nextConfig = issues.some((i) => i.code.startsWith('slug-')) ? config : loadConfig(configText);\n } catch (e) {\n issues.push({ level: 'error', code: 'config', message: (e as Error).message });\n }\n\n // Validation (only problems the new brand brings) and the contrast gate for the new brand in every theme.\n const after = new LayeredTokenSet(nextConfig, nextFiles);\n const key = (i: LayerIssue) => `${i.code}|${i.path ?? ''}|${i.message}`;\n const known = new Set(validateLayered(before).map(key));\n const brandKey = `brand=${slug}`;\n for (const i of validateLayered(after)) {\n if (known.has(key(i))) continue;\n if (i.modes && !i.modes.some((m) => m.split(',').includes(brandKey)) && !created.includes(i.file ?? '')) continue;\n issues.push({ level: i.level, code: i.code, message: i.message, ...(i.path ? { path: i.path } : {}), ...(i.file ? { file: tokensPath(config, i.file) } : {}) });\n }\n const pairs: ContrastPair[] = parseContrastChecks(source.contrastText);\n const inGate = nextConfig.axes.brand?.values.includes(slug);\n const combos = inGate ? after.combos(nextConfig.contrast?.modes).filter((c) => c.brand === slug) : [];\n const results = combos.flatMap((c) => pairs.map((p) => checkLayeredPair(after, p, c)));\n const failing = results.filter((r) => !r.pass);\n const themes = [...new Set(combos.map((c) => c.theme).filter((t): t is string => !!t))];\n\n // Ramps, resolved (so Figma values and overrides show as they will ship).\n const ramps: Record<string, BrandSwatch[]> = {};\n if (inGate) {\n const combo = after.normalizeCombo({ brand: slug });\n const read = (role: string) =>\n STEPS.map((s) => ({ step: s, hex: after.resolve(`palette.${role}.${s}`, combo).css })).filter((x) => /^#[0-9a-f]{6}$/i.test(x.hex));\n ramps.primary = read('primary');\n ramps.neutral = read('neutral');\n for (const role of ['accent', 'link']) {\n const r = read(role);\n if (JSON.stringify(r) !== JSON.stringify(ramps.primary)) ramps[role] = r;\n }\n }\n\n // Tier: every token of the new files is an addition, bridge.config.json is a guardrail. Tier 3, minor.\n const addedTokens = after.defs.filter((d) => created.includes(d.file)).map((d) => ({ kind: 'added' as const, path: d.path }));\n const risk = classifyRisk({ tokenChanges: addedTokens, files: [{ path: CONFIG_FILE, status: 'modified' }], config });\n const planned: PlannedFile[] = [\n ...created.map((f) => ({ path: tokensPath(config, f), action: 'create' as const, content: nextFiles.get(f)! })),\n { path: CONFIG_FILE, action: 'modify', content: configText },\n ];\n const cs = config.changesets ?? (config.changeset ? { dir: '.changeset', package: config.changeset.package } : undefined);\n const changeset = cs\n ? {\n path: `${cs.dir}/bridge-brand-${slug}.md`,\n content: formatChangeset(cs.package, 'minor', `Add the ${name} brand (\\`${slug}\\`), started from ${blank ? 'a blank brand' : brandDisplayName(from)}.`, `- ${created.map((f) => `\\`${tokensPath(config, f)}\\``).join('\\n- ')}\\n- \\`${CONFIG_FILE}\\`: modes.brand gains \"${slug}\", so the token build and the contrast gate cover it.`),\n }\n : undefined;\n if (changeset) planned.push({ path: changeset.path, action: 'create', content: changeset.content });\n\n const errors = issues.filter((i) => i.level === 'error');\n return {\n ok: errors.length === 0 && failing.length === 0 && results.length > 0,\n slug,\n name,\n from,\n title: `Add the ${name} brand`,\n branch: `${config.governance.branchPrefix}brand-${slug || 'new'}`,\n files: planned,\n tokenFiles: Object.fromEntries(nextFiles),\n configText,\n ramps,\n actionStep,\n contrast: { checks: results.length, passing: results.length - failing.length, failing, results, themes },\n issues,\n risk: { ...risk, bump: 'minor' },\n changeset,\n };\n}\n\n/** CSS variables of a planned brand in one theme (every semantic and component token), for live previews. */\nexport function brandPreviewVariables(source: BrandSource, plan: Pick<NewBrandPlan, 'slug' | 'tokenFiles' | 'configText'>, theme?: string): Record<string, string> {\n let config = source.config;\n try {\n config = loadConfig(plan.configText);\n } catch {\n /* keep the old config: the preview falls back to the default brand */\n }\n const set = new LayeredTokenSet(config, new Map(Object.entries(plan.tokenFiles)));\n let combo: Combo;\n try {\n combo = set.normalizeCombo({ brand: plan.slug, ...(theme ? { theme } : {}) });\n } catch {\n combo = set.normalizeCombo(theme ? { theme } : {});\n }\n const out: Record<string, string> = {};\n for (const path of set.view(combo).keys()) {\n const tier = set.tierOf(path);\n if (tier === 'primitive') continue;\n const r = set.resolve(path, combo);\n if (!r.error && r.css) out[set.cssVarName(path)] = r.css;\n }\n return out;\n}\n\n// --- PR body ----------------------------------------------------------------------------------------------\n\nconst code = (s: string) => `\\`${s}\\``;\n\n/** The \"New brand\" section: swatch ramps and the contrast summary. GitHub shows a chip next to `#rrggbb`. */\nexport function newBrandSection(plan: NewBrandPlan): string {\n const roles = Object.keys(plan.ramps);\n const rampTable = roles.length\n ? [\n `| Step | ${roles.map((r) => r[0]!.toUpperCase() + r.slice(1)).join(' | ')} |`,\n `| --- | ${roles.map(() => '---').join(' | ')} |`,\n ...STEPS.map((s) => `| ${s}${s === plan.actionStep ? ' (actions)' : ''} | ${roles.map((r) => code(plan.ramps[r]!.find((x) => x.step === s)?.hex ?? '')).join(' | ')} |`),\n ].join('\\n')\n : '_No ramps resolved._';\n const c = plan.contrast;\n const contrastLine = c.failing.length\n ? `**${c.failing.length} of ${c.checks} pairs fail** for ${plan.name} (${c.themes.join(' and ')}).`\n : `All ${c.checks} contrast checks pass for ${plan.name} in ${c.themes.join(' and ')}.`;\n const failRows = c.failing.slice(0, 20).map((r) => `| ${code(r.fg)} on ${code(r.bg)} | ${r.modes.split(',').find((m) => m.startsWith('theme='))?.slice(6) ?? r.modes} | ${r.ratio ?? 'n/a'} | ${r.min} |`);\n const tightest = [...c.results].filter((r) => r.pass && r.ratio !== null).sort((a, b) => a.ratio! - a.min - (b.ratio! - b.min)).slice(0, 3);\n return [\n '## New brand',\n '',\n `- Name: **${plan.name}** (${code(plan.slug)})`,\n `- Started from: ${plan.from === 'blank' ? 'a blank brand' : brandDisplayName(plan.from)}`,\n `- Primary actions use step ${plan.actionStep} of the primary ramp in the light theme.`,\n '',\n rampTable,\n '',\n '### Contrast',\n '',\n contrastLine,\n ...(failRows.length ? ['', '| Pair | Theme | Ratio | Min |', '| --- | --- | --- | --- |', ...failRows] : []),\n ...(tightest.length ? ['', `Tightest passing pairs: ${tightest.map((r) => `${code(r.fg)} on ${code(r.bg)} ${r.ratio}:1 (min ${r.min})`).join('; ')}.`] : []),\n ].join('\\n');\n}\n\nexport interface NewBrandBodyOptions {\n /** \"the bridge CLI\", \"Bridge MCP\", \"the Bridge Studio\", \"the DS Bridge Figma plugin\". */\n tool: string;\n author?: string;\n /** true when an AI agent proposed it. */\n agent?: boolean;\n /** Free text from the person proposing. */\n notes?: string;\n}\n\nexport function composeNewBrandBody(plan: NewBrandPlan, opts: NewBrandBodyOptions): string {\n const t = plan.risk.tier;\n const box = (n: 1 | 2 | 3) => `- ${n === t ? '[x]' : '[ ]'} ${RISK_LABELS[n]}`;\n const errors = plan.issues.filter((i) => i.level === 'error');\n const warnings = plan.issues.filter((i) => i.level === 'warning');\n return [\n '## What changed and why',\n '',\n `Adds the ${plan.name} brand. Components do not change: the brand re-points palette, radius and font roles, and the token build, the contrast gate and the docs pick it up from ${code('bridge.config.json')}.`,\n ...(opts.notes?.trim() ? ['', opts.notes.trim()] : []),\n '',\n `Proposed through ${opts.tool}${opts.author ? ` by ${opts.author}` : ''}.${opts.agent ? ' Agent-authored: a human design owner and tech owner review and merge.' : ''}`,\n '',\n newBrandSection(plan),\n '',\n '## Files',\n '',\n ...plan.files.map((f) => `- ${f.action === 'create' ? 'Create' : 'Modify'} ${code(f.path)}`),\n '',\n '## Risk tier',\n '',\n box(1),\n box(2),\n box(3),\n '',\n `- Brand added: ${plan.files.filter((f) => f.action === 'create' && f.path.endsWith('.tokens.json')).length} token file(s), every token new`,\n `- ${code('bridge.config.json')} is a guardrail file`,\n `- Semver bump: ${code(plan.risk.bump)} for ${code('@bridge-ds/tokens')}`,\n '',\n '## Checks',\n '',\n `- Token validation: ${errors.length ? `**${errors.length} error(s)**` : 'no errors'} (DTCG shapes, aliases, every mode)${warnings.length ? `, ${warnings.length} warning(s): ${warnings.map((w) => w.message).join(' ')}` : ''}`,\n `- Contrast gate for ${plan.name}: ${plan.contrast.failing.length ? `**${plan.contrast.failing.length} failing pair(s)**` : `all ${plan.contrast.checks} pairs pass`}`,\n '',\n '## Authored by',\n '',\n opts.agent ? '- [ ] Human' : '- [x] Human',\n opts.agent ? '- [x] AI agent (Claude), reviewed by a human before merge' : '- [ ] AI agent',\n '',\n '## Design review checklist',\n '',\n '- [ ] Checked in light and dark, with real components (Studio preview or Storybook brand switch)',\n '- [ ] Primary, zone and link colors read as one family',\n '- [ ] Changeset bump matches the tier',\n '',\n ].join('\\n');\n}\n","// Component docs drafts: the deterministic part of a component's documentation, computed from its code, and the\n// review state of prose an AI drafted. Shared by the Bridge docs editor, the MCP server (bridge_draft_docs), the\n// CLI (bridge docs draft) and the docs-draft GitHub Action, so a draft looks the same wherever it starts.\n//\n// What code can tell (deterministic, never invented): the props table from the TypeScript props, the tokens the\n// stylesheet reads, the anatomy from the CSS module classes, the contrast pairs those tokens take part in, and a\n// changelog line. What only a person (or an AI, then a person) can write: summary, when to use, do and don't,\n// accessibility and content guidelines. Prose an AI wrote carries \"draftedBy\": \"claude\" and \"needsReview\": true\n// until a reviewer accepts it.\n\nimport { type JsonEntry, type JsonNode, fromPlain, getEntry, parseJson, plainEqual, serializeJson, toPlain } from './json-ast';\n\nexport type DocsExampleNode = string | { c: string; p?: Record<string, unknown>; children?: DocsExampleNode[] };\n\nexport interface DocsGuidance {\n title: string;\n text: string;\n example?: DocsExampleNode;\n}\n\n/** The shape of <Name>.docs.json (same keys as Button.docs.json). */\nexport interface ComponentDocsJson {\n summary: string;\n category?: string;\n status?: 'stable' | 'beta' | 'deprecated';\n preview?: DocsExampleNode;\n whenToUse: string[];\n whenNotToUse: string[];\n dos: DocsGuidance[];\n donts: DocsGuidance[];\n accessibility: string[];\n contentGuidelines?: string[];\n anatomy?: Record<string, string>;\n /** Who wrote the prose when it was not a person in the editor. Only \"claude\" today. */\n draftedBy?: string;\n /**\n * The prose sections Claude drafted that wait for review, when a draft covered only some of them (in-place drafting\n * on the Library page, the docs-draft Action). Missing means the whole file. Accepting removes it.\n */\n draftedSections?: ProseKey[];\n /** True while drafted prose waits for a reviewer. Accepting sets it to false. */\n needsReview?: boolean;\n}\n\n/** Keys of docs.json in the order Button.docs.json lists them. The editor and the drafts follow this order. */\nexport const DOCS_KEYS = ['summary', 'preview', 'whenToUse', 'whenNotToUse', 'dos', 'donts', 'accessibility', 'contentGuidelines', 'anatomy'] as const;\nexport type DocsKey = (typeof DOCS_KEYS)[number];\n\n/** Prose keys: the ones code cannot fill. */\nexport const PROSE_KEYS = ['summary', 'whenToUse', 'whenNotToUse', 'dos', 'donts', 'accessibility', 'contentGuidelines'] as const;\nexport type ProseKey = (typeof PROSE_KEYS)[number];\n\nexport interface DocsPropInput {\n name: string;\n type: string;\n required: boolean;\n defaultValue?: string | undefined;\n description?: string | undefined;\n}\n\nexport interface DocsContrastInput {\n foreground: string;\n background: string;\n /** Lowest ratio over every brand and theme. */\n ratio: number;\n min: number;\n}\n\nexport interface DocsPrefillInput {\n /** PascalCase component name. */\n name: string;\n /** JSDoc of the component export, when there is one. */\n description?: string | undefined;\n props: DocsPropInput[];\n /** Native element whose attributes the component also accepts (button, span). */\n inherits?: string | undefined;\n /** CSS custom properties the stylesheet reads that are tokens, e.g. --color-text-default. */\n tokens: string[];\n /** Tokens it reads through another component's stylesheet, by that component (IconButton reads Button's). */\n inheritedTokens?: Record<string, string[]>;\n /** Class names of the CSS module, in source order. */\n cssClasses: string[];\n /** Contrast pairs from the contrast checks that involve the tokens it reads. */\n contrast?: DocsContrastInput[];\n /** The docs.json it has today, if any: existing prose is kept, only gaps are listed. */\n existing?: Partial<ComponentDocsJson> | null;\n /** What changed, when the pre-fill runs for a proposed change (\"token color.text.muted changed\"). */\n change?: string;\n}\n\nexport interface DocsPrefill {\n component: string;\n /** Markdown table: prop, type, default, description. Empty string when the component has no props. */\n propsTable: string;\n tokens: string[];\n inheritedTokens: Record<string, string[]>;\n /** Class name -> readable label, keeping labels a writer already set. */\n anatomy: Record<string, string>;\n contrastNotes: string[];\n changelogLine: string;\n /** Prose keys with no content yet. */\n missing: ProseKey[];\n /** docs.json with the deterministic parts filled and the existing prose kept. Empty prose stays empty. */\n draft: ComponentDocsJson;\n}\n\nconst ACRONYMS = new Set(['sm', 'md', 'lg', 'xl', 'xs']);\n\n/** Readable label for a CSS module class: iconOnly -> \"Icon only\", is-open -> \"Is open\", sm -> \"Size sm\". */\nexport function anatomyLabel(className: string): string {\n if (ACRONYMS.has(className)) return `Size ${className}`;\n const words = className\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/[-_]+/g, ' ')\n .trim()\n .toLowerCase();\n if (!words) return className;\n if (words === 'root') return 'Container';\n return words.charAt(0).toUpperCase() + words.slice(1);\n}\n\n/** Class names of a CSS module, in source order, without duplicates and without keyframes. */\nexport function cssModuleClasses(css: string): string[] {\n const clean = css.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '').replace(/@keyframes\\s+[\\w-]+\\s*\\{(?:[^{}]*\\{[^{}]*\\})*[^{}]*\\}/g, '');\n const out: string[] = [];\n for (const m of clean.matchAll(/\\.(-?[_a-zA-Z][\\w-]*)/g)) {\n // Skip decimals inside values (0.5) and file names: a class follows a selector boundary.\n const before = clean[m.index! - 1] ?? ' ';\n if (/[\\w)]/.test(before)) continue;\n if (!out.includes(m[1]!)) out.push(m[1]!);\n }\n return out;\n}\n\nconst cell = (s: string) => s.replace(/\\|/g, '\\\\|').replace(/\\n/g, ' ');\n\nexport function propsTable(name: string, props: DocsPropInput[], inherits?: string): string {\n if (!props.length) return inherits ? `${name} has no props of its own. It accepts every native <${inherits}> attribute.` : '';\n const rows = props.map((p) => `| \\`${p.name}\\`${p.required ? ' (required)' : ''} | \\`${cell(p.type)}\\` | ${p.defaultValue ? `\\`${cell(p.defaultValue)}\\`` : ''} | ${cell(p.description ?? '')} |`);\n const tail = inherits ? `\\n\\nAlso accepts every native <${inherits}> attribute.` : '';\n return ['| Prop | Type | Default | Description |', '| --- | --- | --- | --- |', ...rows].join('\\n') + tail;\n}\n\nconst isEmpty = (v: unknown) => v === undefined || v === null || (typeof v === 'string' && !v.trim()) || (Array.isArray(v) && v.length === 0);\n\n/** Prose keys with no content in a docs.json (missing or empty). */\nexport function missingProse(d: Partial<ComponentDocsJson> | null | undefined): ProseKey[] {\n return PROSE_KEYS.filter((k) => isEmpty(d?.[k]));\n}\n\n/** The deterministic pre-fill of a component's docs. Same input, same output: nothing is invented. */\nexport function prefillDocs(input: DocsPrefillInput): DocsPrefill {\n const existing = input.existing ?? null;\n const anatomy: Record<string, string> = {};\n for (const c of input.cssClasses) anatomy[c] = existing?.anatomy?.[c] ?? anatomyLabel(c);\n const contrastNotes = (input.contrast ?? [])\n .slice()\n .sort((a, b) => a.ratio - b.ratio)\n .map((p) => `${p.foreground} on ${p.background}: ${p.ratio.toFixed(2)}:1 at worst over every brand and theme, needs ${p.min}:1 (${p.ratio >= p.min ? 'passes' : 'fails'}).`);\n const missing = missingProse(existing);\n const changelogLine = input.change\n ? `${input.name}: ${input.change.replace(/\\.$/, '')}.`\n : missing.length === PROSE_KEYS.length\n ? `${input.name}: usage guidance added.`\n : `${input.name}: usage guidance updated.`;\n const draft: ComponentDocsJson = {\n summary: existing?.summary ?? input.description ?? '',\n ...(existing?.category ? { category: existing.category } : {}),\n ...(existing?.status ? { status: existing.status } : {}),\n ...(existing?.preview ? { preview: existing.preview } : {}),\n whenToUse: existing?.whenToUse ?? [],\n whenNotToUse: existing?.whenNotToUse ?? [],\n dos: existing?.dos ?? [],\n donts: existing?.donts ?? [],\n accessibility: existing?.accessibility ?? [],\n contentGuidelines: existing?.contentGuidelines ?? [],\n anatomy,\n ...(existing?.draftedBy ? { draftedBy: existing.draftedBy } : {}),\n ...(existing?.draftedSections?.length ? { draftedSections: existing.draftedSections } : {}),\n ...(existing?.needsReview !== undefined ? { needsReview: existing.needsReview } : {}),\n };\n return {\n component: input.name,\n propsTable: propsTable(input.name, input.props, input.inherits),\n tokens: [...new Set(input.tokens)].sort(),\n inheritedTokens: input.inheritedTokens ?? {},\n anatomy,\n contrastNotes,\n changelogLine,\n missing,\n draft,\n };\n}\n\nexport interface DocsConventions {\n /** AGENTS.md (or the part about docs.json). */\n agents?: string;\n /** The voice section of the design language. */\n voice?: string;\n /** A finished docs.json to copy the structure and tone from (Button.docs.json). */\n example?: string;\n /** The component source, so the prose stays true to the code. */\n source?: string;\n /** The component's CSS module: its states and parts, so the prose stays true to the look. */\n styles?: string;\n}\n\n/** What docsPrompt asks for. Without `keys`, the missing prose as a full docs.json (the docs-draft Action, bridge_draft_docs). */\nexport interface DocsPromptOptions {\n /** Only these sections, answered as an object holding only them. */\n keys?: readonly ProseKey[];\n /** Rewrite the sections even when they hold text. */\n rewrite?: boolean;\n /**\n * Written sections older than the component code, to check (among `keys`): Claude returns one only when something\n * in it is no longer true for the code, keeping the writer's wording elsewhere; an accurate one is left out.\n */\n check?: readonly ProseKey[];\n}\n\nconst SECTION_SHAPE: Record<ProseKey, string> = {\n summary: '\"summary\": \"one or two sentences\"',\n whenToUse: '\"whenToUse\": [\"...\"]',\n whenNotToUse: '\"whenNotToUse\": [\"...\"]',\n dos: '\"dos\": [{ \"title\": \"...\", \"text\": \"...\" }]',\n donts: '\"donts\": [{ \"title\": \"...\", \"text\": \"...\" }]',\n accessibility: '\"accessibility\": [\"...\"]',\n contentGuidelines: '\"contentGuidelines\": [\"...\"]',\n};\n\n/** The JSON shape of these sections, for a prompt: {\"summary\": \"...\", \"dos\": [{ \"title\", \"text\" }]}. */\nexport const docsSectionShapes = (keys: readonly ProseKey[]): string => `{ ${keys.map((k) => SECTION_SHAPE[k]).join(', ')} }`;\n\n/**\n * The prompt a model gets to write the prose of a docs.json: the pre-fill as facts, the conventions, and strict\n * rules (no invention, JSON only). Used by the GitHub Action and returned by bridge_draft_docs for the user's own\n * Claude.\n */\nexport function docsPrompt(prefill: DocsPrefill, conventions: DocsConventions = {}, options: DocsPromptOptions = {}): string {\n const facts = [\n `Component: ${prefill.component}`,\n prefill.propsTable ? `Props (parsed from TypeScript):\\n${prefill.propsTable}` : 'Props: none of its own.',\n `Tokens its stylesheet reads: ${prefill.tokens.join(', ') || 'none'}`,\n ...Object.entries(prefill.inheritedTokens).map(([from, list]) => `Tokens it reads through ${from}'s stylesheet: ${list.length}`),\n `Anatomy (CSS module classes): ${Object.entries(prefill.anatomy)\n .map(([k, v]) => `${k} = ${v}`)\n .join('; ') || 'none'}`,\n prefill.contrastNotes.length ? `Contrast checks:\\n- ${prefill.contrastNotes.join('\\n- ')}` : '',\n `Changelog line: ${prefill.changelogLine}`,\n ].filter(Boolean);\n const block = (title: string, text?: string) => (text?.trim() ? `<${title}>\\n${text.trim()}\\n</${title}>` : '');\n const keys = options.keys;\n const check = keys ? (options.check ?? []).filter((k) => keys.includes(k)) : [];\n const write = keys ? keys.filter((k) => !check.includes(k)) : [];\n const task = keys\n ? [\n ...(write.length ? [`${options.rewrite ? 'Rewrite' : 'Write'} these sections of ${prefill.component}.docs.json for the Bridge design system: ${write.join(', ')}.`] : []),\n ...(check.length\n ? [\n `Check these written sections of ${prefill.component}.docs.json against the current code: ${check.join(', ')}. The code changed after they were written.`,\n 'Return a checked section ONLY when something in it is no longer true for the code (a wrong or removed prop, a removed state or variant, changed behavior). Then return the whole section with only the untrue parts fixed, keeping the writer\\'s wording everywhere else.',\n 'Leave a checked section out of the answer when it is still accurate: a missing key means unchanged. Never return a checked section just to improve its style.',\n ]\n : []),\n ...(options.rewrite ? ['Rewrite each one from the facts and the source: keep what is true in the current text, drop what the code does not support.'] : []),\n ]\n : [`Write the missing prose of ${prefill.component}.docs.json for the Bridge design system.`];\n const shape = keys\n ? [\n `- ${check.length ? 'Return' : 'Write'} only these keys: ${keys.join(', ')}${check.length ? ` (the checked ones, ${check.join(', ')}, only when they need a fix)` : ''}. Never return anatomy, preview or any other key: code decides them.`,\n `- Answer with one JSON object holding only those keys, nothing else: ${docsSectionShapes(keys)}.`,\n ]\n : [\n `- Fill only these keys: ${prefill.missing.join(', ') || 'none (everything is written: improve nothing, return the draft as is)'}. Keep every other key exactly as given.`,\n '- Answer with the full docs.json as one JSON object, nothing else.',\n ];\n return [\n ...task,\n '',\n 'Rules:',\n '- Ground every sentence in the facts and the source below. Never invent props, variants, keyboard behavior or tokens that are not there.',\n '- Bridge voice: sentence case, plain words, verbs first, no em dashes, no marketing words.',\n '- Keep the keys and shapes of the example docs.json. dos and donts are { \"title\", \"text\" } objects; add an \"example\" only with components and props that exist.',\n ...shape,\n '',\n 'Facts computed from the code:',\n facts.join('\\n\\n'),\n '',\n `Current draft:\\n${JSON.stringify(prefill.draft, null, 2)}`,\n '',\n block('source', conventions.source),\n block('styles', conventions.styles),\n block('agents-md', conventions.agents),\n block('voice', conventions.voice),\n block('example-docs-json', conventions.example),\n ]\n .filter((x, i, all) => x !== '' || all[i - 1] !== '')\n .join('\\n');\n}\n\n/**\n * Marks prose as drafted by Claude and waiting for review. With `sections`, only those sections were drafted: they\n * join the ones already waiting (draftedSections, in the PROSE_KEYS order). Without, the whole file was.\n */\nexport function markClaudeDraft<T extends Partial<ComponentDocsJson>>(d: T, sections?: readonly ProseKey[]): T {\n if (!sections) {\n const { draftedSections: _all, ...rest } = d;\n return { ...rest, draftedBy: 'claude', needsReview: true } as T;\n }\n const waiting = d.needsReview === true ? (d.draftedSections ?? (d.draftedBy ? [...PROSE_KEYS] : [])) : [];\n const union = PROSE_KEYS.filter((k) => waiting.includes(k) || sections.includes(k));\n return { ...d, draftedBy: 'claude', needsReview: true, draftedSections: union };\n}\n\n/** Prose sections that wait for review: draftedSections, every prose key for a whole-file draft, none once accepted. */\nexport function sectionsNeedingReview(d: Partial<ComponentDocsJson> | null | undefined): ProseKey[] {\n if (!d || d.needsReview !== true) return [];\n return d.draftedSections ? PROSE_KEYS.filter((k) => d.draftedSections!.includes(k)) : [...PROSE_KEYS];\n}\n\n/** True when the docs hold AI-drafted prose nobody has reviewed yet. */\nexport const needsDocsReview = (d: Partial<ComponentDocsJson> | null | undefined): boolean => Boolean(d && d.needsReview === true);\n\n/** A reviewer accepts drafted prose: needsReview goes false, draftedBy stays as the record of who wrote it. */\nexport function acceptDocsDraft(d: ComponentDocsJson): ComponentDocsJson {\n const { draftedSections: _done, ...rest } = d;\n return { ...rest, needsReview: false };\n}\n\n/** docs.json text the way the repo writes it: two spaces, keys in the Button.docs.json order, trailing newline. */\nexport function formatDocsJson(d: Partial<ComponentDocsJson>): string {\n const order = ['summary', 'category', 'status', ...DOCS_KEYS.filter((k) => k !== 'summary'), 'draftedBy', 'draftedSections', 'needsReview'];\n const out: Record<string, unknown> = {};\n for (const k of order) if ((d as Record<string, unknown>)[k] !== undefined) out[k] = (d as Record<string, unknown>)[k];\n for (const [k, v] of Object.entries(d)) if (!(k in out) && v !== undefined) out[k] = v;\n return `${JSON.stringify(out, null, 2)}\\n`;\n}\n\n/** Keeps untouched nodes as they were written; rebuilds only what changed, in the shape of what it replaces. */\nfunction patchNode(old: JsonNode, next: unknown): JsonNode {\n if (plainEqual(toPlain(old), next)) return old;\n if (old.kind === 'object' && next && typeof next === 'object' && !Array.isArray(next)) {\n const n = next as Record<string, unknown>;\n const kept = old.entries.filter((e) => n[e.key] !== undefined).map((e): JsonEntry => ({ key: e.key, value: patchNode(e.value, n[e.key]) }));\n const added = Object.keys(n)\n .filter((k) => n[k] !== undefined && !getEntry(old, k))\n .map((k): JsonEntry => ({ key: k, value: fromPlain(n[k], undefined, old.inline) }));\n return { kind: 'object', inline: old.inline, entries: [...kept, ...added] };\n }\n if (old.kind === 'array' && Array.isArray(next)) {\n return { kind: 'array', inline: old.inline, items: next.map((v, i) => (old.items[i] ? patchNode(old.items[i]!, v) : fromPlain(v, old.items[0], old.inline))) };\n }\n return fromPlain(next, old);\n}\n\n/**\n * docs.json text for edited docs, written as a minimal diff of the file it replaces: untouched sections stay byte for\n * byte (a hand-formatted file keeps its inline preview nodes), new keys go at the end in the repo order. Without an\n * original (or with one that is not valid JSON) it falls back to formatDocsJson.\n */\nexport function patchDocsJson(original: string | null | undefined, next: Partial<ComponentDocsJson>): string {\n const plain = JSON.parse(formatDocsJson(next)) as unknown;\n if (!original) return formatDocsJson(next);\n try {\n const doc = parseJson(original);\n if (doc.root.kind !== 'object') return formatDocsJson(next);\n return serializeJson({ ...doc, root: patchNode(doc.root, plain) });\n } catch {\n return formatDocsJson(next);\n }\n}\n\n/** Accepts the drafted prose inside a docs.json text: only the review lines change. Throws on invalid JSON. */\nexport function acceptDocsText(text: string): string {\n return patchDocsJson(text, acceptDocsDraft(JSON.parse(text) as ComponentDocsJson));\n}\n\n/** Tier and bump of a docs-only change: Tier 1 under the shared classifier, and a patch. */\nexport const DOCS_CHANGE_BUMP = 'patch' as const;\n","// Change drafts: the words a designer would otherwise type by hand when sending a change for review. Deterministic and\n// offline: computed only from what the diff detected, so they never invent a reason or a number. Shared by the Figma\n// plugin (request form, Push description) and any tool that sends requests or pull requests from detected changes.\n//\n// Voice (docs/DESIGN-LANGUAGE.md section 10): sentence case, starts with a verb, no em dash, digits for numbers.\n// A request title never repeats the component: the issue title already starts with it (\"Badge: add a danger tone\").\n\nimport type { DiffEntry } from './diff-engine';\nimport type { RequestChange, RequestKind } from './requests';\nimport { modeDisplayName } from './types';\nimport { formatValue } from './values';\n\nexport interface DraftText {\n /** One line, sentence case, no trailing period. Empty when nothing was detected. */\n title: string;\n /** 1 or 2 sentences. Empty when nothing was detected. */\n summary: string;\n}\n\n/** Removes em dashes (U+2014), the punctuation the Bridge voice never uses: \" a [em dash] b \" becomes \"a, b\". */\nexport function cleanDraftText(text: string): string {\n return text\n .replace(/\\s*\\u2014\\s*/g, ', ')\n .replace(/,\\s*,/g, ',')\n .replace(/^,\\s*/, '')\n .replace(/[ \\t]+/g, ' ')\n .trim();\n}\n\nconst values = (s: string | undefined) => (s ?? '').split(', ').map((x) => x.trim()).filter(Boolean);\nconst article = (word: string) => (/^[aeiou]/i.test(word) ? 'an' : 'a');\nconst andList = (xs: string[]) => (xs.length <= 1 ? (xs[0] ?? '') : `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`);\nconst plural = (n: number, word: string, many = `${word}s`) => `${n} ${n === 1 ? word : many}`;\nconst capital = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);\nconst lower = (s: string) => s.charAt(0).toLowerCase() + s.slice(1);\n\n/** \"boolean, default false\" -> { type: \"boolean\", def: \"false\" }. */\nfunction propShape(s: string | undefined): { type: string; def: string } | undefined {\n if (!s) return undefined;\n const m = /^(.*?), default (.*)$/.exec(s);\n return m ? { type: m[1]!, def: m[2]! } : { type: s, def: '' };\n}\n\n// ---------------------------------------------------------------------------------------------\n// Structure changes: a layer added, removed or moved in a variant. The scan writes them as rows\n// `New layer \"Icon\" (Size=sm, Variant=primary)` with the kind and the place as values:\n// added `instance Icon/Pencil, after \"Label\"`, removed the same as `before`, moved `after \"A\"` -> `before \"B\"`.\n\nconst VARIANT_FIRST = ['variant', 'tone', 'intent', 'appearance', 'kind', 'type', 'style'];\n\n/** \"Size=sm, State=Default, Variant=primary\" -> \"primary sm\": the values a designer says, default states left out. */\nexport function shortVariant(key: string): string {\n const pairs = key.split(', ').map((p) => {\n const at = p.indexOf('=');\n return at < 0 ? { k: '', v: p.trim() } : { k: p.slice(0, at).trim(), v: p.slice(at + 1).trim() };\n });\n const kept = pairs.filter((p) => p.v && !/^default$/i.test(p.v));\n if (!kept.length) return key;\n const rank = (k: string) => {\n const i = VARIANT_FIRST.indexOf(k.toLowerCase());\n return i < 0 ? VARIANT_FIRST.length : i;\n };\n return kept\n .map((p, i) => ({ ...p, i }))\n .sort((a, b) => rank(a.k) - rank(b.k) || a.i - b.i)\n .map((p) => p.v)\n .join(' ');\n}\n\n/** \"Size=sm, Variant=primary; Size=md, Variant=primary\" -> \"primary sm and primary md\"; empty -> \"every variant\". */\nexport const shortVariants = (list: string | undefined) => (list ? andList(list.split('; ').map(shortVariant)) : 'every variant');\n\nexport interface StructureRow {\n op: 'added' | 'removed' | 'moved';\n name: string;\n /** \"in primary sm\" or \"in every variant\". */\n where: string;\n /** Layer type in words (\"instance\", \"text\", \"frame\"), when known. */\n type?: string | undefined;\n /** Main component of an instance (\"Icon/Pencil\"). */\n main?: string | undefined;\n /** Where it sits now (added, moved) or sat (removed): `after \"Label\"`, `before \"Label\"`, `alone`. */\n at?: string | undefined;\n /** Moved: where it sat before. */\n from?: string | undefined;\n}\n\n/** A structure row read back, or undefined when the field is not one. */\nexport function parseStructureChange(c: RequestChange): StructureRow | undefined {\n const m = /^(New|Removed|Moved) layer \"(.*)\"(?: \\((.*)\\))?$/.exec(c.field);\n if (!m) return undefined;\n const op = m[1] === 'New' ? 'added' : m[1] === 'Removed' ? 'removed' : 'moved';\n const where = `in ${shortVariants(m[3])}`;\n if (op === 'moved') return { op, name: m[2]!, where, at: c.after, from: c.before };\n const shape = (op === 'added' ? c.after : c.before) ?? '';\n const sm = /^(\\S+)(?: (.*?))?, ((?:after|before) \".*\"|alone)$/.exec(shape);\n return { op, name: m[2]!, where, ...(sm ? { type: sm[1], ...(sm[2] ? { main: sm[2] } : {}), at: sm[3] } : {}) };\n}\n\nfunction structurePhrase(r: StructureRow): string {\n const type = r.type ? `${r.type} ` : '';\n const main = r.main ? ` (${r.main})` : '';\n const at = r.at && r.at !== 'alone' ? ` ${r.at}` : '';\n if (r.op === 'added') return `New ${type}layer \"${r.name}\"${main}${at} ${r.where}`;\n if (r.op === 'removed') return `Removed ${type}layer \"${r.name}\"${main}${at} ${r.where}`;\n return `Moved layer \"${r.name}\" ${r.at ?? ''}${r.from ? ` (was ${r.from})` : ''} ${r.where}`.replace(/\\s+/g, ' ');\n}\n\nconst bare = (at: string | undefined) => (at ?? '').replace(/\"/g, '');\n\n/** Title and summary for the first change of a detected component change. */\nfunction firstChange(component: string, kind: RequestKind, c: RequestChange | undefined, all: RequestChange[]): DraftText {\n switch (kind) {\n case 'new-component': {\n const axes = all.filter((x) => x.field.startsWith('Variant '));\n const props = all.filter((x) => x.field.startsWith('Prop '));\n const parts = [axes.length ? plural(axes.length, 'variant axis', 'variant axes') : '', props.length ? plural(props.length, 'prop') : ''].filter(Boolean);\n return {\n title: `Add the ${component} component`,\n summary: `${component} is not in code yet.${parts.length ? ` The Figma component has ${andList(parts)}.` : ''}`,\n };\n }\n case 'new-variant': {\n if (!c) return { title: `Update the ${component} variants`, summary: `The variants of ${component} changed in Figma.` };\n const axis = c.field.replace(/^Variant /, '');\n const before = values(c.before);\n const after = values(c.after);\n const added = after.filter((x) => !before.includes(x));\n const removed = before.filter((x) => !after.includes(x));\n const word = axis.toLowerCase();\n if (!before.length) return { title: `Add a ${axis} variant axis`, summary: `${component} gets a new variant axis, ${axis}, with ${after.length === 1 ? 'the value' : 'the values'} ${andList(after)}.` };\n if (!after.length) return { title: `Remove the ${axis} variant axis`, summary: `${component} no longer has the ${axis} variant axis (${andList(before)}).` };\n if (added.length === 1 && !removed.length) return { title: `Add ${article(added[0]!)} ${added[0]} ${word}`, summary: `${component} gets a new ${axis} value, ${added[0]}.` };\n if (added.length && !removed.length) return { title: `Add ${andList(added)} to ${axis}`, summary: `${component} gets ${plural(added.length, `new ${axis} value`)}: ${andList(added)}.` };\n if (removed.length === 1 && !added.length) return { title: `Remove the ${removed[0]} ${word}`, summary: `${component} no longer has the ${axis} value ${removed[0]}.` };\n if (removed.length && !added.length) return { title: `Remove ${andList(removed)} from ${axis}`, summary: `${component} no longer has the ${axis} values ${andList(removed)}.` };\n return { title: `Change the ${axis} values`, summary: `${axis} on ${component} goes from ${andList(before)} to ${andList(after)}.` };\n }\n case 'prop-change': {\n if (!c) return { title: `Change a ${component} prop`, summary: `A prop of ${component} changed in Figma.` };\n const name = c.field.replace(/^Prop /, '');\n const b = propShape(c.before);\n const a = propShape(c.after);\n if (!b && a) return { title: `Add the ${name} prop`, summary: `${component} gets a new ${a.type} prop, ${name}${a.def ? `, default ${a.def}` : ''}.` };\n if (b && !a) return { title: `Remove the ${name} prop`, summary: `${component} no longer has the ${name} prop.` };\n if (b && a && b.type === a.type && b.def !== a.def) return { title: `Change the ${name} default to ${a.def || 'empty'}`, summary: `The default of ${name} on ${component} goes from ${b.def || 'empty'} to ${a.def || 'empty'}.` };\n return { title: `Change the ${name} prop`, summary: `${name} on ${component} goes from ${c.before ?? 'none'} to ${c.after ?? 'none'}.` };\n }\n case 'token-binding': {\n if (!c) return { title: 'Use another token', summary: `A part of ${component} uses another token in Figma.` };\n const m = /^(.*?)(?: \\((.*)\\))?$/.exec(c.field)!;\n const part = lower(m[1]!);\n const where = m[2] ? ` in ${m[2]}` : '';\n const after = c.after && c.after !== 'none' ? c.after : '';\n const before = c.before && c.before !== 'none' ? c.before : '';\n if (!after) return { title: `Unbind the ${part}`, summary: `The ${part} of ${component}${where} no longer uses ${before || 'a token'}.` };\n return {\n title: `Use ${after} for the ${part}`,\n summary: `The ${part} of ${component}${where} ${before ? `moves from ${before} to ${after}` : `now uses ${after}`}.`,\n };\n }\n case 'structure': {\n const r = c ? parseStructureChange(c) : undefined;\n if (!r) return { title: 'Change the layers to match Figma', summary: `The layers of ${component} changed in Figma.` };\n if (r.op === 'added') {\n const at = r.at && r.at !== 'alone' ? ` ${bare(r.at)}` : '';\n return { title: `Add a layer${at}`, summary: `${component} gets ${article(r.type ?? 'layer')} ${r.type ?? 'layer'}${r.type ? ' layer' : ''}, ${r.name}${r.main ? ` (${r.main})` : ''}${at} ${r.where}.` };\n }\n if (r.op === 'removed') return { title: `Remove the ${r.name} layer`, summary: `${component} no longer has the ${r.name} layer ${r.where}.` };\n return { title: `Move the ${r.name} layer`, summary: `The ${r.name} layer of ${component} moves ${bare(r.at) || 'elsewhere'}${r.from ? ` (it was ${bare(r.from)})` : ''} ${r.where}.` };\n }\n case 'visual':\n return {\n title: 'Update the look to match Figma',\n summary: `${component} looks different in Figma${c?.field.startsWith('Look of ') && c.field !== 'Look of every variant' ? ` in ${c.field.slice(8)}` : ''}, and no variable edit explains it.`,\n };\n default:\n return { title: '', summary: '' };\n }\n}\n\n/**\n * The deterministic title and summary of a component change request, from the changes a scan detected. Manual\n * requests with no detected change (a bug, an idea) get empty text: there is nothing factual to say yet.\n */\nexport function draftRequestText(component: string, kind: RequestKind, changes: RequestChange[]): DraftText {\n const name = component.trim() || 'the component';\n if (!changes.length && kind !== 'new-component') return { title: '', summary: '' };\n const d = firstChange(name, kind, changes[0], changes);\n const rest = kind === 'new-component' ? 0 : changes.length - 1;\n const summary = rest > 0 ? `${d.summary} ${capital(plural(rest, 'other change'))} ${rest === 1 ? 'is' : 'are'} listed below.` : d.summary;\n return { title: cleanDraftText(d.title), summary: cleanDraftText(summary) };\n}\n\n// ---------------------------------------------------------------------------------------------\n// Change lines: one sentence per detected component change, the main line of its row in the plugin and the first line\n// of its request. Claude rewrites it from the before and after images; this is the deterministic default.\n\n/** A change line is one sentence of at most this many characters, with no trailing period. */\nexport const DRAFT_LINE_MAX = 120;\n\n/** Shortens to `max` characters at a word boundary, without a trailing period. */\nfunction clipText(text: string, max: number): string {\n const t = text.replace(/\\s+/g, ' ').trim().replace(/\\.$/, '');\n if (t.length <= max) return t;\n const cut = t.slice(0, max + 1);\n const at = cut.lastIndexOf(' ');\n return (at > max * 0.5 ? cut.slice(0, at) : t.slice(0, max)).replace(/[\\s,;:(]+$/, '');\n}\n\n/** A change line kept to the contract: one line, no em dash, at most 120 characters, no trailing period. */\nexport function sanitizeDraftLine(raw: unknown): string {\n if (typeof raw !== 'string') return '';\n return capital(clipText(cleanDraftText(raw.replace(/[\\r\\n]+/g, ' ')), DRAFT_LINE_MAX));\n}\n\n/** One change row as a short phrase a developer reads (\"Fill uses color.x instead of color.y in Size=sm\"). */\nfunction changePhrase(c: RequestChange): string {\n let m: RegExpExecArray | null;\n if ((m = /^Variant (.+)$/.exec(c.field))) {\n const axis = m[1]!;\n const before = values(c.before);\n const after = values(c.after);\n if (!before.length) return `New ${axis} variant axis: ${after.join(', ')}`;\n if (!after.length) return `${axis} variant axis removed (${before.join(', ')})`;\n const added = after.filter((x) => !before.includes(x));\n const removed = before.filter((x) => !after.includes(x));\n const parts = [added.length ? `${andList(added)} added to ${axis}` : '', removed.length ? `${andList(removed)} removed from ${axis}` : ''].filter(Boolean);\n return parts.join('; ') || `${axis} values reordered: ${after.join(', ')}`;\n }\n if ((m = /^Prop (.+)$/.exec(c.field))) {\n const name = m[1]!;\n const b = propShape(c.before);\n const a = propShape(c.after);\n if (!b && a) return `New ${a.type} prop ${name}${a.def ? `, default ${a.def}` : ''}`;\n if (b && !a) return `${name} prop removed`;\n if (b && a && b.type === a.type) return `${name} default goes from ${b.def || 'empty'} to ${a.def || 'empty'}`;\n return `${name} prop goes from ${c.before ?? 'none'} to ${c.after ?? 'none'}`;\n }\n if ((m = /^Swapped instance(?: \\((.*)\\))?$/.exec(c.field))) return `Shows ${c.after ?? 'another instance'} instead of ${c.before ?? 'the coded one'} ${m[1] ? `in ${m[1]}` : 'in every variant'}`;\n if ((m = /^Look of (.+)$/.exec(c.field))) return `Looks different in ${m[1]}; no variable explains it`;\n const layer = parseStructureChange(c);\n if (layer) return structurePhrase(layer);\n // A token binding: \"Fill\" or \"Fill (Size=sm, Tone=primary)\".\n m = /^(.*?)(?: \\((.*)\\))?$/.exec(c.field)!;\n const where = m[2] ? ` in ${m[2]}` : '';\n const before = c.before && c.before !== 'none' ? c.before : '';\n const after = c.after && c.after !== 'none' ? c.after : '';\n if (!after) return `${m[1]} no longer uses ${before || 'a token'}${where}`;\n if (!before) return `${m[1]} now uses ${after}${where}`;\n return `${m[1]} uses ${after} instead of ${before}${where}`;\n}\n\n/**\n * The deterministic change line of a detected component change: what changed, in one sentence, from the diff only.\n * The first change is spelled out, the others counted (\"and 2 more\"). Empty when nothing was detected.\n */\nexport function draftChangeLine(kind: RequestKind, changes: RequestChange[]): string {\n if (kind === 'new-component') {\n const axes = changes.filter((x) => x.field.startsWith('Variant ')).length;\n const props = changes.filter((x) => x.field.startsWith('Prop ')).length;\n const parts = [axes ? plural(axes, 'variant axis', 'variant axes') : '', props ? plural(props, 'prop') : ''].filter(Boolean);\n return `New component${parts.length ? ` with ${andList(parts)}` : ''}, not in code yet`;\n }\n if (!changes.length) return '';\n const first = changePhrase(changes[0]!);\n const rest = changes.length - 1;\n const tail = rest ? ` (and ${rest} more)` : '';\n return capital(clipText(cleanDraftText(first), DRAFT_LINE_MAX - tail.length)) + tail;\n}\n\n// ---------------------------------------------------------------------------------------------\n// Push description (variables pull request and the requests sent with it)\n\nconst tokenOf = (e: DiffEntry) => e.figma ?? e.head ?? e.base;\nconst pathOf = (e: DiffEntry) => tokenOf(e)?.path ?? e.path;\n\n/** One line per variable edit for a change table: the token, its value before, its value in Figma. */\nexport function pushChangeRows(entries: DiffEntry[]): RequestChange[] {\n return entries.map((e) => {\n const before = e.head ?? e.base;\n const after = e.figma;\n const show = (t: typeof before) => {\n if (!t) return undefined;\n const modes = Object.keys(t.values);\n if (modes.length <= 1) return formatValue(t.type, t.values[modes[0] ?? '']);\n return modes.map((m) => `${modeDisplayName(m)} ${formatValue(t.type, t.values[m])}`).join('; ');\n };\n const renamed = e.local?.kind === 'renamed' && before && after && before.path !== after.path;\n return { field: renamed ? `${before.path} -> ${after.path}` : pathOf(e), before: show(before), after: show(after) };\n });\n}\n\n/** \"a, b and c\", or \"7 tokens, including a and b\" when the list is long. */\nfunction names(paths: string[]): string {\n if (paths.length <= 3) return andList(paths);\n return `${paths.length} tokens, including ${andList(paths.slice(0, 2))}`;\n}\n\n/** Modes a changed token's value moved in (\"Light and Dark\"), for a single changed token. */\nfunction valueModes(e: DiffEntry): string[] {\n return (e.local?.fields ?? []).filter((f) => f.field === 'value' && f.mode && f.mode !== 'value').map((f) => modeDisplayName(f.mode!));\n}\n\nexport interface PushDraftComponent {\n component: string;\n kind: RequestKind;\n}\n\n/**\n * The deterministic Push description: what the checked variable edits do and which components get a request.\n * 1 or 2 sentences, never a reason (only the designer knows why). Empty when nothing is checked.\n */\nexport function draftPushDescription(entries: DiffEntry[], components: PushDraftComponent[] = []): string {\n const by: Record<'changed' | 'added' | 'renamed' | 'removed', DiffEntry[]> = { changed: [], added: [], renamed: [], removed: [] };\n for (const e of entries) by[e.local?.kind ?? 'changed'].push(e);\n const clauses: string[] = [];\n if (by.changed.length) {\n const only = by.changed.length === 1 ? by.changed[0]! : undefined;\n const fields = new Set((only?.local?.fields ?? []).map((f) => f.field));\n const modes = only ? valueModes(only) : [];\n if (only && fields.size === 1 && fields.has('description')) clauses.push(`updates the description of ${pathOf(only)}`);\n else if (only && modes.length) clauses.push(`changes ${pathOf(only)} in ${andList(modes)}`);\n else clauses.push(`changes ${names(by.changed.map(pathOf))}`);\n }\n if (by.added.length) clauses.push(`adds ${names(by.added.map(pathOf))}`);\n if (by.renamed.length) {\n const r = by.renamed[0]!;\n const from = (r.head ?? r.base)?.path;\n clauses.push(by.renamed.length === 1 && from && from !== pathOf(r) ? `renames ${from} to ${pathOf(r)}` : `renames ${names(by.renamed.map(pathOf))}`);\n }\n if (by.removed.length) clauses.push(`removes ${names(by.removed.map(pathOf))}`);\n const sentences: string[] = [];\n if (clauses.length) sentences.push(`${capital(andList(clauses))}.`);\n const fresh = components.filter((c) => c.kind === 'new-component').map((c) => c.component);\n const changed = [...new Set(components.filter((c) => c.kind !== 'new-component').map((c) => c.component))];\n const comp: string[] = [];\n if (changed.length) comp.push(`${changed.length === 1 ? 'a change' : 'changes'} to ${andList(changed)}`);\n if (fresh.length) comp.push(`the new ${andList(fresh)} component${fresh.length === 1 ? '' : 's'}`);\n if (comp.length) sentences.push(`Requests ${andList(comp)}.`);\n return cleanDraftText(sentences.join(' '));\n}\n","// Component docs drafted with Claude: the task (which sections, or a selected passage), the prompt, the answer\n// parsing and sanitizing, the merge into a docs.json, and the Messages API request. Shared by the docs-draft GitHub\n// Action (scripts/docs-draft.mjs), the in-place drafting of the Library page (apps/docs-site docs-ai) and the draft\n// exchange (the user's own Claude through the Bridge MCP server), so an answer is cleaned the same way everywhere.\n// Pure: no DOM, no Node-only API. The callers do the fetch.\n\nimport { cleanDraftText } from './change-drafts';\nimport {\n type ComponentDocsJson,\n type DocsConventions,\n type DocsExampleNode,\n type DocsGuidance,\n type DocsPrefill,\n PROSE_KEYS,\n type ProseKey,\n docsPrompt,\n markClaudeDraft,\n} from './docs-draft';\n\nexport const DOCS_DRAFT_MODEL = 'claude-sonnet-5-5';\nexport const ANTHROPIC_MESSAGES_URL = 'https://api.anthropic.com/v1/messages';\n\n/** How a selected passage is rewritten. */\nexport type DocsSelectionMode = 'clearer' | 'shorter' | 'voice';\nexport const DOCS_SELECTION_MODES: Record<DocsSelectionMode, string> = {\n clearer: 'Make it clearer: plain words, one idea per sentence, the most useful fact first.',\n shorter: 'Make it shorter: keep every fact, drop filler, aim for half the words or fewer.',\n voice: 'Put it in the Bridge voice: sentence case, verbs first, calm and precise, no marketing words, no em dash.',\n};\nexport const isDocsSelectionMode = (m: unknown): m is DocsSelectionMode => typeof m === 'string' && m in DOCS_SELECTION_MODES;\nexport const isProseKey = (k: unknown): k is ProseKey => typeof k === 'string' && (PROSE_KEYS as readonly string[]).includes(k);\n\n/**\n * One drafting job on a component's docs. \"sections\": write these prose sections (rewrite: even when they hold text;\n * check: written sections older than the code, returned only when no longer true for it, so an absent one is still\n * accurate). \"selection\": rewrite one passage of a section, nothing else.\n */\nexport type DocsDraftTask =\n | { kind: 'sections'; keys: ProseKey[]; rewrite?: boolean | undefined; check?: ProseKey[] | undefined }\n | { kind: 'selection'; key: ProseKey; text: string; mode: DocsSelectionMode };\n\n/** Problems in a task, as sentences. Empty when valid. */\nexport function validateDocsTask(x: unknown): string[] {\n if (!x || typeof x !== 'object') return ['The docs task is missing.'];\n const t = x as Partial<Record<string, unknown>>;\n if (t.kind === 'sections') {\n const keys = t.keys;\n if (!Array.isArray(keys) || !keys.length || !keys.every(isProseKey)) return [`The docs task lists no sections: use ${PROSE_KEYS.join(', ')}.`];\n if (t.check !== undefined && (!Array.isArray(t.check) || !t.check.every(isProseKey))) return ['check must list prose sections.'];\n return [];\n }\n if (t.kind === 'selection') {\n const out: string[] = [];\n if (!isProseKey(t.key)) out.push(`The selection needs a section: ${PROSE_KEYS.join(', ')}.`);\n if (typeof t.text !== 'string' || !t.text.trim()) out.push('The selection has no text.');\n if (!isDocsSelectionMode(t.mode)) out.push('The selection mode must be clearer, shorter or voice.');\n return out;\n }\n return ['The docs task kind must be \"sections\" or \"selection\".'];\n}\n\n/** The keys a task writes. */\nexport const docsTaskKeys = (t: DocsDraftTask): ProseKey[] => (t.kind === 'sections' ? t.keys : [t.key]);\n\n/** The prompt to rewrite a selected passage of a section: the facts and the conventions, the passage, one rule. */\nexport function docsSelectionPrompt(prefill: DocsPrefill, conventions: DocsConventions, sel: { key: ProseKey; text: string; mode: DocsSelectionMode }): string {\n const base = docsPrompt(prefill, conventions, { keys: [sel.key] });\n // Reuse the facts and conventions of the sections prompt, with the selection task and contract on top.\n const facts = base.slice(base.indexOf('Facts computed from the code:'));\n return [\n `Rewrite one passage of the \"${sel.key}\" section of ${prefill.component}.docs.json for the Bridge design system.`,\n DOCS_SELECTION_MODES[sel.mode],\n '',\n 'Rules:',\n '- Keep its meaning and every fact that the code supports. Never add props, variants, keyboard behavior or tokens that are not in the facts or the source below.',\n '- Bridge voice: sentence case, plain words, verbs first, no em dashes, no marketing words, no Markdown.',\n '- Rewrite only the passage: it is pasted back in place of the selection, inside the rest of the section.',\n '- Answer with one JSON object, nothing else: { \"replacement\": \"the rewritten passage\" }.',\n '',\n `<passage>\\n${sel.text.trim()}\\n</passage>`,\n '',\n facts,\n ].join('\\n');\n}\n\n/** The prompt of a task: docsPrompt for sections (only those keys), docsSelectionPrompt for a selection. */\nexport function docsTaskPrompt(prefill: DocsPrefill, conventions: DocsConventions, task: DocsDraftTask): string {\n if (task.kind === 'selection') return docsSelectionPrompt(prefill, conventions, task);\n return docsPrompt(prefill, conventions, { keys: task.keys, ...(task.rewrite ? { rewrite: true } : {}), ...(task.check?.length ? { check: task.check } : {}) });\n}\n\n// ---------------------------------------------------------------------------------------------\n// Answers: parse and sanitize\n\n/** The first JSON object in a model reply (plain, or inside a ```json fence). Throws when there is none. */\nexport function parseDocsReply(text: string): Record<string, unknown> {\n const fenced = /```(?:json)?\\s*([\\s\\S]*?)```/i.exec(text);\n const body = fenced ? fenced[1]! : text;\n const start = body.indexOf('{');\n const end = body.lastIndexOf('}');\n if (start < 0 || end <= start) throw new Error('The reply holds no JSON object.');\n const json = JSON.parse(body.slice(start, end + 1)) as unknown;\n if (!json || typeof json !== 'object' || Array.isArray(json)) throw new Error('The reply is not a docs.json object.');\n return json as Record<string, unknown>;\n}\n\n/** One line of docs prose: em dashes out, whitespace folded, trimmed. */\nexport const cleanDocsText = (s: string): string => cleanDraftText(s.replace(/[\\r\\n]+/g, ' '));\n\nconst isExample = (x: unknown): x is DocsExampleNode => {\n if (typeof x === 'string') return true;\n if (!x || typeof x !== 'object' || Array.isArray(x)) return false;\n const n = x as { c?: unknown; p?: unknown; children?: unknown };\n if (typeof n.c !== 'string' || !n.c) return false;\n if (n.p !== undefined && (!n.p || typeof n.p !== 'object' || Array.isArray(n.p))) return false;\n return n.children === undefined || (Array.isArray(n.children) && n.children.every(isExample));\n};\n\nconst textList = (x: unknown): string[] | undefined => {\n if (typeof x === 'string') x = [x];\n if (!Array.isArray(x)) return undefined;\n const out = x.filter((s): s is string => typeof s === 'string').map(cleanDocsText).filter(Boolean);\n return out.length ? out : undefined;\n};\n\nconst guidanceList = (x: unknown, examples: boolean): DocsGuidance[] | undefined => {\n if (!Array.isArray(x)) return undefined;\n const out: DocsGuidance[] = [];\n for (const g of x as unknown[]) {\n if (!g || typeof g !== 'object') continue;\n const r = g as { title?: unknown; text?: unknown; example?: unknown };\n const title = typeof r.title === 'string' ? cleanDocsText(r.title) : '';\n const text = typeof r.text === 'string' ? cleanDocsText(r.text) : '';\n if (!title || !text) continue;\n out.push({ title, text, ...(examples && r.example !== undefined && isExample(r.example) ? { example: r.example } : {}) });\n }\n return out.length ? out : undefined;\n};\n\nexport type DocsSections = Partial<Pick<ComponentDocsJson, ProseKey>>;\n\n/**\n * The prose sections of an answer, kept to the docs.json shapes: only `keys`, summary one cleaned paragraph, lists of\n * non-empty cleaned strings, dos and donts as {title, text} (an example only when `examples` and well formed). Em\n * dashes removed everywhere. Sections that come back empty or in the wrong shape are left out.\n */\nexport function sanitizeDocsSections(raw: unknown, keys: readonly ProseKey[] = PROSE_KEYS, opts: { examples?: boolean } = {}): DocsSections {\n const out: DocsSections = {};\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;\n const r = raw as Record<string, unknown>;\n for (const k of keys) {\n const v = r[k];\n if (k === 'summary') {\n const s = typeof v === 'string' ? cleanDocsText(v) : '';\n if (s) out.summary = s;\n } else if (k === 'dos' || k === 'donts') {\n const g = guidanceList(v, opts.examples ?? false);\n if (g) out[k] = g;\n } else {\n const l = textList(v);\n if (l) out[k] = l;\n }\n }\n return out;\n}\n\n/** A rewritten passage: one cleaned paragraph without wrapping quotes, or '' when there is none. */\nexport function sanitizeDocsReplacement(raw: unknown): string {\n if (typeof raw !== 'string') return '';\n return cleanDocsText(raw.trim().replace(/^[\"'“]+|[\"'”]+$/g, ''));\n}\n\n/**\n * A task's answer. Sections tasks: `sections` drafted or fixed, and `checked`, the checked sections Claude verified and\n * left unchanged (still accurate). Selection: `replacement` only.\n */\nexport type DocsTaskAnswer = { sections: DocsSections; checked: ProseKey[]; replacement?: undefined } | { sections: DocsSections; checked?: undefined; replacement: string };\n\n/**\n * A task's answer from Claude's reply text. Sections: the requested keys, sanitized; throws when none came back.\n * Selection: `replacement` only (sections stay empty); a reply that is plain text counts as the passage.\n */\nexport function parseDocsTaskAnswer(task: DocsDraftTask, text: string): DocsTaskAnswer {\n if (task.kind === 'selection') {\n let raw: unknown = text;\n try {\n const json = parseDocsReply(text);\n raw = json.replacement ?? json.text ?? json[task.key];\n } catch {\n raw = text.replace(/```[a-z]*\\s*|```/gi, '');\n }\n const replacement = sanitizeDocsReplacement(raw);\n if (!replacement) throw new Error('Claude sent no rewritten passage. Try again.');\n return { sections: {}, replacement };\n }\n return docsSectionsAnswer(task, parseDocsReply(text));\n}\n\n/**\n * Sections and checked of a sections task from an answer object: absent checked keys are still accurate. Throws only\n * when the task checks nothing and none of its keys came back.\n */\nexport function docsSectionsAnswer(task: Extract<DocsDraftTask, { kind: 'sections' }>, raw: unknown): { sections: DocsSections; checked: ProseKey[] } {\n const check = (task.check ?? []).filter((k) => task.keys.includes(k));\n const sections = check.length ? sanitizeDocsSections(raw, task.keys) : docsSectionsResult(task, raw);\n return { sections, checked: check.filter((k) => sections[k] === undefined) };\n}\n\n/** The sections of a task from an answer object (API reply or the exchange). Throws when none of the keys came back. */\nexport function docsSectionsResult(task: Extract<DocsDraftTask, { kind: 'sections' }>, raw: unknown): DocsSections {\n const sections = sanitizeDocsSections(raw, task.keys);\n if (!Object.keys(sections).length) throw new Error(`Claude's answer holds none of the sections asked for (${task.keys.join(', ')}). Try again.`);\n return sections;\n}\n\n/**\n * Drafted sections applied to a docs.json, marked for review: the sections replace the ones there, the rest stays as\n * is (anatomy and preview are code-decided and never come from a draft), and draftedSections lists what waits.\n */\nexport function applyDocsSections<T extends Partial<ComponentDocsJson>>(docs: T, sections: DocsSections): T {\n const keys = PROSE_KEYS.filter((k) => sections[k] !== undefined);\n if (!keys.length) return docs;\n return markClaudeDraft({ ...docs, ...sections }, keys);\n}\n\n/**\n * The docs-draft Action's merge: Claude's prose on top of the pre-fill draft, only where the pre-fill is empty (a\n * written section is never overwritten), anatomy kept from the code, the drafted sections marked for review.\n */\nexport function mergeDocsDraft(prefillDraft: Partial<ComponentDocsJson>, reply: Record<string, unknown>): Partial<ComponentDocsJson> {\n const empty = PROSE_KEYS.filter((k) => {\n const v = prefillDraft[k];\n return v === undefined || (typeof v === 'string' ? !v.trim() : Array.isArray(v) && !v.length);\n });\n const sections = sanitizeDocsSections(reply, empty, { examples: true });\n const merged: Partial<ComponentDocsJson> = { ...prefillDraft, ...sections };\n if (reply.preview && !prefillDraft.preview && isExample(reply.preview)) merged.preview = reply.preview;\n merged.anatomy = prefillDraft.anatomy;\n const drafted = PROSE_KEYS.filter((k) => sections[k] !== undefined);\n return markClaudeDraft(merged, drafted.length && drafted.length < PROSE_KEYS.length ? drafted : undefined);\n}\n\n// ---------------------------------------------------------------------------------------------\n// The Messages API call (raw HTTP: no SDK dependency for one call)\n\nexport interface AnthropicHttpRequest {\n url: string;\n init: { method: 'POST'; headers: Record<string, string>; body: string };\n}\n\nexport interface AnthropicRequestInput {\n apiKey: string;\n prompt: string;\n model?: string | undefined;\n system?: string | undefined;\n maxTokens?: number | undefined;\n /** A direct call from a browser page (the user's own key): adds the header the API asks for. */\n browser?: boolean | undefined;\n /** Re-run a declined request on a fallback model inside the same call (server-side fallback beta). */\n fallback?: boolean | undefined;\n}\n\n/** The Messages API request for one prompt. The key goes in x-api-key, to api.anthropic.com only. */\nexport function anthropicRequest(input: AnthropicRequestInput): AnthropicHttpRequest {\n const headers: Record<string, string> = { 'x-api-key': input.apiKey, 'anthropic-version': '2023-06-01', 'content-type': 'application/json' };\n if (input.fallback) headers['anthropic-beta'] = 'server-side-fallback-2026-07-01';\n if (input.browser) headers['anthropic-dangerous-direct-browser-access'] = 'true';\n const body: Record<string, unknown> = {\n model: input.model || DOCS_DRAFT_MODEL,\n max_tokens: input.maxTokens ?? 16000,\n ...(input.fallback ? { fallbacks: 'default' } : {}),\n ...(input.system ? { system: input.system } : {}),\n messages: [{ role: 'user', content: input.prompt }],\n };\n return { url: ANTHROPIC_MESSAGES_URL, init: { method: 'POST', headers, body: JSON.stringify(body) } };\n}\n\n/** The text of a Messages API reply. Throws when Claude declined or the reply was cut off. */\nexport function anthropicReplyText(msg: unknown): string {\n const m = (msg ?? {}) as { stop_reason?: string; content?: { type?: string; text?: unknown }[] };\n if (m.stop_reason === 'refusal') throw new Error('Claude declined to draft this one.');\n if (m.stop_reason === 'max_tokens') throw new Error('The reply was cut off (max_tokens).');\n return (m.content ?? [])\n .filter((b) => b?.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text as string)\n .join('');\n}\n","// Explorations: try experimental variables and components in a real product staging branch without touching main.\n// An exploration is a branch named `explore/<slug>` with an open DRAFT pull request labeled `exploration`. It holds\n// token edits and component work (requests filed with `exploration: explore/<slug>` are implemented there). Every\n// exploration gets the per-branch previews (bridge.config.json previews.apps) and a snapshot of the packages a product\n// staging branch installs (.github/workflows/preview-packages.yml). It is never merged as is: when the idea is\n// validated it is promoted to a normal pull request for review, otherwise it is closed. The CI check \"Exploration not\n// merged as is\" fails while the label is on, so an exploration cannot be merged by accident.\n//\n// Pure: branch naming, the draft pull request body, status and the promotion plan. Shared by Studio, the MCP server\n// and the CLI, so an exploration reads the same everywhere. GitHub calls live in explorations-github.ts.\n\nimport type { BridgeConfig } from './config';\nimport { slugify } from './pr-composer';\nimport { previewLinks, readPreviewComment, type PreviewApps } from './previews';\nimport { classifyRisk, type ChangedFile, type RiskTier } from './risk';\n\n/** Every exploration pull request carries this label while it is an exploration. */\nexport const EXPLORATION_LABEL = 'exploration';\n/** Exploration branches start with it. */\nexport const EXPLORATION_PREFIX = 'explore/';\n/** Where the note that starts an exploration branch lives. Promotion removes it, so main never gets it. */\nexport const EXPLORATION_NOTES_DIR = '.bridge/explorations';\n/** What Studio shows instead of a risk tier while the pull request is an exploration. */\nexport const EXPLORATION_TIER_LABEL = 'Exploration (not mergeable)';\n/** Name of the CI job that fails while the label is on. */\nexport const EXPLORATION_CHECK = 'Exploration not merged as is';\n\nexport type ExplorationUseCase = 'user-test' | 'stakeholder-demo' | 'ab-idea' | 'terminal' | 'other';\nexport type ExplorationStatus = 'active' | 'promoted' | 'closed';\n/** Where an exploration was started: Bridge Studio, the Figma plugin, the CLI or the MCP server (an AI agent). */\nexport type ExplorationSource = 'studio' | 'figma' | 'cli' | 'mcp';\n\nexport const EXPLORATION_USE_CASES: { value: ExplorationUseCase; label: string; hint: string }[] = [\n { value: 'user-test', label: 'Prototype for a user test', hint: 'A coded prototype on a product staging branch, with the real components and tokens.' },\n { value: 'stakeholder-demo', label: 'Stakeholder demo', hint: 'Show an idea on real screens before anyone commits to it.' },\n { value: 'ab-idea', label: 'A/B idea', hint: 'Ship a variant to a staging or experiment branch and compare it with what is live.' },\n { value: 'terminal', label: 'Exploring with Claude Code', hint: 'A designer works from the terminal with Claude and the Bridge MCP server on this branch, never on main.' },\n { value: 'other', label: 'Other', hint: 'Anything else worth trying before it becomes a change.' },\n];\n\nexport const EXPLORATION_STATUS_LABEL: Record<ExplorationStatus, string> = { active: 'Running', promoted: 'Promoted to review', closed: 'Closed' };\n\nexport interface Exploration {\n /** Display name, sentence case: \"Denser data tables\". */\n name: string;\n /** What the team wants to learn, in one or two sentences. */\n purpose: string;\n /** Branch slug: `explore/<slug>`. Derived from the name when missing. */\n slug?: string | undefined;\n useCase?: ExplorationUseCase | undefined;\n /** What is experimental, one line each: \"color.action.primary.bg\", \"Button: pill radius\". */\n experimental?: string[] | undefined;\n /** GitHub login of who started it, when known. */\n author?: string | undefined;\n /** ISO date it started. */\n startedAt?: string | undefined;\n /** Where it was started, so Studio says \"You\" only for what the viewer started there. */\n source?: ExplorationSource | undefined;\n /** The AI agent that started it (\"claude\"), when one did: the GitHub account alone cannot tell. */\n agent?: string | undefined;\n /** A Jira ticket key (\"DS-42\"), first in the pull request title so Jira's GitHub integration links it. */\n jira?: string | undefined;\n}\n\nconst MARK = 'bridge-exploration';\nconst SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n/** \"Denser data tables!\" -> \"denser-data-tables\". Up to 40 characters, cut at a word boundary. Empty when nothing is left. */\nexport function explorationSlug(name: string): string {\n const s = name.trim().replace(/^explore\\//i, '');\n if (!/[a-z0-9]/i.test(s)) return '';\n return slugify(s, 40);\n}\n\n/** `explore/<slug>` for a name, a slug or a branch name. */\nexport function explorationBranch(nameOrBranch: string): string {\n return `${EXPLORATION_PREFIX}${explorationSlug(nameOrBranch)}`;\n}\n\n/** True for `explore/<valid-slug>`. */\nexport function isExplorationBranch(ref: string | null | undefined): boolean {\n const r = (ref ?? '').replace(/^refs\\/heads\\//, '');\n return r.startsWith(EXPLORATION_PREFIX) && SLUG_RE.test(r.slice(EXPLORATION_PREFIX.length));\n}\n\n/** The slug of an exploration branch, or null. */\nexport function explorationSlugFromBranch(ref: string): string | null {\n return isExplorationBranch(ref) ? ref.replace(/^refs\\/heads\\//, '').slice(EXPLORATION_PREFIX.length) : null;\n}\n\n/** Path of the note that starts an exploration branch. */\nexport const explorationNotePath = (slug: string) => `${EXPLORATION_NOTES_DIR}/${slug}.md`;\n\n/** Problems with a new exploration, as sentences that say how to fix them. Empty when it can start. */\nexport function explorationProblems(e: Pick<Exploration, 'name' | 'purpose'> & { slug?: string | undefined }): string[] {\n const out: string[] = [];\n const name = e.name.trim();\n const slug = e.slug?.trim() || explorationSlug(name);\n if (!name) out.push('Name the exploration, for example \"Denser data tables\".');\n else if (name.length > 60) out.push('Keep the name under 60 characters: it becomes the branch name.');\n else if (slug.length < 2 || !SLUG_RE.test(slug)) out.push('Use letters or digits in the name: it becomes the branch explore/<name>.');\n if (!e.purpose.trim()) out.push('Say what you want to learn, in one sentence.');\n return out;\n}\n\nconst useCaseLabel = (u: ExplorationUseCase | undefined) => EXPLORATION_USE_CASES.find((x) => x.value === u)?.label;\n\n/** The note committed as the first commit of the branch (`.bridge/explorations/<slug>.md`). */\nexport function explorationNote(e: Exploration): string {\n const slug = e.slug || explorationSlug(e.name);\n const uc = useCaseLabel(e.useCase);\n return [\n `# Exploration: ${e.name.trim()}`,\n '',\n e.purpose.trim(),\n '',\n `- Branch: \\`${EXPLORATION_PREFIX}${slug}\\``,\n ...(uc ? [`- Use case: ${uc}`] : []),\n ...(e.startedAt ? [`- Started: ${e.startedAt.slice(0, 10)}${e.author ? ` by @${e.author}` : ''}`] : []),\n '',\n 'This file marks the branch as an exploration. It is never merged as is: promoting the pull request to review removes it.',\n '',\n ].join('\\n');\n}\n\nexport interface ExplorationPrContext {\n owner: string;\n repo: string;\n /** Unknown before the pull request exists: the install section then says where the command will appear. */\n pr?: number | undefined;\n packages: string[];\n apps: PreviewApps;\n /** Requests implemented on this exploration. */\n requests?: { number: number; title: string }[] | undefined;\n}\n\n/** Draft pull request title: \"Exploration: denser data tables\". */\nexport function explorationPrTitle(e: Pick<Exploration, 'name'>): string {\n const n = e.name.trim().replace(/\\.$/, '');\n return `Exploration: ${n.charAt(0).toLowerCase()}${n.slice(1)}`;\n}\n\n/**\n * The draft pull request body: purpose, what is experimental, how a product staging branch installs it, the\n * previews, and how to promote or close it. Markdown for people plus one hidden JSON block for tools.\n */\nexport function explorationPrBody(e: Exploration, ctx: ExplorationPrContext): string {\n const slug = e.slug || explorationSlug(e.name);\n const branch = `${EXPLORATION_PREFIX}${slug}`;\n const uc = useCaseLabel(e.useCase);\n const experimental = (e.experimental ?? []).map((x) => x.trim()).filter(Boolean);\n const lines = [\n `## Exploration: ${e.name.trim()}`,\n '',\n `> Not mergeable as is. This draft pull request is a sandbox on \\`${branch}\\`: promote it to a normal review when the idea is validated, or close it.`,\n '',\n `**Purpose.** ${e.purpose.trim()}`,\n ...(uc ? ['', `**Use case.** ${uc}`] : []),\n '',\n '### What is experimental',\n '',\n ...(experimental.length ? experimental.map((x) => `- ${x}`) : ['- Token edits and component work committed to this branch. Nothing here reaches main or production.']),\n ...(ctx.requests?.length ? ['', 'Requests implemented here:', ...ctx.requests.map((r) => `- #${r.number} ${r.title}`)] : []),\n '',\n '### Try it in a product staging branch',\n '',\n ];\n // No guessed command here: pkg.pr.new may not be set up. The sticky comment has the one the workflow published.\n lines.push(\n 'In the product repo, on a branch that deploys to staging (production keeps the released version), install the snapshot with the command in the \"Try this exploration in your product\" comment below. It appears a few minutes after each push and always matches the latest commit.',\n );\n lines.push('', '### Previews', '');\n const links = previewLinks(ctx.apps, { branch, ...(ctx.pr ? { pr: ctx.pr } : {}) });\n if (links.length) lines.push('| App | Preview |', '| --- | --- |', ...links.map((l) => `| ${l.label} | ${l.url} |`));\n else lines.push('Preview deploys are not set up: add `previews.apps` to `bridge.config.json` (docs/PREVIEWS.md).');\n lines.push(\n '',\n '### When it is done',\n '',\n `- **Promote:** in Bridge Studio (Changes, Explorations, Promote to review) or \\`bridge explore promote ${slug}\\`. Bridge marks the pull request ready for review, removes the \\`${EXPLORATION_LABEL}\\` label and the exploration note, and adds the tier labels. Then it goes through the usual review.`,\n '- **Close:** close this pull request. The branch stays for reference; the preview prerelease is removed.',\n '',\n `<!-- ${MARK} ${JSON.stringify({ name: e.name.trim(), purpose: e.purpose.trim(), slug, ...(e.useCase ? { useCase: e.useCase } : {}), ...(experimental.length ? { experimental } : {}), ...(e.author ? { author: e.author } : {}), ...(e.startedAt ? { startedAt: e.startedAt } : {}), ...(e.source ? { source: e.source } : {}), ...(e.agent ? { agent: e.agent } : {}) }).replace(/-->/g, '--\\\\u003e')} -->`,\n );\n return lines.join('\\n');\n}\n\n/** The exploration inside a pull request body, or undefined when it has no valid Bridge block. */\nexport function parseExplorationBody(body: string | null | undefined): Exploration | undefined {\n if (!body) return undefined;\n const m = new RegExp(`<!-- ${MARK} (\\\\{[\\\\s\\\\S]*?\\\\}) -->`).exec(body);\n if (!m) return undefined;\n try {\n const e = JSON.parse(m[1]!) as Exploration;\n return e && typeof e.name === 'string' && typeof e.purpose === 'string' ? e : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport interface ExplorationPullLike {\n state: string;\n merged?: boolean | undefined;\n merged_at?: string | null | undefined;\n labels: (string | { name?: string })[];\n headRef?: string | undefined;\n body?: string | null | undefined;\n}\n\nconst labelNames = (labels: ExplorationPullLike['labels']) => labels.map((l) => (typeof l === 'string' ? l : (l.name ?? '')));\n\n/** True for a pull request that is or was an exploration: an `explore/*` branch, the label, or the Bridge block. */\nexport function isExplorationPull(p: ExplorationPullLike): boolean {\n return isExplorationBranch(p.headRef) || labelNames(p.labels).includes(EXPLORATION_LABEL) || Boolean(parseExplorationBody(p.body));\n}\n\n/**\n * Where an exploration stands: closed without merging = closed; open with the `exploration` label = active\n * (running); otherwise promoted (the label was removed, so it is a normal pull request now, open or merged).\n */\nexport function explorationStatus(p: ExplorationPullLike): ExplorationStatus {\n const merged = Boolean(p.merged || p.merged_at || p.state === 'merged');\n if (p.state !== 'open' && !merged) return 'closed';\n if (p.state === 'open' && labelNames(p.labels).includes(EXPLORATION_LABEL)) return 'active';\n return 'promoted';\n}\n\n/** True while the label is on: the pull request must not merge (the CI check fails, Studio blocks the merge). */\nexport const isActiveExploration = (labels: ExplorationPullLike['labels']) => labelNames(labels).includes(EXPLORATION_LABEL);\n\nexport interface PromotionPlan {\n tier: RiskTier;\n reasons: string[];\n /** Labels to remove (the exploration label). */\n removeLabels: string[];\n /** Tier labels from the shared classifier. */\n addLabels: string[];\n /** Files to delete on the branch before review: the exploration note. */\n removeFiles: string[];\n /** The pull request body for review. */\n body: string;\n /** Title without the \"Exploration:\" prefix. */\n title: string;\n markReady: true;\n}\n\n/**\n * What promoting an exploration does: the tier from the files it changes (the shared classifier, the exploration\n * note left out since promotion deletes it), tier labels, the exploration label removed, a review body that keeps\n * the purpose and closes the requests implemented on it, and the draft marked ready for review.\n */\nexport function promotionPlan(input: {\n title: string;\n body: string | null | undefined;\n labels: ExplorationPullLike['labels'];\n files: ChangedFile[];\n config?: BridgeConfig | undefined;\n /** Request issues implemented on this exploration: the review body closes them. */\n requests?: number[] | undefined;\n date?: Date | undefined;\n}): PromotionPlan {\n const exploration = parseExplorationBody(input.body);\n // A Jira key first in the title (\"DS-42 Exploration: pill buttons\") stays first after promotion.\n const jira = /^([A-Z][A-Z0-9_]*-\\d+)\\s+/.exec(input.title)?.[1] ?? null;\n const title = jira ? input.title.slice(jira.length).trim() : input.title;\n const removeFiles = input.files.filter((f) => f.path.startsWith(`${EXPLORATION_NOTES_DIR}/`) && f.status !== 'removed').map((f) => f.path);\n const files = input.files.filter((f) => !f.path.startsWith(`${EXPLORATION_NOTES_DIR}/`));\n const risk = classifyRisk({ files, ...(input.config ? { config: input.config } : {}) });\n const tokens = files.some((f) => f.path.endsWith('.tokens.json'));\n const addLabels = [`tier: ${risk.tier}`, ...(risk.tier === 3 && tokens ? ['tokens'] : [])];\n const date = (input.date ?? new Date()).toISOString().slice(0, 10);\n const existing = new Set(input.body ? [...input.body.matchAll(/\\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\\s+#(\\d+)/gi)].map((m) => Number(m[1])) : []);\n const closes = [...new Set(input.requests ?? [])].filter((n) => !existing.has(n));\n const kept = (input.body ?? '')\n // The sandbox warning and the promote/close instructions no longer apply.\n .replace(/^> Not mergeable as is\\..*$\\n?\\n?/m, '')\n .replace(/### When it is done[\\s\\S]*?(?=<!-- |$)/, '')\n .replace(/^## Exploration: /m, '## ')\n .trim();\n const body = [\n `**Promoted from an exploration on ${date}.** Review it like any change: the tier below comes from the files it touches.`,\n '',\n kept || `## ${title.replace(/^Exploration:\\s*/i, '')}`,\n '',\n `**Risk tier:** ${risk.tier}.`,\n ...risk.reasons.slice(0, 8).map((r) => `- ${r}`),\n ...(closes.length ? ['', ...closes.map((n) => `Closes #${n}`)] : []),\n ].join('\\n');\n const t = title.replace(/^Exploration:\\s*/i, '').trim() || exploration?.name || title;\n return {\n tier: risk.tier,\n reasons: risk.reasons,\n removeLabels: [EXPLORATION_LABEL],\n addLabels,\n removeFiles,\n body,\n title: `${jira ? `${jira} ` : ''}${t.charAt(0).toUpperCase()}${t.slice(1)}`,\n markReady: true,\n };\n}\n\n/** Where the test build of an exploration stands, from its sticky preview comment and the branch head. */\nexport type ExplorationTryIt =\n | { state: 'ready'; command: string; source: 'pkg.pr.new' | 'release' | 'other'; sha7: string | null }\n | { state: 'building' }\n | { state: 'failed' };\n\n/**\n * The install command a product staging branch can trust, read from the `<!-- bridge-branch-preview -->` comment,\n * never guessed: no comment yet, or a comment about an older commit than the head, means the snapshot is still\n * building; a comment without a command means the publish failed.\n */\nexport function explorationTryIt(input: { comment?: string | null | undefined; headSha?: string | null | undefined }): ExplorationTryIt {\n const c = readPreviewComment(input.comment);\n if (!c) return { state: 'building' };\n if (input.headSha && c.sha7 && !input.headSha.startsWith(c.sha7)) return { state: 'building' };\n if (!c.command || c.source === 'none') return { state: 'failed' };\n return { state: 'ready', command: c.command, source: c.source, sha7: c.sha7 };\n}\n\n/**\n * The message a designer sends a developer: what the exploration is, the install command for a product staging\n * branch, the previews and the pull request. Plain text, one paragraph, ready to paste in a chat.\n */\nexport function explorationShareMessage(input: { name: string; branch: string; url: string; command?: string | null | undefined; previews?: { label: string; url: string }[] | undefined }): string {\n const name = input.name.trim().replace(/\"/g, \"'\");\n const head = input.command\n ? `Exploration \"${name}\" (${input.branch}): try it in a staging branch of your product with: ${input.command}.`\n : `Exploration \"${name}\" (${input.branch}): its test build is being prepared, the install command for a staging branch of your product will be on the pull request in a few minutes.`;\n const previews = (input.previews ?? []).map((p) => `${p.label} ${p.url}`);\n return [head, previews.length ? `Previews: ${previews.join(', ')}.` : '', `Pull request: ${input.url}.`].filter(Boolean).join(' ');\n}\n\n/**\n * The rules Claude follows on an exploration branch (request briefs, docs drafts, token edits with a target branch):\n * work there, never on main, and never open a pull request to main: the exploration's draft pull request is the place.\n */\nexport function explorationRules(branch: string): string[] {\n return [\n `- Work on the existing branch ${branch} (git fetch origin && git switch ${branch}). Commit there.`,\n `- Do not open a pull request to main and do not create another branch: the draft pull request of ${branch} is the place. It is promoted to review only when the idea is validated.`,\n '- Do not mark the pull request ready for review and do not remove the exploration label: promoting is a person\\'s decision.',\n ];\n}\n","// Component change requests: a designer asks for a new component or a change to a coded one (variant, prop, structure,\n// visual, token binding, bug) from Figma or Studio. Variable edits never become requests: they are pull requests\n// people approve (tokens are data). Components need code, so they become requests. Code stays the source of truth, so a request never rewrites React: it lands as\n// a GitHub issue that people (or Claude, through the MCP server or the CLI) implement in a pull request that closes it.\n// Shared by the Figma plugin, Studio, the MCP server, the CLI and the Jira Action, so a request reads the same\n// everywhere. The issue body is plain Markdown for people plus one hidden JSON block for tools.\n\nimport { EXPLORATION_LABEL, explorationRules } from './explorations';\n\nexport type RequestKind = 'new-component' | 'new-variant' | 'prop-change' | 'structure' | 'visual' | 'token-binding' | 'bug' | 'other';\nexport type RequestSource = 'figma' | 'studio' | 'cli' | 'mcp';\nexport type RequestStatus = 'requested' | 'in-progress' | 'done' | 'declined';\n\nexport const REQUEST_KINDS: { value: RequestKind; label: string; hint: string }[] = [\n { value: 'new-component', label: 'New component', hint: 'A component the design system does not have yet.' },\n { value: 'new-variant', label: 'New variant', hint: 'A size, tone or state the component does not have yet.' },\n { value: 'prop-change', label: 'Option change (prop)', hint: 'Add, rename or change an option (a prop in code) or its default.' },\n { value: 'structure', label: 'Structure change', hint: 'A part was added, removed or moved.' },\n { value: 'visual', label: 'Visual change', hint: 'Spacing, radius, layout or icon placement.' },\n { value: 'token-binding', label: 'Token change', hint: 'The component should paint with another token.' },\n { value: 'bug', label: 'Bug', hint: 'It looks or behaves differently from the guidance.' },\n { value: 'other', label: 'Other', hint: 'Anything else.' },\n];\n\n/** Every request issue carries this label; tools list requests by it. */\nexport const REQUEST_LABEL = 'component-change';\n\nexport interface RequestChange {\n /** What changes: a prop, a variant axis, a token, a part (\"radius\", \"size\", \"color.action.primary.bg\"). */\n field: string;\n before?: string | undefined;\n after?: string | undefined;\n}\n\nexport interface ComponentChangeRequest {\n /** Component name as exported (\"Button\"), or the proposed name of a new component. */\n component: string;\n kind: RequestKind;\n /** One line, sentence case: \"Add a danger ghost variant\". */\n title: string;\n /** What and why, in the requester's words. */\n summary: string;\n /**\n * What changed for developers in one sentence (\"Icon added after the label in primary sm: Pencil, 16px\"): written\n * by Claude from the before and after images, or drafted from the detected changes. Optional.\n */\n line?: string | undefined;\n changes: RequestChange[];\n /** Where the design lives, when it comes from Figma. */\n figma?: { fileKey?: string | undefined; nodeId?: string | undefined; nodeName?: string | undefined; url?: string | undefined } | undefined;\n /** Image URLs (Figma exports committed to the requests branch, or links). */\n images?: string[] | undefined;\n source: RequestSource;\n /** GitHub login, when known. */\n requestedBy?: string | undefined;\n /**\n * Exploration branch (`explore/<slug>`) to implement it on instead of a pull request to main. The issue gets the\n * `exploration` label and the brief says to work on that branch (docs/EXPLORATIONS.md).\n */\n exploration?: string | undefined;\n}\n\nexport interface RequestIssue {\n title: string;\n body: string;\n labels: string[];\n assignees: string[];\n}\n\nconst MARK = 'bridge-request';\nconst kindLabel = (k: RequestKind) => REQUEST_KINDS.find((x) => x.value === k)?.label ?? 'Other';\nconst kindSlug = (k: RequestKind) => `request: ${k}`;\n\n/** Issue title: \"Button: add a danger ghost variant\". */\nexport function requestIssueTitle(r: Pick<ComponentChangeRequest, 'component' | 'title'>): string {\n const t = r.title.trim().replace(/\\.$/, '');\n return `${r.component}: ${t.charAt(0).toLowerCase()}${t.slice(1)}`;\n}\n\n/** The GitHub issue for a request: readable Markdown, the labels tools filter on, and a hidden JSON block. */\nexport function composeRequestIssue(r: ComponentChangeRequest, opts: { labels?: string[]; assignees?: string[]; componentUrl?: string } = {}): RequestIssue {\n const rows = r.changes.length\n ? ['| What | Now | Requested |', '| --- | --- | --- |', ...r.changes.map((c) => `| ${cell(c.field)} | ${cell(c.before ?? '')} | ${cell(c.after ?? '')} |`)]\n : [];\n const figma = r.figma?.url ? `[${r.figma.nodeName ?? 'Open in Figma'}](${r.figma.url})` : r.figma?.nodeName ? r.figma.nodeName : '';\n const body = [\n r.kind === 'new-component' ? `## New component request: ${r.component}` : `## ${kindLabel(r.kind)} request for ${r.component}`,\n '',\n r.summary.trim(),\n '',\n ...(r.line?.trim() ? [`**What changes:** ${r.line.trim()}`, ''] : []),\n ...(rows.length ? [...rows, ''] : []),\n ...(r.images?.length ? [...r.images.map((u, i) => `![${r.component} design ${i + 1}](${u})`), ''] : []),\n ...(figma ? [`**Design:** ${figma}`, ''] : []),\n ...(opts.componentUrl ? [`**Component:** ${opts.componentUrl}`, ''] : []),\n ...(r.exploration ? [`**Exploration:** \\`${r.exploration}\\`. Implement it on that branch, not in a pull request to main: it ships to product staging as a snapshot and is promoted to review only when the idea is validated.`, ''] : []),\n '## How to implement',\n '',\n r.exploration\n ? `Commit the change to \\`${r.exploration}\\` (its draft pull request is the place). With Claude: \\`bridge request implement <number>\\` (CLI) or the \\`bridge_get_request\\` MCP tool. Promoting the exploration closes this request when it merges.`\n : `Code is the source of truth: change the component in a pull request that says \\`Closes #<this issue>\\`, so this request closes when it merges. With Claude: \\`bridge request implement <number>\\` (CLI) or the \\`bridge_get_request\\` MCP tool.`,\n '',\n `<sub>Requested from ${sourceLabel(r.source)}${r.requestedBy ? ` by @${r.requestedBy}` : ''} with Bridge.</sub>`,\n '',\n `<!-- ${MARK} ${JSON.stringify(r)} -->`,\n ].join('\\n');\n const labels = [...new Set([REQUEST_LABEL, kindSlug(r.kind), `source: ${r.source}`, ...(r.exploration ? [EXPLORATION_LABEL] : []), ...(opts.labels ?? [])])];\n return { title: requestIssueTitle(r), body, labels, assignees: opts.assignees ?? [] };\n}\n\n/** The request inside an issue body, or undefined when the body has no valid Bridge block. */\nexport function parseRequestIssue(body: string | null | undefined): ComponentChangeRequest | undefined {\n if (!body) return undefined;\n const m = new RegExp(`<!-- ${MARK} (\\\\{[\\\\s\\\\S]*?\\\\}) -->`).exec(body);\n if (!m) return undefined;\n try {\n const r = JSON.parse(m[1]!) as ComponentChangeRequest;\n return r && typeof r.component === 'string' && typeof r.title === 'string' ? { ...r, changes: Array.isArray(r.changes) ? r.changes : [] } : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The issue body with the request linked to an exploration branch: the hidden block gets `exploration` (what the\n * Explorations view, the MCP server and the CLI read) and the readable part says where to implement it. The rest of the\n * body stays as people wrote it. Undefined when the body has no Bridge block (nothing to link).\n */\nexport function withRequestExploration(body: string | null | undefined, branch: string): string | undefined {\n const r = parseRequestIssue(body);\n if (!r || !body) return undefined;\n const block = new RegExp(`<!-- ${MARK} \\\\{[\\\\s\\\\S]*?\\\\} -->`);\n let out = body.replace(block, () => `<!-- ${MARK} ${JSON.stringify({ ...r, exploration: branch })} -->`);\n const line = `**Exploration:** \\`${branch}\\`. Implement it on that branch, not in a pull request to main: it ships to product staging as a snapshot and is promoted to review only when the idea is validated.`;\n if (/^\\*\\*Exploration:\\*\\* .*$/m.test(out)) out = out.replace(/^\\*\\*Exploration:\\*\\* .*$/m, () => line);\n else if (out.includes('\\n## How to implement')) out = out.replace('\\n## How to implement', () => `\\n${line}\\n\\n## How to implement`);\n else out = out.replace(block, (m) => `${line}\\n\\n${m}`);\n return out;\n}\n\n/** Problems with a decline reason, as sentences that say how to fix them. */\nexport function declineReasonProblems(reason: string): string[] {\n const r = reason.trim();\n if (!r) return ['Say why, in one or two sentences: the requester reads it.'];\n if (r.length < 10) return ['Say a bit more, so the requester knows why: at least 10 characters.'];\n return [];\n}\n\n/** The comment posted on a declined request: who declined it and why, in the decliner's words. */\nexport function declineComment(reason: string, by?: string | null): string {\n const quote = reason\n .trim()\n .split('\\n')\n .map((l) => `> ${l}`.trimEnd())\n .join('\\n');\n return [`Declined${by ? ` by @${by.replace(/^@/, '')}` : ''} in Bridge Studio.`, '', quote, '', '<sub>Closed as not planned. Reopen the issue if things change.</sub>'].join('\\n');\n}\n\n/**\n * Where a request stands: open with no linked pull request = requested; open with an open linked pull request =\n * in progress; closed as completed or by a merged pull request = done; closed otherwise = declined.\n */\nexport function requestStatus(issue: { state: 'open' | 'closed'; stateReason?: string | null | undefined; linkedPrs?: { state: 'open' | 'closed'; merged?: boolean }[] }): RequestStatus {\n const prs = issue.linkedPrs ?? [];\n if (issue.state === 'open') return prs.some((p) => p.state === 'open') ? 'in-progress' : 'requested';\n if (prs.some((p) => p.merged) || issue.stateReason === 'completed') return 'done';\n return 'declined';\n}\n\nexport const REQUEST_STATUS_LABEL: Record<RequestStatus, string> = { requested: 'Requested', 'in-progress': 'In progress', done: 'Done', declined: 'Declined' };\n\n/** Issue numbers a pull request body closes (\"Closes #42\", \"fixes #7\", \"resolves #3\"). */\nexport function closingIssueNumbers(body: string | null | undefined): number[] {\n const out = new Set<number>();\n for (const m of (body ?? '').matchAll(/\\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\\s+#(\\d+)/gi)) out.add(Number(m[1]));\n return [...out];\n}\n\n/** Path of a Figma image attached to a request, on the requests branch. */\nexport const REQUESTS_BRANCH = 'bridge-requests';\nexport function requestImagePath(component: string, date: Date): string {\n const slug = component.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'component';\n return `.bridge/requests/${slug}-${date.toISOString().replace(/[-:]/g, '').replace(/\\..*$/, '')}.png`;\n}\n\n/**\n * The brief Claude gets to implement a request (CLI `bridge request implement`, MCP `bridge_get_request`): the request,\n * the component's files, the repo rules, and how to open the pull request so it closes the issue.\n */\nexport function requestBrief(r: ComponentChangeRequest, ctx: { issue: number; issueUrl?: string; files?: string[]; agentsFile?: string; exploration?: string | undefined }): string {\n const exploration = ctx.exploration ?? r.exploration;\n return [\n `Implement Bridge component change request #${ctx.issue}${ctx.issueUrl ? ` (${ctx.issueUrl})` : ''}.`,\n '',\n `Component: ${r.component}`,\n `Kind: ${kindLabel(r.kind)}`,\n `Request: ${r.title}`,\n ...(r.line?.trim() ? [`What changes: ${r.line.trim()}`] : []),\n '',\n r.summary.trim(),\n '',\n ...(r.changes.length ? ['Changes asked:', ...r.changes.map((c) => `- ${c.field}: ${c.before ?? '(none)'} -> ${c.after ?? '(removed)'}`), ''] : []),\n ...(r.figma?.url ? [`Design: ${r.figma.url}`, ''] : []),\n ...(r.images?.length ? ['Images:', ...r.images.map((u) => `- ${u}`), ''] : []),\n ...(ctx.files?.length ? ['Files of this component:', ...ctx.files.map((f) => `- ${f}`), ''] : []),\n 'Rules:',\n `- Follow ${ctx.agentsFile ?? 'AGENTS.md'}: tokens only in component CSS, Base UI for behavior, states, tests, story, docs.json, changeset.`,\n '- A new component, prop or variant is Tier 2: open the pull request as a draft (new component: follow the new component checklist). A token add or rename is Tier 3: describe it, do not invent values.',\n ...(exploration\n ? [`- This request is part of the exploration ${exploration}.`, ...explorationRules(exploration), `- Reference the request in the commit message (\"Refs #${ctx.issue}\"). Promoting the exploration closes it.`]\n : [`- Work on a branch named agent/request-${ctx.issue}. The pull request body must contain \"Closes #${ctx.issue}\".`]),\n '- If the request is unclear or conflicts with the guidance, comment on the issue instead of guessing.',\n ].join('\\n');\n}\n\nconst cell = (s: string) => s.replace(/\\|/g, '\\\\|').replace(/\\n/g, ' ');\nconst sourceLabel = (s: RequestSource) => (s === 'figma' ? 'Figma' : s === 'studio' ? 'Bridge Studio' : s === 'cli' ? 'the CLI' : 'Claude (MCP)');\n\n// ---------------------------------------------------------------------------------------------\n// Integrations (bridge.config.json \"integrations\"): where requests go besides the GitHub issue.\n\nexport interface JiraIntegration {\n /** Jira site, e.g. \"https://acme.atlassian.net\". The token lives in the repo secrets, never in config. */\n baseUrl: string;\n /** Project key, e.g. \"DS\". */\n project: string;\n /** Issue type, default \"Task\". */\n issueType?: string | undefined;\n labels?: string[] | undefined;\n}\n\nexport interface IntegrationsConfig {\n requests?: { labels?: string[] | undefined; assignees?: string[] | undefined } | undefined;\n /** Mirror each request to Jira through the bridge-jira GitHub Action. */\n jira?: JiraIntegration | undefined;\n}\n\n/** Problems in an integrations block, as sentences that say how to fix them. Empty when valid. */\nexport function validateIntegrations(i: IntegrationsConfig | undefined): string[] {\n const out: string[] = [];\n if (!i?.jira) return out;\n if (!/^https:\\/\\/[^/]+/.test(i.jira.baseUrl ?? '')) out.push('Jira site must start with https://, for example https://acme.atlassian.net.');\n if (!/^[A-Z][A-Z0-9_]{1,9}$/.test(i.jira.project ?? '')) out.push('Jira project key is 2 to 10 capital letters or digits, like DS.');\n return out;\n}\n\n/** The Jira issue fields the Action sends for a request (Jira Cloud REST v3, Atlassian document format). */\nexport function jiraIssueFields(r: ComponentChangeRequest, jira: JiraIntegration, issueUrl: string): Record<string, unknown> {\n const text = (t: string) => ({ type: 'text', text: t });\n const para = (...c: unknown[]) => ({ type: 'paragraph', content: c });\n return {\n project: { key: jira.project },\n issuetype: { name: jira.issueType ?? 'Task' },\n summary: requestIssueTitle(r),\n labels: [...new Set(['bridge', REQUEST_LABEL, ...(jira.labels ?? [])])].map((l) => l.replace(/\\s+/g, '-')),\n description: {\n type: 'doc',\n version: 1,\n content: [\n para(text(r.summary.trim() || r.title)),\n ...(r.line?.trim() ? [para(text(r.line.trim()))] : []),\n ...r.changes.map((c) => para(text(`${c.field}: ${c.before ?? '(none)'} -> ${c.after ?? '(removed)'}`))),\n para({ type: 'text', text: 'GitHub request', marks: [{ type: 'link', attrs: { href: issueUrl } }] }),\n ],\n },\n };\n}\n","// Draft exchange: designers draft their change texts with their own Claude (Claude Desktop or Claude Code on their own\n// plan) through the Bridge MCP server, from the DS Bridge Figma plugin. Third-party apps cannot use a Claude plan, and\n// Bridge has no backend, so the channel is the GitHub repo both already reach with the designer's own token:\n//\n// 1. The plugin writes `.bridge/drafts/<sessionId>.json` (status \"pending\") on the requests branch, with the detected\n// changes, the deterministic draft and links to before and after PNGs uploaded next to it.\n// 2. The designer tells their Claude \"Draft my Bridge changes\". The MCP tool bridge_pending_drafts returns the pending\n// items (and the images, so Claude can see them), bridge_write_drafts writes the results back (status \"drafted\").\n// 3. The plugin polls the file, fills the fields it may fill, then deletes the file once the request or push is sent\n// (or cancelled).\n//\n// Bridge Studio uses the same exchange for component docs (a \"docs\" item, from the Library page): the item carries the\n// task (which prose sections, or a selected passage) and the full prompt with the facts from the code; the result\n// carries the sections (or the rewritten passage), sanitized to the docs.json shapes.\n//\n// Writers update with the file sha (optimistic concurrency) and retry on 409. Pure helpers plus a few GitHubClient\n// helpers: no DOM, no figma.*, no Node-only API.\n\nimport { DRAFT_LINE_MAX, cleanDraftText, sanitizeDraftLine, type DraftText } from './change-drafts';\nimport { type DocsDraftTask, type DocsSections, docsSectionsAnswer, docsTaskKeys, sanitizeDocsReplacement, validateDocsTask } from './docs-ai';\nimport type { ProseKey } from './docs-draft';\nimport { GitHubError, type GitHubClient } from './github-client';\nimport { REQUESTS_BRANCH, type RequestChange, type RequestKind, REQUEST_KINDS } from './requests';\n\nexport const DRAFT_EXCHANGE_VERSION = 1;\n/** Folder of pending draft sessions on the requests branch. */\nexport const DRAFTS_DIR = '.bridge/drafts';\n/** What the designer says to their Claude. */\nexport const DRAFT_PHRASE = 'Draft my Bridge changes';\nexport const DRAFT_TITLE_MAX = 70;\nexport const DRAFT_SUMMARY_SENTENCES = 3;\nexport { DRAFT_LINE_MAX };\nconst SUMMARY_MAX = 600;\n\nexport type DraftScope = 'request' | 'push' | 'docs';\n/** Who wrote the session: the DS Bridge Figma plugin, or Bridge Studio (component docs on the Library page). */\nexport type DraftSource = 'figma' | 'studio';\nexport type DraftSessionStatus = 'pending' | 'drafted';\n\nexport interface DraftImage {\n label: 'before' | 'after';\n /** Public URL on the requests branch (github.com/<repo>/blob/bridge-requests/<path>?raw=true). */\n url: string;\n /** Repo path on the requests branch, so tools can read it with the token. */\n path?: string | undefined;\n /** The change line (DraftLine id) this image shows, when an item has several components (a push). */\n line?: string | undefined;\n}\n\n/**\n * One detected component change to describe in one sentence (its \"change line\"): the main line of its row in the\n * plugin and the first line of its request. A request item has one, a push item one per component it requests.\n */\nexport interface DraftLine {\n /** Stable id to answer with (the plugin uses the component's node id). */\n id: string;\n component?: string | undefined;\n kind?: RequestKind | undefined;\n changes: RequestChange[];\n /** The deterministic line, from the changes only, as a starting point. */\n line: string;\n /** The deterministic request title of this component change, as a starting point. Missing from older plugins. */\n title?: string | undefined;\n}\n\nexport interface DraftVariableRow {\n path: string;\n before?: string | undefined;\n after?: string | undefined;\n}\n\nexport interface DraftItem {\n id: string;\n /** \"request\": one component change request. \"push\": the pull request description of variable edits. */\n scope: DraftScope;\n component?: string | undefined;\n kind?: RequestKind | undefined;\n changes: RequestChange[];\n /** Push only: the variable edits (token path, value now, value in Figma). */\n variables?: DraftVariableRow[] | undefined;\n /** Push only: components the push also sends a request for. */\n components?: string[] | undefined;\n /** What the designer already typed: their intent, kept in the answer. */\n notes?: string | undefined;\n images?: DraftImage[] | undefined;\n /** The deterministic draft (from the detected changes only), as a starting point. */\n draft: DraftText;\n /** Component changes to write one line each for. Missing in sessions from older plugins. */\n lines?: DraftLine[] | undefined;\n /** Docs only: the component docs to write. */\n docs?: DraftDocsItem | undefined;\n}\n\n/** A docs item: prose sections of one component's docs.json (or one selected passage), from Bridge Studio. */\nexport interface DraftDocsItem {\n /** Component slug on the Library page (button, icon-button). */\n slug: string;\n /** docs.json path in the repo. */\n path?: string | undefined;\n task: DocsDraftTask;\n /** The full prompt: the task, the rules, the facts from the code (props, CSS module classes, JSDoc, tokens), the voice. */\n prompt: string;\n}\n\nexport interface DraftResult {\n id: string;\n title: string;\n summary: string;\n /**\n * One sentence per change line of the item (by DraftLine id), and the title of the request it becomes. Optional:\n * older writers send none, or lines without a title.\n */\n lines?: DraftResultLine[] | undefined;\n /** Docs items (sections task): the sections Claude wrote, sanitized to the docs.json shapes. */\n docs?: DocsSections | undefined;\n /** Docs items (selection task): the rewritten passage. */\n replacement?: string | undefined;\n /** Docs items (sections task): checked sections Claude verified and left unchanged (still accurate). */\n checked?: ProseKey[] | undefined;\n by: 'claude';\n at: string;\n}\n\nexport interface DraftResultLine {\n id: string;\n /** May be empty when only the title was written. */\n line: string;\n /** The request title of this component change: short, sentence case, at most 70 characters (\"Add an icon after the label\"). */\n title?: string | undefined;\n}\n\nexport interface PendingDrafts {\n version: 1;\n sessionId: string;\n createdAt: string;\n status: DraftSessionStatus;\n source: DraftSource;\n items: DraftItem[];\n results?: DraftResult[] | undefined;\n}\n\n// ---------------------------------------------------------------------------------------------\n// The words Claude gets: the Bridge voice and the exact output contract.\n\nexport const DRAFT_VOICE_RULES = [\n 'Write like a calm, precise colleague. Sentence case. Start the title with a verb.',\n 'Look at the before and after images first, then the change table: say what changes for developers (props, variants, tokens, the look) and why it matters for people who use the component.',\n 'Use only facts from the changes, the images and the designer\\'s notes. Never invent numbers, names, usage or reasons. If the reason is unknown, say what changes and leave the reason out.',\n 'Keep the designer\\'s intent from their notes.',\n 'Never use an em dash: use a colon, a comma or parentheses. No exclamation marks, no emoji, no Markdown.',\n 'A request title never repeats the component name: the issue title already starts with it.',\n `For each change line, write one short sentence (at most ${DRAFT_LINE_MAX} characters, no trailing period) of what changed for developers, read from the before and after images: the part, the variant and the values when you can see them, for example \"Icon added after the label in primary sm: Pencil, 16px\". Never guess a value you cannot read.`,\n `For each change line, also write the title of the request it becomes: short, sentence case, starts with a verb, at most ${DRAFT_TITLE_MAX} characters, no trailing period, never the component name, for example \"Add an icon after the label\".`,\n];\n\nexport const DRAFT_OUTPUT_CONTRACT = [\n `Call bridge_write_drafts once per session with {\"sessionId\": \"...\", \"results\": [{\"id\": \"<item id>\", \"title\": \"...\", \"summary\": \"...\", \"lines\": [{\"id\": \"<line id>\", \"line\": \"...\", \"title\": \"...\"}]}]}, one result per item.`,\n `title: one line, at most ${DRAFT_TITLE_MAX} characters, no trailing period.`,\n `summary: at most ${DRAFT_SUMMARY_SENTENCES} sentences, plain text.`,\n `lines: one per change line the item lists (its \"lines\"), by line id: line is one sentence, at most ${DRAFT_LINE_MAX} characters, no trailing period; title is the request title for that component change, at most ${DRAFT_TITLE_MAX} characters, no trailing period. Leave lines out when the item lists none.`,\n 'Docs items (scope \"docs\", from Bridge Studio): follow the item\\'s prompt and send {\"id\": \"<item id>\", \"docs\": {<only the sections it asks for>}} for a sections task (a section to check goes in only when something in it is no longer true for the code: leave accurate ones out, {\"docs\": {}} when all are), or {\"id\": \"<item id>\", \"replacement\": \"...\"} for a selection task. No title or summary. The designer reviews them on the Library page.',\n 'The designer reviews the text in Figma before anything is sent.',\n];\n\n// ---------------------------------------------------------------------------------------------\n// Pure helpers\n\n/** A random session id: 16 lowercase base-36 characters, safe in a file name. */\nexport function newDraftSessionId(random: () => number = Math.random): string {\n let out = '';\n while (out.length < 16) out += Math.floor(random() * 36).toString(36);\n return out;\n}\n\nconst SESSION_RE = /^[a-z0-9-]{6,64}$/;\nexport const isDraftSessionId = (s: unknown): s is string => typeof s === 'string' && SESSION_RE.test(s);\n\n/** Path of a session file on the requests branch. */\nexport function draftSessionPath(sessionId: string): string {\n if (!isDraftSessionId(sessionId)) throw new Error(`\"${sessionId}\" is not a draft session id.`);\n return `${DRAFTS_DIR}/${sessionId}.json`;\n}\n\n/** Path of an image of a session item on the requests branch: `.bridge/drafts/<sessionId>/<itemId>-<label>.png`. */\nexport function draftImagePath(sessionId: string, itemId: string, label: DraftImage['label']): string {\n const item = itemId.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'item';\n draftSessionPath(sessionId);\n return `${DRAFTS_DIR}/${sessionId}/${item}-${label}.png`;\n}\n\nexport interface ComposeDraftsInput {\n items: DraftItem[];\n source?: DraftSource | undefined;\n sessionId?: string | undefined;\n now?: Date | undefined;\n random?: (() => number) | undefined;\n}\n\n/** A new pending session. Throws when it has no item or an item is invalid. */\nexport function composePendingDrafts(input: ComposeDraftsInput): PendingDrafts {\n const p: PendingDrafts = {\n version: DRAFT_EXCHANGE_VERSION,\n sessionId: input.sessionId ?? newDraftSessionId(input.random),\n createdAt: (input.now ?? new Date()).toISOString(),\n status: 'pending',\n source: input.source ?? 'figma',\n items: input.items.map((i) => ({ ...i, changes: i.changes ?? [] })),\n };\n const problems = validatePendingDrafts(p);\n if (problems.length) throw new Error(problems.join(' '));\n return p;\n}\n\nconst KINDS = new Set<string>(REQUEST_KINDS.map((k) => k.value));\nconst str = (x: unknown) => typeof x === 'string';\nconst optStr = (x: unknown) => x === undefined || typeof x === 'string';\n\n/** Problems in a session, as sentences. Empty when valid. */\nexport function validatePendingDrafts(x: unknown): string[] {\n const out: string[] = [];\n if (!x || typeof x !== 'object' || Array.isArray(x)) return ['A draft session is a JSON object.'];\n const p = x as Partial<PendingDrafts>;\n if (p.version !== DRAFT_EXCHANGE_VERSION) out.push(`Unsupported draft session version ${String(p.version)}: update Bridge.`);\n if (!isDraftSessionId(p.sessionId)) out.push('The session id is missing or invalid.');\n if (!str(p.createdAt) || Number.isNaN(Date.parse(p.createdAt!))) out.push('createdAt must be an ISO date.');\n if (p.status !== 'pending' && p.status !== 'drafted') out.push('status must be \"pending\" or \"drafted\".');\n if (p.source !== 'figma' && p.source !== 'studio') out.push('source must be \"figma\" or \"studio\".');\n if (!Array.isArray(p.items) || !p.items.length) out.push('A draft session needs at least one item.');\n const ids = new Set<string>();\n for (const [n, i] of (Array.isArray(p.items) ? p.items : []).entries()) {\n const at = `Item ${n + 1}`;\n if (!i || typeof i !== 'object') {\n out.push(`${at} is not an object.`);\n continue;\n }\n if (!str(i.id) || !i.id) out.push(`${at} has no id.`);\n else if (ids.has(i.id)) out.push(`${at} repeats the id \"${i.id}\".`);\n else ids.add(i.id);\n if (i.scope !== 'request' && i.scope !== 'push' && i.scope !== 'docs') out.push(`${at}: scope must be \"request\", \"push\" or \"docs\".`);\n if (i.scope === 'docs') {\n const d = i.docs;\n if (!d || typeof d !== 'object' || !str(d.slug) || !d.slug || !str(d.prompt) || !d.prompt || !optStr(d.path)) out.push(`${at}: a docs item needs docs {slug, task, prompt}.`);\n else out.push(...validateDocsTask(d.task).map((m) => `${at}: ${m}`));\n } else if (i.docs !== undefined) out.push(`${at}: only a docs item has docs.`);\n if (!optStr(i.component)) out.push(`${at}: component must be text.`);\n if (i.kind !== undefined && !KINDS.has(i.kind)) out.push(`${at}: unknown kind \"${String(i.kind)}\".`);\n if (!Array.isArray(i.changes) || i.changes.some((c) => !c || !str(c.field) || !optStr(c.before) || !optStr(c.after))) out.push(`${at}: changes must be a list of {field, before, after}.`);\n if (i.variables !== undefined && (!Array.isArray(i.variables) || i.variables.some((v) => !v || !str(v.path)))) out.push(`${at}: variables must be a list of {path, before, after}.`);\n if (i.variables !== undefined && i.scope !== 'push') out.push(`${at}: only a push item has variables.`);\n if (i.images !== undefined && (!Array.isArray(i.images) || i.images.some((m) => !m || (m.label !== 'before' && m.label !== 'after') || !str(m.url)))) out.push(`${at}: images must be a list of {label: before or after, url}.`);\n if (!i.draft || !str(i.draft.title) || !str(i.draft.summary)) out.push(`${at}: draft must hold a title and a summary.`);\n if (i.lines !== undefined && (!Array.isArray(i.lines) || i.lines.some((l) => !l || !str(l.id) || !l.id || !str(l.line) || !optStr(l.title) || !Array.isArray(l.changes)))) out.push(`${at}: lines must be a list of {id, changes, line, title}.`);\n }\n if (p.results !== undefined) {\n if (!Array.isArray(p.results)) out.push('results must be a list.');\n else\n for (const r of p.results) {\n if (!r || !str(r.id) || !str(r.title) || !str(r.summary)) out.push('Each result needs an id, a title and a summary.');\n else if (r.docs !== undefined && (!r.docs || typeof r.docs !== 'object' || Array.isArray(r.docs))) out.push('Result docs must be an object of sections.');\n else if (!optStr(r.replacement)) out.push('A result replacement must be text.');\n else if (r.lines !== undefined && (!Array.isArray(r.lines) || r.lines.some((l) => !l || !str(l.id) || !str(l.line) || !optStr(l.title)))) out.push('Result lines must be a list of {id, line, title}.');\n }\n }\n return out;\n}\n\n/** The session in a file's text, or undefined when it is not a valid session. */\nexport function parsePendingDrafts(text: string | null | undefined): PendingDrafts | undefined {\n if (!text) return undefined;\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch {\n return undefined;\n }\n return validatePendingDrafts(json).length ? undefined : (json as PendingDrafts);\n}\n\nexport function serializePendingDrafts(p: PendingDrafts): string {\n return `${JSON.stringify(p, null, 2)}\\n`;\n}\n\n/** Shortens to `max` characters at a word boundary, without a trailing period. */\nfunction clip(text: string, max: number): string {\n const t = text.replace(/\\s+/g, ' ').trim().replace(/\\.$/, '');\n if (t.length <= max) return t;\n const cut = t.slice(0, max + 1);\n const at = cut.lastIndexOf(' ');\n return (at > max * 0.5 ? cut.slice(0, at) : t.slice(0, max)).replace(/[\\s,;:]+$/, '');\n}\n\n/** At most 3 sentences and 600 characters. */\nfunction sentences(text: string): string {\n const t = text.replace(/\\s+/g, ' ').trim();\n const parts = t.match(/[^.!?]+(?:[.!?]+(?=\\s|$)|$)/g) ?? [t];\n let out = parts.slice(0, DRAFT_SUMMARY_SENTENCES).map((s) => s.trim()).join(' ');\n if (out.length > SUMMARY_MAX) out = `${clip(out, SUMMARY_MAX)}.`;\n return out;\n}\n\n/**\n * Title and summary kept to the contract: em dashes removed, title one line of at most 70 characters with no\n * trailing period, summary at most 3 sentences. Both may come back empty.\n */\nexport function sanitizeDraftText(raw: { title?: unknown; summary?: unknown }): DraftText {\n const title = typeof raw.title === 'string' ? clip(cleanDraftText(raw.title), DRAFT_TITLE_MAX) : '';\n const summary = typeof raw.summary === 'string' ? sentences(cleanDraftText(raw.summary)) : '';\n return { title, summary };\n}\n\n/** What a writer (bridge_write_drafts) sends for one item, before sanitizing. */\nexport interface DraftResultInput {\n id: string;\n title?: unknown;\n summary?: unknown;\n lines?: unknown;\n /** Docs items: the sections written (sections task). */\n docs?: unknown;\n /** Docs items: the rewritten passage (selection task). */\n replacement?: unknown;\n}\n\n/** The docs part of a result for a docs item, sanitized to its task. Throws when it holds nothing the task asked for. */\nexport function sanitizeDocsResult(item: DraftItem, r: DraftResultInput): Pick<DraftResult, 'docs' | 'replacement' | 'checked'> {\n const task = item.docs!.task;\n if (task.kind === 'selection') {\n const raw = r.replacement ?? (r.docs && typeof r.docs === 'object' ? (r.docs as Record<string, unknown>)[task.key] : undefined);\n const replacement = sanitizeDocsReplacement(raw);\n if (!replacement) throw new Error(`Item \"${item.id}\" asks to rewrite a passage of ${task.key}: send {\"id\": \"${item.id}\", \"replacement\": \"...\"}.`);\n return { replacement };\n }\n try {\n const { sections, checked } = docsSectionsAnswer(task, r.docs ?? {});\n return { docs: sections, checked };\n } catch {\n throw new Error(`Item \"${item.id}\" asks for the sections ${docsTaskKeys(task).join(', ')}: send {\"id\": \"${item.id}\", \"docs\": {${task.keys.map((k) => `\"${k}\": ...`).join(', ')}}} in the shapes of its prompt.`);\n }\n}\n\n/**\n * The change lines of a result kept to the contract: known line ids only (throws on an unknown one), one sentence of\n * at most 120 characters each, empty ones dropped, the last one per id kept.\n */\nexport function sanitizeResultLines(item: Pick<DraftItem, 'id' | 'lines'>, raw: unknown): DraftResultLine[] {\n if (raw === undefined || raw === null) return [];\n if (!Array.isArray(raw)) throw new Error(`lines for \"${item.id}\" must be a list of {\"id\", \"line\", \"title\"}.`);\n const known = new Set((item.lines ?? []).map((l) => l.id));\n const out = new Map<string, DraftResultLine>();\n for (const l of raw as { id?: unknown; line?: unknown; title?: unknown }[]) {\n const id = typeof l?.id === 'string' ? l.id : '';\n if (!known.has(id)) throw new Error(`Item \"${item.id}\" has no change line \"${id}\".${known.size ? ` Use the line ids from bridge_pending_drafts: ${[...known].join(', ')}.` : ' It lists no lines: leave lines out.'}`);\n const line = sanitizeDraftLine(l.line);\n const title = sanitizeDraftTitle(l.title);\n if (line || title) out.set(id, { id, line, ...(title ? { title } : {}) });\n }\n return [...out.values()];\n}\n\n/** A request title kept to the contract: one line, no em dash, sentence case, at most 70 characters, no trailing period. */\nexport function sanitizeDraftTitle(raw: unknown): string {\n if (typeof raw !== 'string') return '';\n const t = clip(cleanDraftText(raw.replace(/[\\r\\n]+/g, ' ')), DRAFT_TITLE_MAX);\n return t.charAt(0).toUpperCase() + t.slice(1);\n}\n\n/**\n * The session with these results added (a result for the same item replaces the earlier one). Results are sanitized.\n * Throws on an unknown item id or an empty result. Status is \"drafted\" once every item has a result.\n */\nexport function mergeDraftResults(p: PendingDrafts, results: DraftResultInput[], at: Date = new Date()): PendingDrafts {\n const ids = new Set(p.items.map((i) => i.id));\n const next = new Map((p.results ?? []).map((r) => [r.id, r]));\n for (const r of results) {\n if (!ids.has(r.id)) throw new Error(`Session ${p.sessionId} has no item \"${r.id}\". Use the ids from bridge_pending_drafts: ${[...ids].join(', ')}.`);\n const item = p.items.find((i) => i.id === r.id)!;\n if (item.scope === 'docs') {\n next.set(r.id, { id: r.id, title: '', summary: '', ...sanitizeDocsResult(item, r), by: 'claude', at: at.toISOString() });\n continue;\n }\n const clean = sanitizeDraftText(r);\n const lines = sanitizeResultLines(item, r.lines);\n if (!clean.title && !clean.summary && !lines.length) throw new Error(`The result for \"${r.id}\" has no title and no summary, and no line.`);\n next.set(r.id, { id: r.id, title: clean.title, summary: clean.summary, ...(lines.length ? { lines } : {}), by: 'claude', at: at.toISOString() });\n }\n const merged = p.items.map((i) => next.get(i.id)).filter((r): r is DraftResult => !!r);\n return { ...p, results: merged, status: merged.length === p.items.length ? 'drafted' : 'pending' };\n}\n\n/** The Markdown brief of one item, for Claude: what to write, the facts, the starting draft. */\nexport function draftItemBrief(i: DraftItem): string {\n if (i.scope === 'docs' && i.docs) {\n const t = i.docs.task;\n const check = t.kind === 'sections' ? (t.check ?? []).filter((k) => t.keys.includes(k)) : [];\n const write = t.kind === 'sections' ? t.keys.filter((k) => !check.includes(k)) : [];\n const what =\n t.kind === 'selection'\n ? `rewrite one passage of the ${t.key} section (${t.mode}), answer with \"replacement\"`\n : [\n write.length ? `${t.rewrite ? 'rewrite' : 'write'} the sections ${write.join(', ')}` : '',\n check.length ? `check the sections ${check.join(', ')} against the code and return one only when something in it is no longer true (leave accurate ones out)` : '',\n ]\n .filter(Boolean)\n .join('; ') + ', answer with \"docs\"';\n return [`Item ${i.id}: component docs${i.component ? ` of ${i.component}` : ''} from Bridge Studio (${i.docs.path ?? i.docs.slug}): ${what}.`, '', i.docs.prompt].join('\\n');\n }\n const kind = i.kind ? REQUEST_KINDS.find((k) => k.value === i.kind)?.label : undefined;\n const cell = (s: string | undefined) => (s ?? '').replace(/\\|/g, '\\\\|').replace(/\\n/g, ' ');\n const lines: string[] = [`Item ${i.id}: ${i.scope === 'request' ? 'a component change request (a GitHub issue developers implement)' : 'the description of a pull request with design token (variable) edits from Figma'}.`];\n if (i.component) lines.push(`Component: ${i.component}`);\n if (kind) lines.push(`Kind: ${kind}`);\n if (i.components?.length) lines.push(`Components with a change request: ${i.components.join(', ')}`);\n if (i.changes.length) lines.push('', '| What | Now | In Figma |', '| --- | --- | --- |', ...i.changes.map((c) => `| ${cell(c.field)} | ${cell(c.before) || 'none'} | ${cell(c.after) || 'removed'} |`));\n if (i.variables?.length) lines.push('', '| Token | Now | In Figma |', '| --- | --- | --- |', ...i.variables.map((v) => `| ${cell(v.path)} | ${cell(v.before) || 'none'} | ${cell(v.after) || 'removed'} |`));\n if (!i.changes.length && !i.variables?.length && !i.lines?.length) lines.push('', 'No change detected: rely on the notes and the images.');\n if (i.draft.title || i.draft.summary) lines.push('', 'Starting draft, written from the changes only:', `Title: ${i.draft.title}`, `Summary: ${i.draft.summary}`);\n if (i.notes?.trim()) lines.push('', 'The designer\\'s notes (keep their intent):', i.notes.trim());\n if (i.lines?.length) {\n lines.push('', `Change lines to write (one sentence each, at most ${DRAFT_LINE_MAX} characters, from the before and after images), each with the title of its request (at most ${DRAFT_TITLE_MAX} characters):`);\n for (const l of i.lines) {\n lines.push(`- Line ${l.id}${l.component ? `, ${l.component}` : ''}${l.kind ? ` (${REQUEST_KINDS.find((k) => k.value === l.kind)?.label ?? l.kind})` : ''}. Starting line: ${l.line || '(none)'}${l.title ? `. Starting title: ${l.title}` : ''}`);\n for (const c of l.changes) lines.push(` - ${c.field}: ${c.before || 'none'} -> ${c.after || 'removed'}`);\n }\n }\n if (i.images?.length) lines.push('', `Images: ${i.images.map((m) => `${m.label}${m.line ? ` (line ${m.line})` : ''} ${m.url}`).join(', ')}`);\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------------------------\n// GitHub: read and write sessions on the requests branch\n\ntype DraftClient = Pick<GitHubClient, 'getFile' | 'putFile' | 'deleteFile' | 'listDirectory'>;\n\nconst isConflict = (err: unknown) => err instanceof GitHubError ? err.status === 409 || (err.status === 422 && /sha/i.test(`${err.detail ?? ''} ${err.message}`)) : (err as { status?: number })?.status === 409;\n\n/** Writes a new session file on the requests branch (the branch must exist). Returns the session. */\nexport async function createPendingDrafts(client: DraftClient, p: PendingDrafts, branch = REQUESTS_BRANCH): Promise<PendingDrafts> {\n const problems = validatePendingDrafts(p);\n if (problems.length) throw new Error(problems.join(' '));\n await client.putFile({ path: draftSessionPath(p.sessionId), content: serializePendingDrafts(p), branch, message: `Bridge drafts: ${p.items.length === 1 ? '1 item' : `${p.items.length} items`} waiting for Claude` });\n return p;\n}\n\n/** One session and its file sha, or undefined when the file is gone (sent, cancelled) or not a session. */\nexport async function readPendingDrafts(client: Pick<GitHubClient, 'getFile'>, sessionId: string, branch = REQUESTS_BRANCH): Promise<{ drafts: PendingDrafts; sha: string } | undefined> {\n const f = await client.getFile(draftSessionPath(sessionId), branch);\n const drafts = parsePendingDrafts(f?.text);\n return f && drafts ? { drafts, sha: f.sha } : undefined;\n}\n\n/** Every valid session on the requests branch, newest first. Unreadable files are skipped. */\nexport async function listPendingDrafts(client: Pick<GitHubClient, 'getFile' | 'listDirectory'>, opts: { status?: DraftSessionStatus | 'all'; branch?: string } = {}): Promise<PendingDrafts[]> {\n const branch = opts.branch ?? REQUESTS_BRANCH;\n const entries = (await client.listDirectory(DRAFTS_DIR, branch)).filter((e) => e.type === 'file' && /\\.json$/.test(e.name));\n const out: PendingDrafts[] = [];\n for (const e of entries) {\n const id = e.name.replace(/\\.json$/, '');\n if (!isDraftSessionId(id)) continue;\n const r = await readPendingDrafts(client, id, branch).catch(() => undefined);\n if (r && r.drafts.sessionId === id) out.push(r.drafts);\n }\n const status = opts.status ?? 'all';\n return out.filter((p) => status === 'all' || p.status === status).sort((a, b) => b.createdAt.localeCompare(a.createdAt));\n}\n\n/**\n * Read, change and write a session with its sha; when someone else wrote it in between (409), read it again and\n * retry, up to `attempts` times. Throws when the session does not exist.\n */\nexport async function updatePendingDrafts(\n client: DraftClient,\n sessionId: string,\n change: (p: PendingDrafts) => PendingDrafts,\n opts: { branch?: string; attempts?: number; message?: string } = {},\n): Promise<PendingDrafts> {\n const branch = opts.branch ?? REQUESTS_BRANCH;\n const attempts = Math.max(1, opts.attempts ?? 3);\n for (let attempt = 1; ; attempt++) {\n const cur = await readPendingDrafts(client, sessionId, branch);\n if (!cur) throw new Error(`No pending drafts for session ${sessionId}: it was sent or cancelled in Figma. Call bridge_pending_drafts for the current ones.`);\n const next = change(cur.drafts);\n try {\n await client.putFile({ path: draftSessionPath(sessionId), content: serializePendingDrafts(next), branch, message: opts.message ?? 'Bridge drafts: update', sha: cur.sha });\n return next;\n } catch (err) {\n if (attempt >= attempts || !isConflict(err)) throw err;\n }\n }\n}\n\n/** Writes Claude's results into a session (sanitized, merged, status \"drafted\" when complete), retrying on 409. */\nexport function writeDraftResults(client: DraftClient, sessionId: string, results: DraftResultInput[], opts: { branch?: string; now?: Date; attempts?: number } = {}): Promise<PendingDrafts> {\n return updatePendingDrafts(client, sessionId, (p) => mergeDraftResults(p, results, opts.now), {\n ...opts,\n message: `Bridge drafts: ${results.length === 1 ? '1 text' : `${results.length} texts`} drafted by Claude`,\n });\n}\n\n/**\n * Removes a session once it was sent or cancelled: its file, then its images (best effort). Returns false when it was\n * already gone.\n */\nexport async function deletePendingDrafts(client: DraftClient, sessionId: string, opts: { branch?: string } = {}): Promise<boolean> {\n const branch = opts.branch ?? REQUESTS_BRANCH;\n const path = draftSessionPath(sessionId);\n const f = await client.getFile(path, branch);\n if (!f) return false;\n await client.deleteFile({ path, branch, message: 'Bridge drafts: done', sha: f.sha });\n const images = await client.listDirectory(`${DRAFTS_DIR}/${sessionId}`, branch).catch(() => []);\n for (const img of images.filter((e) => e.type === 'file')) {\n await client.deleteFile({ path: img.path, branch, message: 'Bridge drafts: done', sha: img.sha }).catch(() => undefined);\n }\n return true;\n}\n\n/** Creates the requests branch from the head of `baseBranch` when it is missing. Never moves an existing branch. */\nexport async function ensureRequestsBranch(client: Pick<GitHubClient, 'getBranchSha' | 'createBranch'>, baseBranch: string): Promise<void> {\n if (await client.getBranchSha(REQUESTS_BRANCH)) return;\n const head = await client.getBranchSha(baseBranch);\n if (!head) throw new Error(`Branch \"${baseBranch}\" was not found, so the ${REQUESTS_BRANCH} branch cannot start from it.`);\n await client.createBranch(REQUESTS_BRANCH, head);\n}\n\nexport interface DocsDraftSessionInput {\n component: string;\n slug: string;\n path?: string | undefined;\n task: DocsDraftTask;\n prompt: string;\n /** Branch the requests branch starts from when it does not exist yet. */\n baseBranch: string;\n now?: Date | undefined;\n random?: (() => number) | undefined;\n}\n\n/**\n * Bridge Studio asks the user's own Claude for component docs: one docs item in a new session (source \"studio\") on\n * the requests branch, created from `baseBranch` when missing. Returns the session to poll.\n */\nexport async function createDocsDraftSession(\n client: Pick<GitHubClient, 'getBranchSha' | 'createBranch' | 'getFile' | 'putFile' | 'deleteFile' | 'listDirectory'>,\n input: DocsDraftSessionInput,\n): Promise<PendingDrafts> {\n await ensureRequestsBranch(client, input.baseBranch);\n const what = input.task.kind === 'selection' ? `Rewrite a passage of ${input.task.key}` : `${input.task.rewrite ? 'Rewrite' : 'Write'} ${input.task.keys.join(', ')}`;\n const item: DraftItem = {\n id: 'docs-1',\n scope: 'docs',\n component: input.component,\n changes: [],\n draft: { title: `${input.component} docs`, summary: what },\n docs: { slug: input.slug, ...(input.path ? { path: input.path } : {}), task: input.task, prompt: input.prompt },\n };\n return createPendingDrafts(client, composePendingDrafts({ items: [item], source: 'studio', now: input.now, random: input.random }));\n}\n\n// ---------------------------------------------------------------------------------------------\n// Polling: the plugin and Studio read the session until Claude answers\n\nexport const DRAFT_POLL_INTERVAL_MS = 5_000;\nexport const DRAFT_POLL_TIMEOUT_MS = 10 * 60_000;\n\nexport interface DraftPollerOptions {\n client: Pick<GitHubClient, 'getFile'>;\n sessionId: string;\n intervalMs?: number | undefined;\n timeoutMs?: number | undefined;\n now?: (() => number) | undefined;\n setTimer?: ((fn: () => void, ms: number) => unknown) | undefined;\n clearTimer?: ((handle: unknown) => void) | undefined;\n /** Claude answered every item. Polling has stopped. */\n onResults: (results: DraftResult[], drafts: PendingDrafts) => void;\n /** No answer within the timeout. Polling has stopped; start() polls again. */\n onTimeout: () => void;\n /** The file is gone (sent or cancelled elsewhere). Polling has stopped. */\n onGone?: (() => void) | undefined;\n /** A read failed; polling goes on. */\n onError?: ((message: string) => void) | undefined;\n}\n\n/** Reads the session every 5 seconds until Claude answers, the file goes away, or 10 minutes pass. */\nexport class DraftPoller {\n private handle: unknown;\n private startedAt = 0;\n private running = false;\n private busy = false;\n\n constructor(private readonly o: DraftPollerOptions) {}\n\n get active(): boolean {\n return this.running;\n }\n\n private now(): number {\n return (this.o.now ?? Date.now)();\n }\n\n private schedule(): void {\n const set = this.o.setTimer ?? ((fn: () => void, ms: number) => setTimeout(fn, ms));\n this.handle = set(() => void this.tick(), this.o.intervalMs ?? DRAFT_POLL_INTERVAL_MS);\n }\n\n /** Starts (or restarts, after a timeout) polling; the timeout counts from now. */\n start(): void {\n this.stop();\n this.running = true;\n this.startedAt = this.now();\n this.schedule();\n }\n\n stop(): void {\n if (this.handle !== undefined) (this.o.clearTimer ?? ((h: unknown) => clearTimeout(h as ReturnType<typeof setTimeout>)))(this.handle);\n this.handle = undefined;\n this.running = false;\n }\n\n private async tick(): Promise<void> {\n if (!this.running) return;\n this.handle = undefined;\n const done = await this.check();\n if (done || !this.running) return;\n if (this.now() - this.startedAt >= (this.o.timeoutMs ?? DRAFT_POLL_TIMEOUT_MS)) {\n this.stop();\n this.o.onTimeout();\n return;\n }\n this.schedule();\n }\n\n /** Reads the file once. True when polling is over (answered or gone). */\n async check(): Promise<boolean> {\n if (this.busy) return false;\n this.busy = true;\n try {\n const cur = await readPendingDrafts(this.o.client, this.o.sessionId);\n if (!cur) {\n this.stop();\n this.o.onGone?.();\n return true;\n }\n if (cur.drafts.status === 'drafted' && cur.drafts.results?.length) {\n this.stop();\n this.o.onResults(cur.drafts.results, cur.drafts);\n return true;\n }\n return false;\n } catch (err) {\n this.o.onError?.(err instanceof Error ? err.message : String(err));\n return false;\n } finally {\n this.busy = false;\n }\n }\n}\n","// Explorations on GitHub: start one (branch from the base with the exploration note, a draft pull request labeled\n// `exploration`), list them, promote one to review, close one. Shared by Studio (in the browser, with the viewer's\n// token), the MCP server and the CLI. The pure rules are in explorations.ts.\n\nimport type { BridgeConfig } from './config';\nimport {\n EXPLORATION_LABEL,\n EXPLORATION_PREFIX,\n explorationNote,\n explorationNotePath,\n explorationPrBody,\n explorationPrTitle,\n explorationProblems,\n explorationSlug,\n explorationStatus,\n explorationTryIt,\n isExplorationPull,\n parseExplorationBody,\n promotionPlan,\n type Exploration,\n type ExplorationSource,\n type ExplorationStatus,\n type ExplorationTryIt,\n type PromotionPlan,\n} from './explorations';\nimport { GitHubError, type GitHubClient, type PullRequestSummary } from './github-client';\nimport { findPreviewComment, previewLinks, previewsSettled, type BranchPreview, type PreviewApps } from './previews';\nimport { branchPreviewUrls } from './previews-github';\n\nexport interface ExplorationSettings {\n /** Branch explorations start from and pull requests target (the default branch). */\n base: string;\n /** Snapshot packages (bridge.config.json previews.packages). */\n packages: string[];\n /** Per-branch preview URL templates (bridge.config.json previews.apps). */\n apps: PreviewApps;\n /** Requests the exploration answers, listed in its draft pull request body. */\n requests?: { number: number; title: string }[] | undefined;\n /** More labels for the draft pull request, such as the product ones (productMarks). */\n labels?: string[] | undefined;\n}\n\nexport interface ExplorationSummary {\n number: number;\n url: string;\n branch: string;\n slug: string;\n name: string;\n purpose: string;\n useCase?: string | undefined;\n status: ExplorationStatus;\n draft: boolean;\n author: string;\n /** Where it was started and the AI agent that started it, when the exploration block says so. */\n source?: ExplorationSource | undefined;\n agent?: string | undefined;\n updatedAt: string;\n /** Head commit of the branch. */\n headSha: string;\n /**\n * Template previews Vercel cannot have shortened (a host label of 63 characters or less), without a round trip. The\n * URLs Vercel reports, with their build state, come from `explorationTestBuildOnGitHub`.\n */\n previews: { app: string; label: string; url: string }[];\n}\n\n/** One exploration from a pull request summary. */\nexport function explorationSummary(p: PullRequestSummary, _owner: string, _repo: string, s: Pick<ExplorationSettings, 'packages' | 'apps'>): ExplorationSummary {\n const e = parseExplorationBody(p.body);\n const slug = p.headRef?.startsWith(EXPLORATION_PREFIX) ? p.headRef.slice(EXPLORATION_PREFIX.length) : (e?.slug ?? explorationSlug(p.title));\n return {\n number: p.number,\n url: p.url,\n branch: p.headRef,\n slug,\n name: e?.name ?? p.title.replace(/^[A-Z][A-Z0-9_]*-\\d+\\s+/, '').replace(/^Exploration:\\s*/i, ''),\n purpose: e?.purpose ?? '',\n ...(e?.useCase ? { useCase: e.useCase } : {}),\n status: explorationStatus({ state: p.state, labels: p.labels, headRef: p.headRef, body: p.body }),\n draft: p.draft,\n author: e?.author ?? p.author,\n ...(e?.source ? { source: e.source } : {}),\n ...(e?.agent ? { agent: e.agent } : {}),\n updatedAt: p.updatedAt,\n headSha: p.headSha,\n previews: previewLinks(s.apps, { branch: p.headRef, pr: p.number, sha: p.headSha }),\n };\n}\n\n/** Explorations of the repo, newest activity first. `state: 'open'` lists the running ones and the promoted open ones. */\nexport async function listExplorationsOnGitHub(gh: GitHubClient, s: Pick<ExplorationSettings, 'packages' | 'apps'>, opts: { state?: 'open' | 'closed' | 'all' } = {}): Promise<ExplorationSummary[]> {\n const pulls = await gh.listPullRequests(opts.state ?? 'open');\n return pulls.filter((p) => isExplorationPull({ state: p.state, labels: p.labels, headRef: p.headRef, body: p.body })).map((p) => explorationSummary(p, gh.owner, gh.name, s));\n}\n\nexport interface StartedExploration {\n branch: string;\n slug: string;\n pr: number;\n url: string;\n commit: string;\n /** Just started: the snapshot is not built yet. `explorationTestBuildOnGitHub` reads the command once it is. */\n tryIt: ExplorationTryIt;\n previews: { app: string; label: string; url: string }[];\n}\n\n/**\n * Starts an exploration: the branch `explore/<slug>` from the base with one commit (the exploration note), a draft\n * pull request labeled `exploration`, then the body rewritten with the pull request number so it carries the\n * install command. Refuses an exploration whose branch already exists.\n */\nexport async function startExplorationOnGitHub(gh: GitHubClient, e: Exploration, s: ExplorationSettings): Promise<StartedExploration> {\n const problems = explorationProblems(e);\n if (problems.length) throw new GitHubError(422, problems.join(' '));\n if (!gh.canWrite) throw new GitHubError(401, 'Starting an exploration needs a GitHub token (contents and pull requests, read and write, on this repository only).');\n const slug = e.slug || explorationSlug(e.name);\n const branch = `${EXPLORATION_PREFIX}${slug}`;\n const x = gh.withBranchPrefix(EXPLORATION_PREFIX);\n if (await x.getBranchSha(branch)) throw new GitHubError(422, `An exploration named \"${slug}\" already exists (${branch}). Pick another name, or continue that one.`);\n const full: Exploration = { ...e, slug, startedAt: e.startedAt ?? new Date().toISOString() };\n const commit = await x.commitToNewBranch({\n base: s.base,\n branch,\n message: `chore(explore): start ${full.name.trim()}\\n\\n${full.purpose.trim()}\\n\\nExploration: never merged as is. Promote it to review or close it.`,\n files: [{ path: explorationNotePath(slug), content: explorationNote(full) }],\n });\n const ctx = { owner: gh.owner, repo: gh.name, packages: s.packages, apps: s.apps, ...(s.requests?.length ? { requests: s.requests } : {}) };\n const title = full.jira ? `${full.jira.trim().toUpperCase()} ${explorationPrTitle(full)}` : explorationPrTitle(full);\n const pr = await x.createPullRequest({ title, head: branch, base: s.base, body: explorationPrBody(full, ctx), draft: true });\n await x.addLabels(pr.number, [EXPLORATION_LABEL, ...(s.labels ?? [])]);\n // The number exists now: the body gets the install command.\n await x.updatePullRequest(pr.number, { body: explorationPrBody(full, { ...ctx, pr: pr.number }) }).catch(() => undefined);\n return {\n branch,\n slug,\n pr: pr.number,\n url: pr.url,\n commit: commit.sha,\n tryIt: { state: 'building' },\n previews: previewLinks(s.apps, { branch, pr: pr.number, sha: commit.sha }),\n };\n}\n\n/**\n * Where the test build of an exploration stands: the install command from its sticky preview comment when it matches\n * the branch head, \"building\" while the workflow has not caught up, \"failed\" when the publish failed. Two reads.\n */\nexport async function explorationTryItOnGitHub(gh: GitHubClient, e: { number: number; branch: string }): Promise<ExplorationTryIt> {\n const [comments, head] = await Promise.all([gh.listIssueComments(e.number), gh.getBranchSha(e.branch).catch(() => undefined)]);\n return explorationTryIt({ comment: findPreviewComment(comments)?.body, headSha: head });\n}\n\nexport interface ExplorationTestBuild {\n /** The install command from the sticky preview comment, or building/failed. Never a guessed command. */\n tryIt: ExplorationTryIt;\n /** Every configured app with the URL Vercel reports (null while unknown) and its build state. */\n previews: BranchPreview[];\n /** True when the command is ready (or the publish failed) and every preview is built: polling can stop. */\n settled: boolean;\n}\n\n/**\n * Everything \"Try it\" shows for an exploration, read in one go: the command from the preview comment and the real\n * preview URLs (deployments, Vercel statuses, the Vercel comment). Comments and the branch head are read once.\n */\nexport async function explorationTestBuildOnGitHub(gh: GitHubClient, e: { number: number; branch: string }, config: Pick<BridgeConfig, 'previews'> | undefined): Promise<ExplorationTestBuild> {\n const [comments, head] = await Promise.all([gh.listIssueComments(e.number), gh.getBranchSha(e.branch).catch(() => undefined)]);\n const tryIt = explorationTryIt({ comment: findPreviewComment(comments)?.body, headSha: head });\n const previews = await branchPreviewUrls(gh, e.number, config, { branch: e.branch, sha: head, comments }).catch(() => [] as BranchPreview[]);\n return { tryIt, previews, settled: tryIt.state !== 'building' && previewsSettled(previews) };\n}\n\n/** The open exploration pull request of a branch, slug or number. */\nexport async function findExplorationOnGitHub(gh: GitHubClient, ref: string | number): Promise<PullRequestSummary & { body: string }> {\n if (typeof ref === 'number' || /^#?\\d+$/.test(String(ref))) {\n const p = await gh.getPullRequest(Number(String(ref).replace(/^#/, '')));\n if (!isExplorationPull({ state: p.state, labels: p.labels, headRef: p.headRef, body: p.body })) throw new GitHubError(422, `Pull request #${p.number} is not an exploration.`);\n return p;\n }\n const branch = `${EXPLORATION_PREFIX}${explorationSlug(String(ref))}`;\n const open = await gh.findOpenPullRequest(branch);\n if (!open) throw new GitHubError(404, `No open exploration on ${branch}. \\`bridge explore list\\` shows the running ones.`);\n return gh.getPullRequest(open.number);\n}\n\nexport interface PromotedExploration extends PromotionPlan {\n number: number;\n url: string;\n branch: string;\n /** Steps that did not go through, with what to do on GitHub instead. */\n warnings: string[];\n}\n\n/**\n * Promotes an exploration to a normal pull request for review: the exploration note removed from the branch, the\n * tier labels from the shared classifier, the `exploration` label removed, the body for review (closing the\n * requests implemented on it), and the draft marked ready for review (GraphQL). Never merges.\n */\nexport async function promoteExplorationOnGitHub(\n gh: GitHubClient,\n ref: string | number,\n opts: { config?: BridgeConfig | undefined; requests?: number[] | undefined; date?: Date | undefined; dryRun?: boolean | undefined } = {},\n): Promise<PromotedExploration> {\n const p = await findExplorationOnGitHub(gh, ref);\n const status = explorationStatus({ state: p.state, labels: p.labels, headRef: p.headRef, body: p.body });\n if (status !== 'active') throw new GitHubError(422, status === 'closed' ? `Exploration #${p.number} is closed. Reopen it on GitHub first.` : `#${p.number} is already promoted to review.`);\n const files = await gh.listPullRequestFiles(p.number);\n const plan = promotionPlan({ title: p.title, body: p.body, labels: p.labels, files: files.map((f) => ({ path: f.filename, status: f.status })), config: opts.config, requests: opts.requests, date: opts.date });\n const out: PromotedExploration = { ...plan, number: p.number, url: p.url, branch: p.headRef, warnings: [] };\n if (opts.dryRun) return out;\n if (!gh.canWrite) throw new GitHubError(401, 'Promoting an exploration needs a GitHub token (contents and pull requests, read and write).');\n const x = gh.withBranchPrefix(EXPLORATION_PREFIX);\n if (plan.removeFiles.length) {\n await x.commitToBranch({ branch: p.headRef, message: 'chore(explore): promote to review, remove the exploration note', files: plan.removeFiles.map((path) => ({ path, content: null })) }).catch((e: Error) => {\n // A refused token is not a partial success: nothing else would go through either.\n if (e instanceof GitHubError && e.auth === 'rejected') throw e;\n out.warnings.push(`The exploration note stays on the branch (${e.message}). Delete ${plan.removeFiles.join(', ')} before merging.`);\n });\n }\n await x.addLabels(p.number, plan.addLabels);\n await x.removeLabel(p.number, EXPLORATION_LABEL).catch((e: Error) => {\n if (!(e instanceof GitHubError && e.status === 404)) out.warnings.push(`The exploration label is still on (${e.message}). Remove it on GitHub.`);\n });\n await x.updatePullRequest(p.number, { title: plan.title, body: plan.body });\n await x.markReadyForReview(p.number).catch((e: Error) => {\n out.warnings.push(`Still a draft: ${e.message}`);\n });\n return out;\n}\n\n/** Closes an exploration without merging. The branch stays for reference; the workflow removes the prerelease. */\nexport async function closeExplorationOnGitHub(gh: GitHubClient, ref: string | number): Promise<{ number: number; url: string; branch: string }> {\n if (!gh.canWrite) throw new GitHubError(401, 'Closing an exploration needs a GitHub token (pull requests: write).');\n const p = await findExplorationOnGitHub(gh, ref);\n await gh.updatePullRequest(p.number, { state: 'closed' });\n return { number: p.number, url: p.url, branch: p.headRef };\n}\n","// Deciding on a component change request on GitHub: link it to an exploration, assign someone, or decline it. The\n// same calls for Studio (the viewer's own token), the MCP server and the CLI. Pure rules live in requests.ts.\nimport { EXPLORATION_LABEL, isExplorationBranch } from './explorations';\nimport { GitHubClient, GitHubError } from './github-client';\nimport { declineComment, declineReasonProblems, withRequestExploration } from './requests';\n\nexport interface RequestExplorationLink {\n number: number;\n branch: string;\n /** Who is now on it, when someone was assigned in the same step. */\n assignees: string[];\n /** Sentences about the parts that did not go through (label refused): the link itself holds. */\n warnings: string[];\n}\n\n/**\n * Links a request to an exploration branch, the way `bridge request create --exploration` files one: the hidden block\n * gets `exploration`, the issue gets the `exploration` label, and whoever starts the exploration is assigned, so the\n * request reads \"in progress\" everywhere. Implementing it then happens on that branch (`request implement --branch`).\n */\nexport async function linkRequestToExplorationOnGitHub(gh: GitHubClient, n: number, branch: string, opts: { assignee?: string | null } = {}): Promise<RequestExplorationLink> {\n if (!isExplorationBranch(branch)) throw new GitHubError(422, `\"${branch}\" is not an exploration branch. Exploration branches are named explore/<name>.`);\n const issue = await gh.getIssue(n);\n const body = withRequestExploration(issue.body, branch);\n if (!body) throw new GitHubError(422, `#${n} has no Bridge request block, so it cannot be linked. Add \"exploration: ${branch}\" to it on GitHub.`);\n await gh.updateIssue(n, { body });\n const warnings: string[] = [];\n if (!(await gh.addLabels(n, [EXPLORATION_LABEL]))) warnings.push(`The ${EXPLORATION_LABEL} label could not be added to #${n}.`);\n let assignees: string[] = [];\n if (opts.assignee) {\n try {\n assignees = await gh.addAssignees(n, [opts.assignee.replace(/^@/, '')]);\n } catch {\n warnings.push(`@${opts.assignee.replace(/^@/, '')} could not be assigned to #${n}.`);\n }\n }\n return { number: n, branch, assignees, warnings };\n}\n\n/** Assigns someone to a request. Throws when GitHub does not keep the assignee (no access to the repository). */\nexport async function assignRequestOnGitHub(gh: GitHubClient, n: number, login: string): Promise<string[]> {\n const who = login.trim().replace(/^@/, '');\n if (!who) throw new GitHubError(422, 'Pick who should work on it.');\n const assignees = await gh.addAssignees(n, [who]);\n if (!assignees.some((a) => a.toLowerCase() === who.toLowerCase())) throw new GitHubError(422, `GitHub did not assign @${who}: they need access to this repository.`);\n return assignees;\n}\n\n/** Declines a request: the reason as a comment the requester is notified of, then the issue closed as not planned. */\nexport async function declineRequestOnGitHub(gh: GitHubClient, n: number, reason: string, by?: string | null): Promise<void> {\n const problems = declineReasonProblems(reason);\n if (problems.length) throw new GitHubError(422, problems.join(' '));\n await gh.addComment(n, declineComment(reason, by));\n await gh.updateIssue(n, { state: 'closed', state_reason: 'not_planned' });\n}\n","// Fidelity check: does a component built in Figma look like the code? Compares a Figma export of one variant with\n// an image of the same variant rendered from code (the Storybook reference images, see fidelity-references.ts).\n// Pure and dependency free: images are plain RGBA buffers, decoded by the caller (a canvas in the plugin, pngjs in\n// Node). The result shapes are JSON so a report can be stored and shown later (Studio Quality, follow-up).\n\n/** An RGBA image, 4 bytes per pixel, row by row (ImageData, pngjs and canvas all use this layout). */\nexport interface RgbaImage {\n width: number;\n height: number;\n data: Uint8Array | Uint8ClampedArray;\n}\n\nexport interface Size {\n width: number;\n height: number;\n}\n\nexport interface CompareOptions {\n /** Export scale of both images (device pixels per CSS pixel). Sizes are reported in CSS pixels. Default 2. */\n scale?: number;\n /**\n * Color distance under which two pixels are the same, 0 to 1 (YIQ, as pixelmatch). Default 0.1: absorbs gamma\n * and antialiasing ramps, catches a token swap (a gray one step away is about 0.12).\n */\n threshold?: number;\n /**\n * Neighborhood, in device pixels, searched for a matching pixel before one counts as different. Figma and Chrome\n * rasterize text and curves differently (glyph hinting, subpixel positions, corner antialiasing): a pixel that has\n * its twin within this distance is the same shape drawn half a pixel away. Default: one CSS pixel (= scale).\n */\n radius?: number;\n /** Largest share of different pixels, in percent, that still matches. Default 3. */\n maxPercent?: number;\n /** Largest size difference per side, in CSS pixels, that still matches. Default 1. */\n sizeTolerance?: number;\n /** Also return the diff overlay. Default true. */\n diffImage?: boolean;\n}\n\nexport interface ImageCompareResult {\n matches: boolean;\n /** Different pixels in percent of the larger canvas, two decimals. */\n percent: number;\n differentPixels: number;\n totalPixels: number;\n /** CSS pixel sizes (image size divided by the scale, rounded). */\n size: { figma: Size; code: Size };\n sizeMatches: boolean;\n /** The code image faded to gray with different pixels in red, on the larger canvas. */\n diff?: RgbaImage | undefined;\n}\n\nexport const FIDELITY_DEFAULTS = { scale: 2, threshold: 0.1, maxPercent: 3, sizeTolerance: 1 } as const;\n\n// Largest YIQ squared distance (black vs white), as in pixelmatch.\nconst MAX_DELTA = 35215;\n// Outside the overlap of two sizes: only near-white (transparent) pixels are the same.\nconst STRICT_THRESHOLD = 0.02;\n\n/** Pixel `i` of an image composited over white, or white outside the image. */\nfunction rgbAt(img: RgbaImage, x: number, y: number): [number, number, number] {\n if (x < 0 || y < 0 || x >= img.width || y >= img.height) return [255, 255, 255];\n const i = (y * img.width + x) * 4;\n const a = img.data[i + 3]! / 255;\n return [255 + (img.data[i]! - 255) * a, 255 + (img.data[i + 1]! - 255) * a, 255 + (img.data[i + 2]! - 255) * a];\n}\n\n/** YIQ squared distance between two opaque colors (pixelmatch's perceptual metric). */\nexport function colorDelta(a: [number, number, number], b: [number, number, number]): number {\n const dr = a[0] - b[0];\n const dg = a[1] - b[1];\n const db = a[2] - b[2];\n const y = dr * 0.29889531 + dg * 0.58662247 + db * 0.11448223;\n const i = dr * 0.59597799 - dg * 0.2741761 - db * 0.32180189;\n const q = dr * 0.21147017 - dg * 0.52261711 + db * 0.31114694;\n return 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q;\n}\n\n/** Whether color `c` appears in `img` within `radius` pixels of (x, y). */\nfunction foundNear(img: RgbaImage, x: number, y: number, c: [number, number, number], radius: number, max: number): boolean {\n for (let dy = -radius; dy <= radius; dy++) for (let dx = -radius; dx <= radius; dx++) if (colorDelta(c, rgbAt(img, x + dx, y + dy)) <= max) return true;\n return false;\n}\n\n/**\n * Compares a Figma export with the code reference of the same variant. A pixel differs when its color is not found\n * near the same place in the other image, in either direction: a shape drawn half a pixel away, or text rasterized\n * a little differently, matches; a missing border, another color, other padding or a different size does not.\n * Pixels outside the smaller image count as transparent: there, any visible color differs (a missing footer is a\n * difference even when its gray is light).\n */\nexport function compareImages(figma: RgbaImage, code: RgbaImage, options: CompareOptions = {}): ImageCompareResult {\n const scale = options.scale ?? FIDELITY_DEFAULTS.scale;\n const radius = Math.max(0, Math.round(options.radius ?? scale));\n const max = MAX_DELTA * (options.threshold ?? FIDELITY_DEFAULTS.threshold) ** 2;\n const strict = MAX_DELTA * STRICT_THRESHOLD ** 2;\n const width = Math.max(figma.width, code.width);\n const height = Math.max(figma.height, code.height);\n const total = width * height;\n const wantDiff = options.diffImage !== false;\n const out = wantDiff ? new Uint8ClampedArray(total * 4) : undefined;\n let different = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const a = rgbAt(figma, x, y);\n const b = rgbAt(code, x, y);\n // Where only one image has pixels (a size difference), any visible color counts: a light surface on white is\n // a missing part, not antialiasing.\n const m = x < Math.min(figma.width, code.width) && y < Math.min(figma.height, code.height) ? max : strict;\n const same = colorDelta(a, b) <= m || (foundNear(code, x, y, a, radius, m) && foundNear(figma, x, y, b, radius, m));\n if (!same) different++;\n if (out) {\n const o = (y * width + x) * 4;\n if (same) {\n // The code image, faded: light gray context for the red marks.\n const gray = 255 + ((b[0] * 0.299 + b[1] * 0.587 + b[2] * 0.114) - 255) * 0.1;\n out[o] = out[o + 1] = out[o + 2] = gray;\n } else {\n out[o] = 220;\n out[o + 1] = 38;\n out[o + 2] = 38;\n }\n out[o + 3] = 255;\n }\n }\n }\n const css = (img: RgbaImage): Size => ({ width: Math.round(img.width / scale), height: Math.round(img.height / scale) });\n const size = { figma: css(figma), code: css(code) };\n const tol = options.sizeTolerance ?? FIDELITY_DEFAULTS.sizeTolerance;\n const sizeMatches = Math.abs(size.figma.width - size.code.width) <= tol && Math.abs(size.figma.height - size.code.height) <= tol;\n const percent = total ? Math.round((different / total) * 10000) / 100 : 0;\n return {\n matches: sizeMatches && percent <= (options.maxPercent ?? FIDELITY_DEFAULTS.maxPercent),\n percent,\n differentPixels: different,\n totalPixels: total,\n size,\n sizeMatches,\n ...(out ? { diff: { width, height, data: out } } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------------------------\n// Report: what a check found, per component and variant. JSON, storable as is.\n\nexport type FidelityVariantStatus = 'matches' | 'differs' | 'skipped';\n\nexport interface FidelityVariantResult {\n /** Variant key, as the plugin stores it (\"Size=md, State=Default, Variant=primary\"). */\n key: string;\n status: FidelityVariantStatus;\n percent?: number | undefined;\n size?: { figma: Size; code: Size } | undefined;\n /** Skipped variants: why there is nothing to compare, in designer words. */\n reason?: string | undefined;\n}\n\nexport type FidelityComponentStatus = 'matches' | 'differs' | 'not-checked';\n\nexport interface FidelityComponentResult {\n component: string;\n status: FidelityComponentStatus;\n checked: number;\n differing: number;\n skipped: number;\n /** The variant that differs most (or matches least well). */\n worst?: { key: string; percent: number; size: { figma: Size; code: Size } } | undefined;\n /** Not checked at all: why. */\n reason?: string | undefined;\n variants: FidelityVariantResult[];\n}\n\nexport interface FidelityReport {\n version: 1;\n checkedAt: string;\n /** Figma file the sets were exported from. */\n file?: string | undefined;\n /** Commit the code images were made from. */\n reference: { sha: string; createdAt: string };\n options: { scale: number; threshold: number; radius: number; maxPercent: number; sizeTolerance: number };\n components: FidelityComponentResult[];\n summary: { components: number; matches: number; differs: number; notChecked: number; variantsChecked: number; variantsSkipped: number };\n}\n\n/** Rolls variant results up into one component result. */\nexport function summarizeComponent(component: string, variants: FidelityVariantResult[], reason?: string): FidelityComponentResult {\n const compared = variants.filter((v) => v.status !== 'skipped');\n const differing = compared.filter((v) => v.status === 'differs');\n const rank = (v: FidelityVariantResult) => (v.status === 'differs' ? 1000 : 0) + (v.percent ?? 0) + (v.size && !sameSize(v.size) ? 500 : 0);\n const worst = [...compared].sort((a, b) => rank(b) - rank(a))[0];\n return {\n component,\n status: compared.length === 0 ? 'not-checked' : differing.length ? 'differs' : 'matches',\n checked: compared.length,\n differing: differing.length,\n skipped: variants.length - compared.length,\n ...(worst && worst.size ? { worst: { key: worst.key, percent: worst.percent ?? 0, size: worst.size } } : {}),\n ...(compared.length === 0 ? { reason: reason ?? variants.find((v) => v.reason)?.reason } : {}),\n variants,\n };\n}\n\nconst sameSize = (s: { figma: Size; code: Size }) => s.figma.width === s.code.width && s.figma.height === s.code.height;\n\nexport function buildFidelityReport(input: {\n components: FidelityComponentResult[];\n reference: { sha: string; createdAt: string };\n options?: CompareOptions;\n file?: string;\n now?: Date;\n}): FidelityReport {\n const o = input.options ?? {};\n const scale = o.scale ?? FIDELITY_DEFAULTS.scale;\n const c = input.components;\n return {\n version: 1,\n checkedAt: (input.now ?? new Date()).toISOString(),\n ...(input.file ? { file: input.file } : {}),\n reference: input.reference,\n options: {\n scale,\n threshold: o.threshold ?? FIDELITY_DEFAULTS.threshold,\n radius: Math.round(o.radius ?? scale),\n maxPercent: o.maxPercent ?? FIDELITY_DEFAULTS.maxPercent,\n sizeTolerance: o.sizeTolerance ?? FIDELITY_DEFAULTS.sizeTolerance,\n },\n components: c,\n summary: {\n components: c.length,\n matches: c.filter((x) => x.status === 'matches').length,\n differs: c.filter((x) => x.status === 'differs').length,\n notChecked: c.filter((x) => x.status === 'not-checked').length,\n variantsChecked: c.reduce((n, x) => n + x.checked, 0),\n variantsSkipped: c.reduce((n, x) => n + x.skipped, 0),\n },\n };\n}\n\nconst fmtPercent = (p: number) => (p >= 10 ? `${Math.round(p)}%` : p >= 1 ? `${Math.round(p * 10) / 10}%` : p > 0 ? 'under 1%' : '0%');\nconst fmtSize = (s: Size) => `${s.width}x${s.height}`;\n\n/** One variant's verdict: \"Matches the code\" or \"Differs from the code: 12% of pixels, size 120x40 vs 118x40\". */\nexport function fidelityVerdict(v: Pick<FidelityVariantResult, 'status' | 'percent' | 'size' | 'reason'>): string {\n if (v.status === 'skipped') return `Not compared: ${v.reason ?? 'no image of the code'}`;\n if (v.status === 'matches') return 'Matches the code';\n const parts = [`${fmtPercent(v.percent ?? 0)} of pixels`];\n if (v.size && !sameSize(v.size)) parts.push(`size ${fmtSize(v.size.figma)} vs ${fmtSize(v.size.code)}`);\n return `Differs from the code: ${parts.join(', ')}`;\n}\n\n/** One component's line, from its worst variant. */\nexport function fidelityComponentLine(c: FidelityComponentResult): string {\n if (c.status === 'not-checked') return `Not compared: ${c.reason ?? 'no image of the code'}`;\n if (c.status === 'matches') return c.checked === 1 ? 'Matches the code' : `Matches the code (${c.checked} variants)`;\n const w = c.worst!;\n const head = fidelityVerdict({ status: 'differs', percent: w.percent, size: w.size });\n return c.checked > 1 ? `${head} (${c.differing} of ${c.checked} variants)` : head;\n}\n","// Code images for the fidelity check: which code render matches each generated Figma variant, and where the images\n// live. The generator (component-specs.ts) draws one Figma variant per axis combination; this module turns that same\n// spec back into props, content and a pseudo state, so the hidden Storybook story \"Internal/Figma reference\" renders\n// what the Figma variant should look like (same texts, icons and width). A variant that cannot be rendered the same\n// way is skipped with a reason, never guessed.\n//\n// Images are made on main by .github/workflows/figma-references.yml (bridge figma-references) and published to the\n// `bridge-visual` branch, the one Visual impact already publishes to, under figma-references/: manifest.json plus one\n// PNG per variant. The plugin reads them through the GitHub contents API with the token it already has.\n\nimport { variantKeyOf, type ComponentSpec, type ComponentSpecsFile, type SpecExample, type SpecPart, type SpecVariant } from './component-spec';\n\nexport const FIGMA_REFERENCES_BRANCH = 'bridge-visual';\nexport const FIGMA_REFERENCES_DIR = 'figma-references';\nexport const FIGMA_REFERENCES_MANIFEST = `${FIGMA_REFERENCES_DIR}/manifest.json`;\n/** Story id of packages/react/src/stories/FigmaReference.stories.tsx. */\nexport const FIGMA_REFERENCE_STORY = 'internal-figma-reference--variant';\n/** Width token of a block-level root in Figma (the plugin draws fill roots at this width: FILL_WIDTH_TOKEN). */\nexport const FIGMA_FILL_WIDTH_TOKEN = 'size.80';\n\nexport type ReferencePseudo = 'hover' | 'active' | 'focus-visible';\n\n/** What the reference story renders for one variant. JSON, passed to the story as a string arg. */\nexport interface ReferenceRender {\n /** Export name of the component (\"Button\", \"Card\"). */\n component: string;\n /** Props from the variant axes and the default property values (\"variant\": \"primary\", \"disabled\": true). */\n props: Record<string, unknown>;\n /** Text children (the Label property) of a simple component. */\n text?: string | undefined;\n /** Compound parts, in order: export name and text (\"CardHeader\", \"Header\"). */\n parts?: { component: string; text: string }[] | undefined;\n /** Icon props -> Lucide icon name (\"icon\": \"Pencil\"). */\n icons?: Record<string, string> | undefined;\n /** Hover, pressed or focus, forced with the pseudo-states addon classes. */\n pseudo?: ReferencePseudo | undefined;\n /** Width token path of the frame the component sits in, for roots that fill their container. */\n width?: string | undefined;\n /**\n * Children from the code example the set was drawn with (a table's rows, a form's fields): texts and design system\n * elements with their props, icons by name. Replaces `text` and `parts`.\n */\n children?: (string | SpecExample)[] | undefined;\n}\n\nexport type ReferencePlan = { ok: true; render: ReferenceRender } | { ok: false; reason: string };\n\nconst STATE_PSEUDO: Record<string, ReferencePseudo | 'rest' | 'disabled'> = {\n default: 'rest',\n rest: 'rest',\n enabled: 'rest',\n hover: 'hover',\n hovered: 'hover',\n pressed: 'active',\n active: 'active',\n focus: 'focus-visible',\n focused: 'focus-visible',\n 'focus visible': 'focus-visible',\n disabled: 'disabled',\n};\n\nconst iconName = (component: string) => component.replace(/^Icon\\//, '');\nconst exportName = (name: string) => name.replace(/[^A-Za-z0-9]+/g, '');\n\n/** How to render one generated variant from code, or why it cannot be compared. */\nexport function planReference(spec: ComponentSpec, variant: SpecVariant, file?: Pick<ComponentSpecsFile, 'slots'>): ReferencePlan {\n // A popup drawn open: the code image shows the component closed, so there is nothing to compare it with.\n if (spec.view === 'popup') return { ok: false, reason: 'drawn open in Figma; the code image shows it closed' };\n const props: Record<string, unknown> = { ...(spec.fixed ?? {}) };\n let pseudo: ReferencePseudo | undefined;\n for (const axis of spec.axes) {\n const value = variant.props[axis.name];\n if (value === undefined) return { ok: false, reason: `the variant has no ${axis.name} value` };\n if (axis.prop) {\n props[axis.prop] = value === 'true' ? true : value === 'false' ? false : value;\n continue;\n }\n // The Checked axis the generator draws from Base UI's checked state: the checked and indeterminate props.\n if (axis.name === 'Checked') {\n props.checked = value === 'true';\n if (value === 'mixed') props.indeterminate = true;\n continue;\n }\n if (axis.name.toLowerCase() !== 'state') return { ok: false, reason: `${axis.name} has no matching option in code` };\n const s = STATE_PSEUDO[value.toLowerCase()];\n if (!s) return { ok: false, reason: `the ${value} state has no code equivalent to render` };\n if (s === 'disabled') props.disabled = true;\n else if (s !== 'rest') pseudo = s;\n }\n\n const root = spec.parts.find((p) => !p.parent);\n if (!root) return { ok: false, reason: 'the spec has no root layer' };\n const children = (id: string) => spec.parts.filter((p) => p.parent === id);\n const textOf = (part: SpecPart): string | { reason: string } => {\n const swapTo = variant.slots?.[part.id] ?? part.swap?.default;\n if (part.swap && swapTo) {\n const slot = file?.slots?.find((s) => s.name === swapTo);\n if (!slot) return { reason: `${swapTo} is not in the specs` };\n if (slot.kind !== 'text' || !slot.text) return { reason: `Figma shows a placeholder (${swapTo}) that code has no example of` };\n return slot.text.default;\n }\n const prop = spec.properties.find((p) => p.name === part.text && p.type === 'TEXT');\n return typeof prop?.default === 'string' ? prop.default : part.name;\n };\n\n let text: string | undefined;\n const icons: Record<string, string> = {};\n for (const prop of spec.properties) {\n if (prop.type === 'TEXT') {\n // Optional content hidden by default (an input's prefix, a description): not passed, as Figma does not show it.\n const hidden = spec.properties.some((b) => b.type === 'BOOLEAN' && b.prop === prop.prop && b.default === false);\n if (hidden && prop.prop) continue;\n if (prop.prop === 'children') text = String(prop.default);\n else if (prop.prop) props[prop.prop] = String(prop.default);\n continue;\n }\n // BOOLEAN: an optional icon shown by default gets its icon below; any other default-on flag is a prop, unless the\n // content it shows is already passed (a description's text, an example's token name).\n const iconPart = spec.parts.find((p) => p.kind === 'icon' && p.visible === prop.name);\n if (prop.default === true && !iconPart && prop.prop && props[prop.prop] === undefined && spec.example?.p?.[prop.prop] === undefined) props[prop.prop] = true;\n }\n\n for (const part of spec.parts) {\n if (part.kind !== 'icon' || !part.swap) continue;\n const shown = part.visible ? spec.properties.find((p) => p.name === part.visible)?.default === true : true;\n if (!shown) continue;\n if (!part.swap.prop) return { ok: false, reason: `the ${part.name} icon has no matching option in code` };\n icons[part.swap.prop] = iconName(variant.slots?.[part.id] ?? part.swap.default);\n }\n\n // Texts that no prop carries: an input's placeholder, or a compound component's parts (CardHeader...).\n let parts: { component: string; text: string }[] | undefined;\n const loose = spec.properties.filter((p) => p.type === 'TEXT' && !p.prop);\n const frames = children(root.id).filter((p) => p.kind === 'frame');\n // Compound parts are frames named like their text (CardHeader's \"Header\") or holding a slot, not a field's box.\n const compound = text === undefined && frames.length > 0 && frames.every((f) => spec.parts.some((p) => p.parent === f.id && p.kind === 'text' && (p.swap || p.text === f.name)));\n if (compound) {\n parts = [];\n for (const f of frames) {\n const t = spec.parts.find((p) => p.parent === f.id && p.kind === 'text')!;\n const value = textOf(t);\n if (typeof value !== 'string') return { ok: false, reason: value.reason };\n parts.push({ component: `${exportName(spec.name)}${exportName(f.name)}`, text: value });\n }\n }\n for (const p of loose) {\n // A value display Base UI writes from the component's value (a progress percentage): code writes it too.\n if (p.name === 'Value') continue;\n const part = spec.parts.find((x) => x.text === p.name);\n if (compound && part && part.parent !== root.id) continue;\n if (part && /placeholder$/.test(part.id)) {\n props.placeholder = String(p.default);\n continue;\n }\n return { ok: false, reason: `the ${p.name} text has no matching option in code` };\n }\n\n // The code example the content came from: its props (the variant's own win) and children.\n const example = spec.example;\n const exampleChildren = example?.children?.length ? example.children : undefined;\n return {\n ok: true,\n render: {\n component: exportName(spec.view || spec.fixed || example ? (example?.c ?? spec.component ?? spec.name) : spec.name),\n props: { ...(example?.p ?? {}), ...props },\n ...(exampleChildren ? { children: exampleChildren } : {}),\n ...(text !== undefined && !exampleChildren ? { text } : {}),\n ...(parts && !exampleChildren ? { parts } : {}),\n ...(Object.keys(icons).length ? { icons } : {}),\n ...(pseudo ? { pseudo } : {}),\n ...(root.fill ? { width: FIGMA_FILL_WIDTH_TOKEN } : {}),\n },\n };\n}\n\n/** File name of a variant's image, stable and file safe: \"button/size-md__state-default__variant-primary.png\". */\nexport function referenceImagePath(component: string, key: string): string {\n const slug = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');\n const file = key\n .split(',')\n .map((kv) => slug(kv))\n .filter(Boolean)\n .join('__');\n return `${slug(component)}/${file || 'default'}.png`;\n}\n\nexport type FigmaReferenceEntry = { file: string; width: number; height: number } | { skipped: string };\n\nexport interface FigmaReferenceManifest {\n version: 1;\n tool: '@bridge-ds/visual';\n createdAt: string;\n /** Commit of the code the images were made from. */\n sha: string;\n /** Device pixels per CSS pixel, the scale the plugin exports Figma variants at. */\n scale: number;\n mode: { brand: string; theme: string; density: string };\n storyId: string;\n components: Record<string, { specHash: string; variants: Record<string, FigmaReferenceEntry> }>;\n}\n\n/** Every variant of every spec with its render plan (the capture's to-do list). */\nexport function planReferences(file: ComponentSpecsFile): { component: string; specHash: string; key: string; plan: ReferencePlan }[] {\n return file.components.flatMap((spec) =>\n spec.variants.map((v) => ({ component: spec.name, specHash: spec.hash, key: variantKeyOf(v.props), plan: planReference(spec, v, file) })),\n );\n}\n","// Review and merge rules shared by Bridge Studio, the MCP server and the CLI: one implementation of who may merge\n// a branch, what blocks it, the owner override and its audit comment, the review queue and the status of a branch.\n// Pure functions over GitHub REST shapes, no fetch, no DOM. Same rules as docs/GOVERNANCE.md: the highest tier wins,\n// Tier 2 and 3 need a design and a tech approval, nothing merges while tests fail. Who may ship comes from\n// `governance.rights` (rights.ts). Moved from the docs site (apps/docs-site/src/lib/review-rules.ts re-exports it).\nimport type { OverridePolicy } from './config';\nimport { isActiveExploration } from './explorations';\nimport { canShip, unreadableShipTeams, whoCanShipSentence, type ShipPolicy } from './rights';\nimport { classifyRisk, type RiskTier } from './risk';\n\nexport interface LabelLike {\n name: string;\n}\n\n/** Tier from labels (`tier-3`, `tier: 3`, `risk:3`), the PR template checkbox (`- [x] Tier 3`) or a `Risk tier: 3` line. Highest wins. */\nexport function parseTier(labels: LabelLike[], body: string | null | undefined): RiskTier | null {\n const found: number[] = [];\n for (const l of labels) {\n const m = l.name.match(/^(?:risk[\\s:-]*)?tier[\\s:_-]*([123])\\b/i) ?? l.name.match(/^risk[\\s:_-]*([123])$/i);\n if (m) found.push(Number(m[1]));\n }\n for (const m of (body ?? '').matchAll(/-\\s*\\[[xX]\\]\\s*\\**\\s*Tier\\s*([123])\\b/g)) found.push(Number(m[1]));\n // \"**Risk tier:** 3, high\" or \"Risk tier: Tier 2\"\n for (const m of (body ?? '').matchAll(/risk tier\\W{0,6}(?:tier\\s*)?([123])\\b/gi)) found.push(Number(m[1]));\n return found.length ? (Math.max(...found) as RiskTier) : null;\n}\n\n/** What GitHub returns about a pull request's lifecycle. `merged_at` is set once merged; `state` is then \"closed\". */\nexport interface PullStateLike {\n state?: string;\n draft?: boolean;\n merged?: boolean;\n merged_at?: string | null;\n}\n\nexport type PullState = 'merged' | 'closed' | 'draft' | 'open';\n\n/** Merged wins over closed (GitHub reports merged pull requests as closed), closed over draft, draft over open. */\nexport function pullState(p: PullStateLike): PullState {\n if (p.merged_at || p.merged) return 'merged';\n if (p.state && p.state !== 'open') return 'closed';\n if (p.draft) return 'draft';\n return 'open';\n}\n\n/** Label and pill tone of each state, for list and detail views. */\nexport const PULL_STATE_PILL: Record<PullState, { label: string; cls: string }> = {\n merged: { label: 'Merged', cls: '' },\n closed: { label: 'Closed', cls: '' },\n draft: { label: 'Draft', cls: '' },\n open: { label: 'Open', cls: '' },\n};\n\n/** Pull requests still waiting for review (open or draft): merged and closed ones never count as open reviews. */\nexport function openPulls<P extends PullStateLike>(pulls: P[]): P[] {\n return pulls.filter((p) => {\n const s = pullState(p);\n return s === 'open' || s === 'draft';\n });\n}\n\nexport interface CiRunLike {\n name: string;\n status: 'queued' | 'in_progress' | 'completed' | string;\n conclusion: string | null;\n html_url?: string;\n}\n\nexport interface CiStatusLike {\n context: string;\n state: 'success' | 'failure' | 'error' | 'pending' | string;\n target_url?: string | null;\n}\n\nexport type CiState = 'pass' | 'fail' | 'pending' | 'none';\n\nexport interface CiSummary {\n state: CiState;\n total: number;\n passed: number;\n failed: { name: string; url?: string }[];\n pending: { name: string; url?: string }[];\n}\n\nconst OK = new Set(['success', 'neutral', 'skipped']);\n\n/** Combines check runs and commit statuses into one verdict. Any failure wins over pending. */\nexport function summarizeCi(runs: CiRunLike[], statuses: CiStatusLike[] = []): CiSummary {\n const failed: CiSummary['failed'] = [];\n const pending: CiSummary['pending'] = [];\n let passed = 0;\n for (const r of runs) {\n if (r.status !== 'completed') pending.push({ name: r.name, url: r.html_url });\n else if (r.conclusion && OK.has(r.conclusion)) passed++;\n else failed.push({ name: r.name, url: r.html_url });\n }\n // Statuses repeat per context; the first one is the latest.\n const seen = new Set<string>();\n for (const s of statuses) {\n if (seen.has(s.context)) continue;\n seen.add(s.context);\n if (s.state === 'success') passed++;\n else if (s.state === 'pending') pending.push({ name: s.context, url: s.target_url ?? undefined });\n else failed.push({ name: s.context, url: s.target_url ?? undefined });\n }\n const total = passed + failed.length + pending.length;\n const state: CiState = total === 0 ? 'none' : failed.length ? 'fail' : pending.length ? 'pending' : 'pass';\n return { state, total, passed, failed, pending };\n}\n\nexport interface ReviewLike {\n user: { login: string } | null;\n state: 'APPROVED' | 'CHANGES_REQUESTED' | 'COMMENTED' | 'DISMISSED' | 'PENDING' | string;\n submitted_at?: string | null;\n}\n\nexport interface ApprovalSummary {\n approvers: string[];\n changesRequested: string[];\n design: boolean;\n tech: boolean;\n}\n\n/** Latest decisive review per person (comments do not reset an approval), then owner coverage. */\nexport function summarizeApprovals(reviews: ReviewLike[], owners: { design: string[]; tech: string[] }, author?: string): ApprovalSummary {\n const latest = new Map<string, string>();\n const sorted = [...reviews].sort((a, b) => String(a.submitted_at ?? '').localeCompare(String(b.submitted_at ?? '')));\n for (const r of sorted) {\n const login = r.user?.login;\n if (!login || login === author) continue;\n if (r.state === 'APPROVED' || r.state === 'CHANGES_REQUESTED' || r.state === 'DISMISSED') latest.set(login, r.state);\n }\n const approvers = [...latest].filter(([, s]) => s === 'APPROVED').map(([l]) => l);\n const changesRequested = [...latest].filter(([, s]) => s === 'CHANGES_REQUESTED').map(([l]) => l);\n const lower = (xs: string[]) => xs.map((x) => x.toLowerCase().replace(/^@/, ''));\n const d = lower(owners.design);\n const t = lower(owners.tech);\n const a = lower(approvers);\n let design: boolean;\n let tech: boolean;\n if (d.length || t.length) {\n design = d.length ? a.some((x) => d.includes(x)) : a.length > 0;\n // One person holding both roles cannot cover both approvals alone.\n const soloBoth = (x: string) => a.length === 1 && d.includes(x);\n tech = t.length ? a.some((x) => t.includes(x) && !soloBoth(x)) : a.length > 1;\n } else {\n // No owners configured: two distinct approvers stand in for design and tech.\n design = a.length >= 1;\n tech = a.length >= 2;\n }\n return { approvers, changesRequested, design, tech };\n}\n\nexport type MissingApproval = 'design approval' | 'tech approval' | 'approval';\n\nexport interface MergeGate {\n allowed: boolean;\n reasons: string[];\n /** True when the only failing reasons are missing approvals and the viewer is in `governance.override.allowed`. */\n overridable: boolean;\n /** Approvals still missing, in the words the override comment uses. */\n missing: MissingApproval[];\n /** Whether the viewer holds the right to ship (true when no rule singles anyone out or the viewer is unknown). */\n canShip: boolean;\n}\n\nconst normLogin = (x: string) => x.trim().toLowerCase().replace(/^@/, '');\n\n/** Whether `login` may use the owner override. Case-insensitive, a leading @ is ignored. */\nexport function canOverride(login: string | null | undefined, policy: OverridePolicy | null | undefined): boolean {\n if (!login || !policy?.allowed.length) return false;\n return policy.allowed.map(normLogin).includes(normLogin(login));\n}\n\n/**\n * Whether the Merge button is enabled, and why not. Mirrors docs/GOVERNANCE.md.\n * The owner override only ever covers missing approvals: CI failing or running, changes requested, a draft,\n * a closed pull request or a merge conflict always block, for everyone.\n */\nexport function mergeGate(input: {\n tier: RiskTier | null;\n ci: CiSummary;\n approvals: ApprovalSummary;\n draft: boolean;\n mergeable?: boolean | null;\n state: string;\n merged_at?: string | null;\n /** Login of the connected viewer (GitHub /user). */\n viewer?: string | null;\n override?: OverridePolicy | null;\n /** A running exploration (label `exploration`): never merged as is, whatever else is green. */\n exploration?: boolean;\n /** Who may ship (shipPolicy from governance.rights). null or absent: anyone with write access. */\n ship?: ShipPolicy | null;\n}): MergeGate {\n const blocking: string[] = [];\n const missing: MissingApproval[] = [];\n const approvalReasons: string[] = [];\n const lifecycle = pullState(input);\n if (lifecycle === 'merged') blocking.push('This branch is already merged.');\n else if (lifecycle === 'closed') blocking.push('This branch is closed.');\n if (input.exploration && lifecycle !== 'merged' && lifecycle !== 'closed') blocking.push('It is an exploration: promote it to review first.');\n if (input.draft) blocking.push('It is a draft. Mark it ready for review on GitHub first.');\n if (input.ci.state === 'fail') blocking.push(`Tests fail: ${input.ci.failed.map((f) => f.name).join(', ')}.`);\n if (input.ci.state === 'pending') blocking.push('Tests are still running.');\n if (input.approvals.changesRequested.length) blocking.push(`Changes requested by @${input.approvals.changesRequested.join(', @')}.`);\n const tier = input.tier ?? 3;\n // docs/GOVERNANCE.md: Tier 2 (new component, variant or prop) and Tier 3 need a design and a tech owner approval.\n if (tier >= 2) {\n if (!input.approvals.design) {\n approvalReasons.push('It needs a design owner approval.');\n missing.push('design approval');\n }\n if (!input.approvals.tech) {\n approvalReasons.push('It needs a tech owner approval.');\n missing.push('tech approval');\n }\n } else if (!input.approvals.approvers.length) {\n approvalReasons.push('It needs one approval.');\n missing.push('approval');\n }\n const conflict = input.mergeable === false ? [CONFLICT_REASON] : [];\n // Only a known viewer is checked: without a login the Merge button asks to connect first anyway.\n const shipper = !input.viewer || canShip(input.viewer, input.ship);\n // A team holding the right that GitHub would not show: say why and how to fix it, never treat it as empty.\n const ship = !shipper && lifecycle !== 'merged' && lifecycle !== 'closed' ? [whoCanShipSentence(input.ship!), ...unreadableShipTeams(input.ship).map((t) => (t.status === 'unreadable' ? t.message : ''))] : [];\n // Order: state, draft, CI, changes requested, approvals, who ships, conflict.\n const reasons = [...blocking, ...approvalReasons, ...ship, ...conflict];\n const allowed = reasons.length === 0;\n // The override skips approvals only: it never lets someone ship who does not hold the right.\n const overridable = !allowed && blocking.length + conflict.length + ship.length === 0 && missing.length > 0 && canOverride(input.viewer, input.override);\n return { allowed, reasons, overridable, missing, canShip: shipper };\n}\n\n/** The gate reason of a conflict, in the words a designer reads. Detected by identity, never by regex. */\nexport const CONFLICT_REASON = 'It conflicts with main: resolve it with Update from main on the branch.';\n\nexport const OVERRIDE_HEADING = '**Bridge owner override**';\n\n/** Problem with an override reason, or null when it is accepted. */\nexport function overrideReasonProblem(reason: string, policy: OverridePolicy): string | null {\n if (!policy.requireReason) return null;\n const n = reason.trim().length;\n if (n === 0) return `Write why this merges without the missing approvals, in at least ${policy.minReasonLength} characters.`;\n if (n < policy.minReasonLength) return `Write at least ${policy.minReasonLength} characters (${n} so far), so the history says why.`;\n return null;\n}\n\n/**\n * The audit comment posted on the pull request before an override merge. Stable format: History and the PR\n * timeline find it by its first line, `**Bridge owner override**`, and read it back with parseOverrideComment.\n */\nexport function overrideComment(login: string, reason: string, missing: MissingApproval[]): string {\n const why = reason.trim().replace(/\\s+/g, ' ').replace(/[.\\s]+$/, '');\n return `${OVERRIDE_HEADING}\\n\\nOwner override by @${normLogin(login)}: ${why || 'no reason given'}. Missing: ${missing.join(', ')}. Merged from Bridge.`;\n}\n\n/** The comment body after GitHub refused the merge, so the audit trail does not claim a merge that never happened. */\nexport function overrideRefusedComment(body: string, message: string): string {\n return body.replace(/ Merged from Bridge\\.$/, ` Merge refused by GitHub: ${message.trim().replace(/[.\\s]+$/, '')}. Not merged.`);\n}\n\nexport interface OverrideRecord {\n login: string;\n reason: string;\n missing: string[];\n merged: boolean;\n}\n\n/** Reads an override comment back; null for any other comment. */\nexport function parseOverrideComment(body: string | null | undefined): OverrideRecord | null {\n const text = (body ?? '').trim();\n if (!text.startsWith(OVERRIDE_HEADING)) return null;\n const m = text.match(/Owner override by @([\\w-]+): ([\\s\\S]*?)\\. Missing: ([^.]*)\\. (Merged from Bridge\\.|Merge refused by GitHub)/);\n if (!m) return null;\n return { login: m[1]!, reason: m[2]!, missing: m[3]!.split(/,\\s*/).filter(Boolean), merged: m[4]!.startsWith('Merged') };\n}\n\nexport type MergeMethod = 'squash' | 'merge' | 'rebase';\n\n/** Merge methods the repo allows, squash first. Unknown settings (no push access) count as allowed. */\nexport function allowedMergeMethods(repo: { allow_squash_merge?: boolean; allow_merge_commit?: boolean; allow_rebase_merge?: boolean } | null | undefined): MergeMethod[] {\n const out: MergeMethod[] = [];\n if (repo?.allow_squash_merge !== false) out.push('squash');\n if (repo?.allow_merge_commit !== false) out.push('merge');\n if (repo?.allow_rebase_merge !== false) out.push('rebase');\n return out;\n}\n\n/** Whether the viewer can write to the repo, from `permissions` on GET /repos/{owner}/{repo} with their token. */\nexport function hasWriteAccess(perms: { admin?: boolean; maintain?: boolean; push?: boolean } | null | undefined): boolean {\n return Boolean(perms && (perms.admin || perms.maintain || perms.push));\n}\n\nexport type ReviewStatusKind =\n | 'merged'\n | 'closed'\n | 'draft'\n | 'ci-failing'\n | 'changes-requested'\n | 'ci-running'\n | 'needs-design'\n | 'needs-tech'\n | 'needs-approval'\n | 'conflict'\n | 'checking'\n | 'ready'\n | 'unknown';\n\n/**\n * Sort order for a \"needs you\" list, most urgent first: what blocks the merge, then what waits for an approval,\n * then what is ready, then running checks and unknown ones, drafts and finished ones last. Lower comes first.\n */\nexport const REVIEW_STATUS_ORDER: Record<ReviewStatusKind, number> = {\n 'ci-failing': 0,\n conflict: 1,\n 'changes-requested': 2,\n 'needs-design': 3,\n 'needs-tech': 4,\n 'needs-approval': 5,\n ready: 6,\n 'ci-running': 7,\n checking: 8,\n unknown: 9,\n draft: 10,\n merged: 11,\n closed: 12,\n};\n\n/**\n * One status chip for a pull request, from real data. Same rules and order as the pull request header\n * (lib/changes needFromDetail): lifecycle, draft, CI failing, changes requested, merge conflict, CI running, then\n * missing approvals (Tier 3 by default), then ready. `mergeable` null means GitHub has not computed it yet: the chip\n * reads \"Checking\" instead of an approval or \"Ready to ship\", so a list never says something the detail contradicts.\n * Undefined means it was not read: no conflict known. `ready` is returned only when mergeGate allows the merge.\n * Unknown CI or reviews (null, still loading or failed) never read as ready.\n */\nexport function reviewStatusKind(input: {\n state?: string;\n draft?: boolean;\n merged_at?: string | null;\n ci: CiSummary | null;\n approvals: ApprovalSummary | null;\n tier: RiskTier | null;\n mergeable?: boolean | null;\n}): ReviewStatusKind {\n const out = (kind: ReviewStatusKind): ReviewStatusKind => kind;\n const lifecycle = pullState(input);\n if (lifecycle === 'merged') return out('merged');\n if (lifecycle === 'closed') return out('closed');\n if (lifecycle === 'draft') return out('draft');\n if (input.ci?.state === 'fail') return out('ci-failing');\n if (input.approvals?.changesRequested.length) return out('changes-requested');\n if (input.mergeable === false) return out('conflict');\n if (input.ci?.state === 'pending') return out('ci-running');\n if (!input.ci || !input.approvals) return out('unknown');\n if (input.mergeable === null) return out('checking');\n const tier = input.tier ?? 3;\n if (tier >= 2) {\n if (!input.approvals.design) return out('needs-design');\n if (!input.approvals.tech) return out('needs-tech');\n } else if (!input.approvals.approvers.length) return out('needs-approval');\n const gate = mergeGate({ tier: input.tier, ci: input.ci, approvals: input.approvals, draft: Boolean(input.draft), mergeable: input.mergeable, state: input.state ?? 'open', merged_at: input.merged_at });\n return gate.allowed ? out('ready') : out('unknown');\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// The review queue: which open pull requests wait for a review. Left out: running explorations (tried, never merged\n// as is) and GitHub automation (the changesets release pull request, anything github-actions[bot] opened).\n\nexport interface QueuePull extends PullStateLike {\n state: string;\n labels?: ({ name?: string } | string)[];\n head: { ref: string };\n user?: { login: string; type?: string } | null;\n}\n\nconst BOTS = new Set(['github-actions[bot]', 'app/github-actions', 'changeset-bot[bot]']);\n\n/** The changesets release pull request (\"Version packages\"), on a changeset-release/* branch. */\nexport const isReleasePull = (p: Pick<QueuePull, 'head'>) => p.head.ref.startsWith('changeset-release/');\n\n/** Opened by GitHub automation, not by a person: the release pull request or anything github-actions[bot] opened. */\nexport function isAutomationPull(p: Pick<QueuePull, 'head' | 'user'>): boolean {\n return isReleasePull(p) || BOTS.has((p.user?.login ?? '').toLowerCase());\n}\n\n/** A running exploration: open and labeled exploration. */\nconst runningExploration = (p: Pick<QueuePull, 'state' | 'labels'>) => p.state === 'open' && isActiveExploration((p.labels ?? []) as never);\n\n/** The open pull requests that wait for a review, in the order given. Every count in the Studio comes from here. */\nexport function reviewQueue<P extends QueuePull>(pulls: P[]): P[] {\n return openPulls(pulls).filter((p) => !isAutomationPull(p) && !runningExploration(p));\n}\n\n/** The open release pull request, if the changesets action opened one. */\nexport function releasePull<P extends QueuePull>(pulls: P[]): P | null {\n return openPulls(pulls).find((p) => isReleasePull(p)) ?? null;\n}\n\n/**\n * The approval a change needs, the same rule everywhere: the tier the author set (label, PR template checkbox or\n * \"Risk tier\" line) or the one the shared classifier computes from the changed files, highest wins. Without files\n * (not read yet) only a label counts, and a missing label stays unknown.\n */\nexport function effectiveTier(labels: LabelLike[], body: string | null | undefined, files: { filename: string; status?: string }[] | null): RiskTier | null {\n const labelled = parseTier(labels, body);\n if (!files) return labelled;\n const computed = classifyRisk({ files: files.map((f) => ({ path: f.filename, status: f.status })) }).tier;\n return Math.max(labelled ?? 0, computed) as RiskTier;\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Reopen\n\nexport type ReopenEligibility =\n /** The branch is still there: the change can be reopened as it was. */\n | { kind: 'reopen' }\n /** The branch is gone: nothing to reopen, but its token edits can start a new change. */\n | { kind: 'gone' }\n /** Not closed, or not the viewer's to reopen, or not known yet. */\n | { kind: 'none' };\n\nconst norm = (x: string) => x.trim().toLowerCase().replace(/^@/, '');\n\n/**\n * Whether the viewer can reopen a closed change: only a change closed without shipping, only its author or an owner\n * (governance.owners, both roles), and only someone GitHub lets write (write access, or the author). `branch` is what\n * GitHub said about the head branch: there, removed, or not read.\n */\nexport function reopenEligibility(x: {\n state: PullState;\n viewer: string | null;\n author: string;\n owners: string[];\n canWrite: boolean;\n branch: 'exists' | 'gone' | 'unknown';\n}): ReopenEligibility {\n if (x.state !== 'closed' || !x.viewer) return { kind: 'none' };\n const isAuthor = norm(x.viewer) === norm(x.author);\n const isOwner = x.owners.some((o) => norm(o) === norm(x.viewer!));\n if (!isAuthor && !isOwner) return { kind: 'none' };\n if (!x.canWrite && !isAuthor) return { kind: 'none' };\n if (x.branch === 'exists') return { kind: 'reopen' };\n if (x.branch === 'gone') return { kind: 'gone' };\n return { kind: 'none' };\n}\n\n\n// ---------------------------------------------------------------------------------------------------------------\n// Who still approves, and who else to ask (\"Ask someone else to review\" in the review queue)\n\nexport type ApprovalRole = 'design' | 'tech' | 'approval';\n\nconst NO_CI: CiSummary = { state: 'pass', total: 0, passed: 0, failed: [], pending: [] };\nconst ROLE_OF_MISSING: Record<MissingApproval, ApprovalRole> = { 'design approval': 'design', 'tech approval': 'tech', approval: 'approval' };\n\n/** The approvals a tier needs, as mergeGate counts them (Tier 2 and 3: design and tech; Tier 1: one approval). */\nexport function requiredApprovals(tier: RiskTier | null): ApprovalRole[] {\n return mergeGate({ tier, ci: NO_CI, approvals: { approvers: [], changesRequested: [], design: false, tech: false }, draft: false, state: 'open' }).missing.map((m) => ROLE_OF_MISSING[m]);\n}\n\n/** The approvals still missing on a branch, from its tier and the reviews read (empty when either is unknown). */\nexport function pendingApprovals(tier: RiskTier | null | undefined, approvals: ApprovalSummary | null | undefined): ApprovalRole[] {\n if (tier == null || !approvals) return [];\n return mergeGate({ tier, ci: NO_CI, approvals, draft: false, state: 'open' }).missing.map((m) => ROLE_OF_MISSING[m]);\n}\n\nconst uniqLogins = (xs: string[]) => xs.filter((x, i) => xs.findIndex((y) => normLogin(y) === normLogin(x)) === i);\n\n/**\n * Who can still give an approval: the owners listed for the role (both lists for a plain approval) minus the author\n * and anyone who already approved. `open`: the config lists nobody for the role, so any reviewer but the author counts.\n */\nexport function eligibleReviewers(role: ApprovalRole, p: { owners: { design: string[]; tech: string[] }; author: string; approvers?: string[] | undefined }): { open: boolean; logins: string[]; listed: string[] } {\n const raw = role === 'design' ? p.owners.design : role === 'tech' ? p.owners.tech : uniqLogins([...p.owners.design, ...p.owners.tech]);\n const listed = raw.map((x) => x.replace(/^@/, ''));\n const approvers = (p.approvers ?? []).map(normLogin);\n const logins = listed.filter((l) => normLogin(l) !== normLogin(p.author) && !approvers.includes(normLogin(l)));\n return { open: listed.length === 0, logins, listed };\n}\n\n/**\n * \"Ask someone else to review\": the other people who can give the missing approvals, never the viewer or the author.\n * Empty when nobody else can (the caller says to review it or to add a reviewer in Settings).\n */\nexport function reviewersToAsk(x: { tier: RiskTier | null; approvals: ApprovalSummary; owners: { design: string[]; tech: string[] }; author: string; viewer: string | null | undefined }): string[] {\n const roles = pendingApprovals(x.tier, x.approvals);\n const all = roles.flatMap((r) => eligibleReviewers(r, { owners: x.owners, author: x.author, approvers: x.approvals.approvers }).logins);\n return uniqLogins(all).filter((l) => normLogin(l) !== normLogin(x.viewer ?? '') && normLogin(l) !== normLogin(x.author));\n}\n","// Update a branch from main (\"bring in the latest library\"), shared by Bridge Studio, the MCP server and the CLI.\n// Reads how far a branch is behind and what both sides touched since they parted; when nothing conflicts, GitHub's\n// update-branch; when only token files conflict, a merge commit with the person's token choices (\"keep mine\" or\n// \"use main's\", core token-merge); anything in code stays with a developer. One implementation over the core\n// GitHub client: Studio passes its own client (studioClient), the MCP server and the CLI theirs.\nimport { loadConfig, DEFAULT_TOKEN_PATHS, type BridgeConfig } from './config';\nimport type { GitHubClient, TreeEntry } from './github-client';\nimport { buildTokenSet, layoutOptions, type LayoutOptions, type TokenSet } from './token-set';\nimport { parseContrastChecks, type ContrastPair } from './wcag';\nimport { applyTokenMerge, choiceFor, planTokenMerge, type MergeChoices, type TokenMergeConflict, type TokenMergeInput, type TokenMergePlan } from './token-merge';\n\nconst plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;\n\n/** A file of a compare (GET /repos/{o}/{r}/compare/{base}...{head}). */\nexport interface CompareFile {\n filename: string;\n status: string;\n previous_filename?: string | undefined;\n sha?: string | null | undefined;\n}\n\n/** Every path a compare file names: a renamed file counts under its old name too. */\nconst names = (files: CompareFile[]) => files.flatMap((f) => (f.previous_filename ? [f.filename, f.previous_filename] : [f.filename]));\n\n/** Files both the branch and main changed since they parted, split into token files and the rest (code). */\nexport function overlap(changeFiles: CompareFile[], libraryFiles: CompareFile[], isTokenFile: (path: string) => boolean): { tokenFiles: string[]; codeFiles: string[] } {\n const lib = new Set(names(libraryFiles));\n const both = [...new Set(names(changeFiles).filter((f) => lib.has(f)))].sort();\n return { tokenFiles: both.filter(isTokenFile), codeFiles: both.filter((f) => !isTokenFile(f)) };\n}\n\n/** GitHub lists at most 300 files per compare: past that, Bridge cannot know what both sides touched. */\nexport const COMPARE_FILE_LIMIT = 300;\n\nexport type ConflictRoute = { kind: 'tokens'; files: string[] } | { kind: 'code'; alsoTokens: boolean; files: string[] };\n\n/**\n * Who resolves the conflict. Only token files on both sides: the designer, in Bridge. Any code file on both sides, a\n * file list GitHub cut short, or no shared file at all (GitHub saw a conflict Bridge cannot explain): a developer.\n */\nexport function conflictRoute(o: { tokenFiles: string[]; codeFiles: string[] }, opts: { truncated?: boolean } = {}): ConflictRoute {\n if (opts.truncated || (!o.tokenFiles.length && !o.codeFiles.length)) return { kind: 'code', alsoTokens: false, files: [] };\n if (o.codeFiles.length) return { kind: 'code', alsoTokens: o.tokenFiles.length > 0, files: o.codeFiles };\n return { kind: 'tokens', files: o.tokenFiles };\n}\n\n/** A rule from GET /repos/{o}/{r}/rules/branches/{branch}. */\nexport interface BranchRuleLike {\n type: string;\n parameters?: { dismiss_stale_reviews_on_push?: boolean } | null;\n}\n\n/**\n * Whether GitHub dismisses approvals when new commits arrive, from the rules that apply to the library branch. True\n * or false when a pull request rule says so; null when no rule says (classic branch protection is not readable\n * without admin rights).\n */\nexport function dismissStaleFrom(rules: BranchRuleLike[] | null | undefined): boolean | null {\n const pr = (rules ?? []).filter((r) => r.type === 'pull_request');\n if (!pr.length) return null;\n return pr.some((r) => r.parameters?.dismiss_stale_reviews_on_push === true);\n}\n\n/** The commit message of the resolution, so History and the branch say what the person chose. */\nexport function resolutionMessage(input: { library: string; conflicts: TokenMergeConflict[]; choices: MergeChoices; who?: string | null | undefined }): string {\n const lines = input.conflicts.map((c) => `- ${c.path} (${c.file}): ${choiceFor(c, input.choices) === 'theirs' ? `used the ${input.library} value` : 'kept this change'}`);\n const title = input.conflicts.length ? `Bring in the latest ${input.library} and resolve ${plural(input.conflicts.length, 'token conflict')}` : `Bring in the latest ${input.library}`;\n const by = input.who ? `\\n\\nResolved in Bridge by @${input.who.replace(/^@/, '')}.` : '\\n\\nResolved in Bridge.';\n return `${title}${lines.length ? `\\n\\n${lines.join('\\n')}` : ''}${by}`;\n}\n\nexport type LibraryState = 'current' | 'behind' | 'conflict' | 'unknown';\n\nexport interface Freshness {\n state: LibraryState;\n /** Library updates (commits on the library branch) since the change started; null when not read. */\n behindBy: number | null;\n /** The commit the change and the library share. */\n mergeBase: string | null;\n}\n\n/**\n * How the change stands against the latest library. A conflict (mergeable false) wins: GitHub cannot combine them.\n * Otherwise it is behind when the library has commits the change has not. A shipped or closed change has nothing to\n * bring in. A compare that could not be read says unknown, never \"up to date\".\n */\nexport function freshness<C extends { behind_by?: number | undefined; merge_base_commit?: { sha: string } | null | undefined }>(input: { compare: C | null | undefined; mergeable: boolean | null | undefined; open: boolean }): Freshness {\n const behindBy = typeof input.compare?.behind_by === 'number' ? input.compare.behind_by : null;\n const mergeBase = input.compare?.merge_base_commit?.sha ?? null;\n if (!input.open) return { state: 'current', behindBy, mergeBase };\n if (input.mergeable === false) return { state: 'conflict', behindBy, mergeBase };\n if (behindBy === null) return { state: 'unknown', behindBy, mergeBase };\n return { state: behindBy > 0 ? 'behind' : 'current', behindBy, mergeBase };\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Reads and writes over the core GitHub client\n\n/** The compare of main and a branch head, in the shape the conflict reader needs (client.compareDetailed). */\nexport interface LibraryCompare {\n mergeBase: string | null;\n baseSha: string | null;\n baseTree: string | null;\n files: CompareFile[];\n}\n\nexport interface LibraryConflicts {\n route: ConflictRoute;\n /** Present for a pure token-file conflict. */\n tokens?: {\n root: string;\n plan: TokenMergePlan;\n input: TokenMergeInput;\n sets: { base: TokenSet; mine: TokenSet; theirs: TokenSet };\n /** Every token file of each side, relative to the tokens root. */\n mineFiles: Record<string, string>;\n theirsFiles: Record<string, string>;\n pairs: ContrastPair[];\n options: LayoutOptions;\n };\n /** What the commit needs: main's tip and its tree, the branch head tree and its own files. */\n write?: { mainSha: string; mainTree: string; headSha: string; headTree: Map<string, TreeEntry>; changeFiles: CompareFile[] };\n}\n\nconst withoutRoot = (root: string, p: string) => (root && p.startsWith(`${root}/`) ? p.slice(root.length + 1) : p);\n\nasync function treeAt(gh: GitHubClient, sha: string): Promise<Map<string, TreeEntry>> {\n const t = await gh.getTree(await gh.getCommitTree(sha));\n if (t.truncated) throw new Error('This repository is too big for Bridge to read in one go. A developer resolves the conflict on GitHub.');\n return new Map(t.entries.filter((e) => e.type === 'blob').map((e) => [e.path, e]));\n}\n\nasync function textAt(gh: GitHubClient, sha: string, path: string): Promise<string> {\n return (await gh.readFile(path, sha)) ?? '';\n}\n\nasync function tokenFilesAt(gh: GitHubClient, sha: string, root: string, tree: Map<string, TreeEntry>): Promise<Record<string, string>> {\n const prefix = root ? `${root}/` : '';\n const paths = [...tree.keys()].filter((p) => p.startsWith(prefix) && p.endsWith('.tokens.json'));\n return Object.fromEntries(await Promise.all(paths.map(async (p) => [withoutRoot(root, p), await textAt(gh, sha, p)] as const)));\n}\n\nasync function configAt(gh: GitHubClient, sha: string, tree: Map<string, TreeEntry>): Promise<BridgeConfig | null> {\n if (!tree.has('bridge.config.json')) return null;\n try {\n return loadConfig(await textAt(gh, sha, 'bridge.config.json'));\n } catch {\n return null;\n }\n}\n\n/**\n * What conflicts and who resolves it. Reads the files main changed since the branch started (one compare), then, for\n * a pure token-file conflict, the token files at the shared start, in the branch and in main. `tokensRoot` is the\n * best guess before the config is read (Studio: its site config); `contrastFallback` the contrast checks to use when\n * main has none.\n */\nexport async function readLibraryConflicts(\n gh: GitHubClient,\n compare: LibraryCompare,\n headSha: string,\n opts: { tokensRoot?: string | undefined; contrastFallback?: string | undefined } = {},\n): Promise<LibraryConflicts> {\n const { mergeBase, baseSha: mainSha, baseTree: mainTree } = compare;\n const changeFiles = compare.files;\n if (!mergeBase || !mainSha || !mainTree) return { route: conflictRoute({ tokenFiles: [], codeFiles: [] }) };\n const library = (await gh.compareDetailed(mergeBase, mainSha)).files;\n const truncated = changeFiles.length >= COMPARE_FILE_LIMIT || library.length >= COMPARE_FILE_LIMIT;\n // The tokens root guess first: the config of main confirms it before anything is written.\n const guess = opts.tokensRoot ?? DEFAULT_TOKEN_PATHS.root;\n const route = conflictRoute(\n overlap(changeFiles, library, (p) => p.endsWith('.tokens.json') && p.startsWith(`${guess}/`)),\n { truncated },\n );\n if (route.kind !== 'tokens') return { route };\n\n const [baseTree, headTree, theirsTree] = await Promise.all([treeAt(gh, mergeBase), treeAt(gh, headSha), treeAt(gh, mainSha)]);\n const config = (await configAt(gh, mainSha, theirsTree)) ?? (await configAt(gh, mergeBase, baseTree));\n const root = config?.tokens.root ?? guess;\n const options = config ? layoutOptions(config) : {};\n const checksPath = `${root}/${config?.tokens.contrastChecks ?? DEFAULT_TOKEN_PATHS.contrastChecks}`;\n const [baseFiles, mineFiles, theirsFiles, checks] = await Promise.all([\n tokenFilesAt(gh, mergeBase, root, baseTree),\n tokenFilesAt(gh, headSha, root, headTree),\n tokenFilesAt(gh, mainSha, root, theirsTree),\n theirsTree.has(checksPath) ? textAt(gh, mainSha, checksPath) : Promise.resolve(''),\n ]);\n const input: TokenMergeInput = { base: baseFiles, mine: mineFiles, theirs: theirsFiles, files: route.files.map((f) => withoutRoot(root, f)) };\n return {\n route,\n tokens: {\n root,\n plan: planTokenMerge(input),\n input,\n sets: { base: buildTokenSet(baseFiles, options), mine: buildTokenSet(mineFiles, options), theirs: buildTokenSet(theirsFiles, options) },\n mineFiles,\n theirsFiles,\n pairs: parseContrastChecks(checks || opts.contrastFallback),\n options,\n },\n write: { mainSha, mainTree, headSha, headTree, changeFiles },\n };\n}\n\n/**\n * Every token file once resolved, relative to the tokens root: main's files, the branch's own token files where only\n * the branch touched them, and the merged files where both did.\n */\nexport function resolvedTokenFiles(data: LibraryConflicts, choices: MergeChoices): { all: Record<string, string>; merged: Record<string, string | null> } {\n const t = data.tokens!;\n const merged = applyTokenMerge(t.input, choices).files;\n const all: Record<string, string> = { ...t.theirsFiles };\n for (const f of data.write!.changeFiles) {\n for (const p of [f.previous_filename, f.filename]) {\n if (!p || !p.endsWith('.tokens.json') || !p.startsWith(`${t.root}/`)) continue;\n const rel = withoutRoot(t.root, p);\n if (rel in merged) continue;\n if (t.mineFiles[rel] === undefined) delete all[rel];\n else all[rel] = t.mineFiles[rel]!;\n }\n }\n for (const [rel, text] of Object.entries(merged)) {\n if (text === null) delete all[rel];\n else all[rel] = text;\n }\n return { all, merged };\n}\n\n/**\n * Commits the resolution to the branch: a merge commit of main and the branch, whose tree is main plus the branch's\n * own files plus the merged token files. Fast-forward only: when the branch moved meanwhile, GitHub refuses and\n * nothing is lost.\n */\nexport async function commitLibraryResolution(\n gh: GitHubClient,\n pull: { head: { ref: string; sha: string }; base: { ref: string } },\n data: LibraryConflicts,\n choices: MergeChoices,\n who: string | null | undefined,\n): Promise<string> {\n const t = data.tokens;\n const w = data.write;\n if (!t || !w) throw new Error('Only a token conflict can be resolved in Bridge. A developer resolves code conflicts on GitHub.');\n if (w.headSha !== pull.head.sha) throw new Error('The branch moved while you were choosing. Read it again and resolve again.');\n const { merged } = resolvedTokenFiles(data, choices);\n const shared = new Set(data.route.files);\n type Entry = { path: string; mode: string; sha: string | null } | { path: string; mode: string; content: string };\n const tree: Entry[] = [];\n for (const f of w.changeFiles) {\n if (shared.has(f.filename)) continue;\n if (f.previous_filename && !shared.has(f.previous_filename)) tree.push({ path: f.previous_filename, mode: '100644', sha: null });\n if (f.status === 'removed') {\n tree.push({ path: f.filename, mode: '100644', sha: null });\n continue;\n }\n const e = w.headTree.get(f.filename);\n if (!e) throw new Error(`Bridge could not read ${f.filename} in the branch. Read it again and try again.`);\n tree.push({ path: e.path, mode: e.mode, sha: e.sha });\n }\n for (const [rel, text] of Object.entries(merged)) {\n const path = t.root ? `${t.root}/${rel}` : rel;\n const mode = w.headTree.get(path)?.mode ?? '100644';\n tree.push(text === null ? { path, mode, sha: null } : { path, mode, content: text });\n }\n const newTree = await gh.createTreeEntries(w.mainTree, tree);\n const message = resolutionMessage({ library: pull.base.ref, conflicts: t.plan.conflicts, choices, who });\n const commit = await gh.createCommit(message, newTree, [w.headSha, w.mainSha]);\n await gh.updateBranch(pull.head.ref, commit);\n return commit;\n}\n","// The writes behind the actions on a branch in review, shared by Bridge Studio (scripts/reviews.ts), the MCP server\n// and the CLI: merge, merge as owner override (reason posted first, marked \"not merged\" when GitHub refuses), review,\n// close and reopen. The rules that decide whether they are allowed live in review-gate.ts; these only write, through\n// the core GitHub client, so every surface sends GitHub the same requests.\nimport type { GitHubClient, Review } from './github-client';\nimport { OVERRIDE_HEADING, overrideComment, overrideRefusedComment, type MergeMethod, type MissingApproval } from './review-gate';\n\n/** Merges a branch at the head the person saw (GitHub refuses when it moved meanwhile). Studio's Merge button: squash. */\nexport async function mergeOnGitHub(gh: GitHubClient, input: { number: number; headSha: string; method?: MergeMethod | undefined }): Promise<{ sha: string }> {\n const r = await gh.mergePullRequest(input.number, { method: input.method ?? 'squash', sha: input.headSha });\n return { sha: r.sha };\n}\n\n/** Where an owner override stopped: GitHub refused the reason comment (nothing merged), or the merge itself. */\nexport class OverrideMergeError extends Error {\n constructor(\n readonly stage: 'comment' | 'merge',\n message: string,\n readonly cause?: unknown,\n readonly commentUrl?: string | undefined,\n ) {\n super(message);\n this.name = 'OverrideMergeError';\n }\n}\n\n/**\n * Merge as owner override: posts the reason on the branch first (the audit trail History reads back), then merges\n * with the first merge method the repository allows. When GitHub refuses the merge, the comment is edited to say\n * \"Merge refused by GitHub ... Not merged\", so the trail never claims a merge that did not happen. The caller checks\n * the gate first (mergeGate: overridable) and the reason (overrideReasonProblem).\n */\nexport async function overrideMergeOnGitHub(\n gh: GitHubClient,\n input: { number: number; headSha: string; login: string; reason: string; missing: MissingApproval[]; method: MergeMethod },\n): Promise<{ sha: string; commentUrl: string; comment: string }> {\n const body = overrideComment(input.login, input.reason, input.missing);\n let comment: { id: number; url: string };\n try {\n comment = await gh.createIssueComment(input.number, body);\n } catch (err) {\n throw new OverrideMergeError('comment', `GitHub did not take the comment, so nothing merged: ${(err as Error).message}`, err);\n }\n try {\n const r = await gh.mergePullRequest(input.number, { method: input.method, sha: input.headSha, commitMessage: body.replace(OVERRIDE_HEADING, '').trim() });\n return { sha: r.sha, commentUrl: comment.url, comment: body };\n } catch (err) {\n const msg = (err as Error).message.trim().replace(/[.\\s]+$/, '');\n await gh.updateIssueComment(comment.id, overrideRefusedComment(body, msg)).catch(() => undefined);\n throw new OverrideMergeError(\n 'merge',\n `GitHub refused to merge it: ${msg}. Your reason stays on the branch, marked not merged. The protection of main may need an approving review or an admin bypass.`,\n err,\n comment.url,\n );\n }\n}\n\nexport type ReviewEvent = 'APPROVE' | 'REQUEST_CHANGES' | 'COMMENT';\n\n/** Approve, request changes or comment, on the head the reviewer saw. Changes and comments need a text. */\nexport async function reviewOnGitHub(gh: GitHubClient, input: { number: number; event: ReviewEvent; body?: string | undefined; headSha?: string | undefined }): Promise<Review> {\n const text = input.body?.trim() ?? '';\n if (input.event === 'REQUEST_CHANGES' && !text) throw new Error('Add a comment that says what to change.');\n if (input.event === 'COMMENT' && !text) throw new Error('Write a comment first.');\n return gh.submitReview(input.number, { event: input.event, body: text || undefined, commitId: input.headSha });\n}\n\n/** A comment on the branch's conversation. */\nexport async function commentOnGitHub(gh: GitHubClient, n: number, body: string): Promise<{ id: number; url: string }> {\n const text = body.trim();\n if (!text) throw new Error('Write the comment first.');\n return gh.createIssueComment(n, text);\n}\n\n/**\n * \"Ask someone else to review\": requests the review from `others` (core reviewersToAsk) and takes the viewer off the\n * requested reviewers when GitHub had them on it. Throws how to fix it when nobody else can.\n */\nexport async function askOthersToReviewOnGitHub(gh: GitHubClient, input: { number: number; others: string[]; viewer?: string | null | undefined; viewerRequested?: boolean | undefined }): Promise<string[]> {\n if (!input.others.length) throw new Error('Nobody else can give the missing approval. Review it, or ask an owner in Settings to add a reviewer.');\n await gh.requestReviewers(input.number, input.others);\n if (input.viewer && input.viewerRequested) await gh.removeRequestedReviewers(input.number, [input.viewer]).catch(() => undefined);\n return input.others;\n}\n\n/** Closes a branch without merging it. Its work stays on GitHub and it can be reopened. */\nexport async function closeOnGitHub(gh: GitHubClient, n: number): Promise<void> {\n await gh.updatePullRequest(n, { state: 'closed' });\n}\n\n/** Reopens a closed branch (GitHub refuses when its branch was deleted). */\nexport async function reopenOnGitHub(gh: GitHubClient, n: number): Promise<void> {\n await gh.updatePullRequest(n, { state: 'open' });\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Adding edits to a branch already in review\n\nconst sameLogin = (a: string | null | undefined, b: string | null | undefined) => Boolean(a && b && a.toLowerCase().replace(/^@/, '') === b.toLowerCase().replace(/^@/, ''));\n\n/** Only the author or someone with write access to the repository adds to a branch. */\nexport function canAddTo(p: { user: { login: string } | null }, viewer: string | null | undefined, write: boolean): boolean {\n if (!viewer) return false;\n return write || sameLogin(p.user?.login, viewer);\n}\n\n/** The comment posted on the branch, so reviewers see what was added and from where. */\nexport function addedComment(paths: string[], viewer: string | null | undefined, from = 'the Bridge token editor'): string {\n const lines = paths.slice(0, 20).map((p) => `- \\`${p}\\``);\n if (paths.length > 20) lines.push(`- and ${paths.length - 20} more`);\n return `${viewer ? `@${viewer} added` : 'Added'} token edits from ${from}:\\n\\n${lines.join('\\n')}`;\n}\n","// Jira ticket keys: an optional \"DS-42\" given when a branch is created (Bridge Studio, the MCP server, the CLI).\n// Jira's GitHub integration links a pull request whose title (or branch name) starts with the key, so the key goes\n// first in both.\n\nconst JIRA_KEY = /^[A-Z][A-Z0-9_]{0,9}-[1-9]\\d{0,6}$/;\n\n/**\n * The Jira key given when a branch is created, normalised (\"ds-42 \" is \"DS-42\"), or null when empty. Throws a\n * sentence that says how to fix it when the text is not a key.\n */\nexport function parseJiraKey(input: string | null | undefined): string | null {\n const t = (input ?? '').trim().toUpperCase();\n if (!t) return null;\n if (!JIRA_KEY.test(t)) throw new Error('Write the Jira ticket as its key, like DS-42, or leave it empty.');\n return t;\n}\n\n/** Whether a text is a Jira key, without throwing (for live field validation). */\nexport const isJiraKey = (input: string) => JIRA_KEY.test(input.trim().toUpperCase());\n\nconst LEADING_KEY = /^\\[?([A-Z][A-Z0-9_]{0,9}-[1-9]\\d{0,6})\\]?[:\\s]\\s*/;\n\n/** The Jira key a title starts with (\"DS-42 tokens: darker primary\" gives \"DS-42\"), else null. */\nexport function jiraKeyOf(title: string): string | null {\n return LEADING_KEY.exec(title.trim())?.[1] ?? null;\n}\n\n/** The title without its leading Jira key. */\nexport const withoutJiraKey = (title: string) => title.trim().replace(LEADING_KEY, '');\n\n/** The pull request title with the key first: \"DS-42 tokens: darker primary\". Idempotent; no key, no change. */\nexport function titleWithJiraKey(title: string, key: string | null): string {\n if (!key) return title;\n return `${key} ${withoutJiraKey(title)}`;\n}\n\n/** The branch name with the key first in its last part: \"tokens/DS-42-darker-primary-20261019-1200\". */\nexport function branchWithJiraKey(branch: string, key: string | null): string {\n if (!key || branch.includes(key)) return branch;\n const i = branch.lastIndexOf('/');\n return i < 0 ? `${key}-${branch}` : `${branch.slice(0, i + 1)}${key}-${branch.slice(i + 1)}`;\n}\n","// Component docs (docs.json) proposed as a reviewable change, shared by the Library edit mode in Bridge Studio, the MCP\n// server and the CLI: what blocks a docs.json (validateDocs), the editor's cleaning, and one pull request per set of\n// docs edits (Tier 1 under the shared classifier, a patch changeset), at most one open per component (a new send\n// continues the open one), and an author line that says who wrote the text. The GitHub writes use the core client.\nimport { formatDocsJson, missingProse, patchDocsJson, type ComponentDocsJson } from './docs-draft';\nimport type { GitHubClient, PullRequestSummary } from './github-client';\nimport { classifyRisk, type RiskResult } from './risk';\nimport { branchWithJiraKey, titleWithJiraKey } from './jira';\n\n/** One component's docs.json, before (null: a new file) and after, at its repo path. */\nexport interface DocsFileEdit {\n path: string;\n component: string;\n slug: string;\n before: string | null;\n after: string;\n}\n\n/** Who wrote the docs, for the pull request body and its source label. */\nexport interface DocsOrigin {\n /** \"in the Bridge docs editor\". */\n where: string;\n footer: string;\n label: string;\n}\n\nexport const DOCS_EDITOR_ORIGIN: DocsOrigin = {\n where: 'in the Bridge docs editor',\n footer: 'Written by a person in the Bridge docs editor. No AI involved in this text.',\n label: 'source: bridge-web',\n};\n\nexport const DOCS_MCP_ORIGIN: DocsOrigin = {\n where: 'with Claude through the Bridge MCP server',\n footer: 'Proposed with the Bridge MCP server on behalf of a person. Docs Claude drafted say \"draftedBy\": \"claude\" until a reviewer accepts them.',\n label: 'source: mcp',\n};\n\nexport interface DocsIssue {\n field: string;\n message: string;\n}\n\nconst EM_DASH = /\\u2014/;\n\n/** What blocks proposing a docs.json: a summary, no empty list items, no em dash (Bridge voice). */\nexport function validateDocs(d: ComponentDocsJson): DocsIssue[] {\n const out: DocsIssue[] = [];\n if (!d.summary.trim()) out.push({ field: 'summary', message: 'Add a summary: one or two sentences on what it is for.' });\n const lists = ['whenToUse', 'whenNotToUse', 'accessibility', 'contentGuidelines'] as const;\n for (const k of lists) (d[k] ?? []).forEach((x, i) => !x.trim() && out.push({ field: `${k}.${i}`, message: 'Fill or remove the empty item.' }));\n for (const k of ['dos', 'donts'] as const) d[k].forEach((g, i) => (!g.title.trim() || !g.text.trim()) && out.push({ field: `${k}.${i}`, message: 'Give every item a title and a sentence.' }));\n const prose = JSON.stringify([d.summary, d.whenToUse, d.whenNotToUse, d.dos, d.donts, d.accessibility, d.contentGuidelines ?? [], d.anatomy ?? {}]);\n if (EM_DASH.test(prose)) out.push({ field: 'voice', message: 'Replace the em dashes with a colon, a comma or two sentences.' });\n return out;\n}\n\n/** Drops empty list items and trims text, the way the editor saves. */\nexport function cleanDocs(d: ComponentDocsJson): ComponentDocsJson {\n const list = (xs: string[] | undefined) => (xs ?? []).map((x) => x.trim()).filter(Boolean);\n const guide = (xs: ComponentDocsJson['dos']) => xs.map((g) => ({ ...g, title: g.title.trim(), text: g.text.trim() })).filter((g) => g.title || g.text);\n return {\n ...d,\n summary: d.summary.trim(),\n whenToUse: list(d.whenToUse),\n whenNotToUse: list(d.whenNotToUse),\n dos: guide(d.dos),\n donts: guide(d.donts),\n accessibility: list(d.accessibility),\n contentGuidelines: list(d.contentGuidelines),\n anatomy: Object.fromEntries(Object.entries(d.anatomy ?? {}).filter(([k, v]) => k.trim() && v.trim())),\n };\n}\n\n/** docs.json in the editor's canonical form: cleaned, in the Button.docs.json key order. Used to compare. */\nexport const docsText = (d: ComponentDocsJson) => formatDocsJson(cleanDocs(d));\n\n/** docs.json text the editor writes: cleaned, as a minimal diff of the file on main (or the branch) when there is one. */\nexport const docsFileText = (d: ComponentDocsJson, original: string | null) => patchDocsJson(original, cleanDocs(d));\n\nexport interface DocsProposal {\n branch: string;\n title: string;\n body: string;\n files: { path: string; content: string }[];\n risk: RiskResult;\n bump: 'patch';\n labels: string[];\n}\n\nconst slugDate = (d: Date) => d.toISOString().slice(0, 10).replace(/-/g, '');\n\n/** The branch slug of a component's docs: \"visually-hidden\" for VisuallyHidden or visually-hidden, at most 40 characters. */\nexport const docsSlug = (nameOrSlug: string) =>\n nameOrSlug\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-')\n .slice(0, 40);\n\n/* ------------------------------------------------------------------------------------------------------------------ */\n/* Who wrote the text */\n\n/** Section names (as the editor shows them) by who wrote their text in this send. */\nexport interface DocsAuthorship {\n /** Drafted by Claude, kept as Claude wrote it after review. */\n claude: string[];\n /** Drafted by Claude, then edited by the person. */\n edited: string[];\n /** Written by the person, no Claude draft involved. */\n written: string[];\n /** Drafted by Claude, not reviewed yet (they go out marked for review). */\n pending: string[];\n}\n\nconst listOf = (xs: string[]) => (xs.length < 2 ? (xs[0] ?? '') : `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`);\n\n/**\n * The author line of a docs proposal: \"by a person, no AI\" only when no Claude draft is in the text; \"drafted by\n * Claude AI, reviewed and sent by @ana\" when the person kept Claude's text as is; \"drafted by Claude AI, edited by\n * @ana\" with the edited sections when they changed parts of it.\n */\nexport function docsAuthorLine(a: DocsAuthorship, who: string | null | undefined, where = 'the Bridge docs editor'): string {\n const w = who?.trim() ? `@${who.trim().replace(/^@/, '')}` : 'a person';\n if (!a.claude.length && !a.edited.length && !a.pending.length) return `Written by ${w} in ${where}. No AI involved in this text.`;\n const head = a.edited.length\n ? `Drafted by Claude AI, edited by ${w} in ${where}.`\n : a.claude.length\n ? `Drafted by Claude AI, reviewed and sent by ${w} in ${where}.`\n : `Drafted by Claude AI, sent by ${w} in ${where} before review.`;\n const mixed = [a.edited, a.written, a.pending].some((x) => x.length);\n return [\n head,\n a.edited.length ? `Edited by ${w}: ${listOf(a.edited)}.` : '',\n a.claude.length && mixed ? `As Claude drafted them: ${listOf(a.claude)}.` : '',\n a.written.length ? `Written by ${w}: ${listOf(a.written)}.` : '',\n a.pending.length && (a.claude.length || a.edited.length || a.written.length) ? `Not reviewed yet: ${listOf(a.pending)}.` : '',\n ]\n .filter(Boolean)\n .join(' ');\n}\n\n/** Without an author line from the editor: the docs' own record (\"draftedBy\": \"claude\") decides, never \"no AI\" over it. */\nexport function defaultDocsFooter(edits: Pick<DocsFileEdit, 'after'>[], origin: DocsOrigin): string {\n if (origin.label !== DOCS_EDITOR_ORIGIN.label) return origin.footer;\n const claude = edits.some((e) => {\n try {\n return (JSON.parse(e.after) as ComponentDocsJson).draftedBy === 'claude';\n } catch {\n return false;\n }\n });\n return claude ? `Drafted by Claude AI (the docs say \"draftedBy\": \"claude\"), sent by a person ${origin.where}.` : origin.footer;\n}\n\n/** The body with its author line (the text after the last \"---\" line) replaced, or added when it has none. */\nexport function withAuthorLine(body: string, line: string): string {\n const i = body.lastIndexOf('\\n---\\n');\n return i < 0 ? `${body.trimEnd()}\\n\\n---\\n${line}` : `${body.slice(0, i + 5)}${line}`;\n}\n\n/* ------------------------------------------------------------------------------------------------------------------ */\n/* One open proposal per component */\n\n/** The open docs proposal of a component: the one a new send continues instead of opening a second one. */\nexport interface OpenDocsProposal {\n number: number;\n url: string;\n branch: string;\n author: string;\n title: string;\n updatedAt: string;\n}\n\nconst escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n/**\n * True when `branch` is a docs proposal branch of this component: docs/<slug>-<yyyymmdd>-<id>, with an optional Jira\n * key before the slug (docs/DS-42-button-...). \"button\" does not match docs/button-group-... branches. Older MCP\n * branches used the lowercased name (docs/visuallyhidden-...): they match too.\n */\nexport function isDocsProposalBranch(branch: string, component: { name: string; slug?: string | undefined }): boolean {\n const slugs = new Set([docsSlug(component.slug ?? component.name), docsSlug(component.name), docsSlug(component.name.toLowerCase())]);\n return [...slugs].some((s) => new RegExp(`^docs/(?:[A-Z][A-Z0-9]*-\\\\d+-)?${escapeRe(s)}-\\\\d{8}-[a-z0-9]+$`).test(branch));\n}\n\ntype PullLike = Pick<PullRequestSummary, 'number' | 'state' | 'headRef' | 'author' | 'title' | 'url' | 'updatedAt'> & { baseRef?: string | undefined };\n\n/** The most recently updated open docs proposal of the component (into `base` when given), or null. */\nexport function findOpenDocsProposal(pulls: PullLike[], component: { name: string; slug?: string | undefined }, base?: string): OpenDocsProposal | null {\n const hit = pulls\n .filter((p) => p.state === 'open' && isDocsProposalBranch(p.headRef, component) && (!base || !p.baseRef || p.baseRef === base))\n .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))[0];\n return hit ? { number: hit.number, url: hit.url, branch: hit.headRef, author: hit.author, title: hit.title, updatedAt: hit.updatedAt } : null;\n}\n\n/** Reads the open pull requests and returns the component's open docs proposal, or null. */\nexport async function findOpenDocsProposalOnGitHub(gh: GitHubClient, component: { name: string; slug?: string | undefined }, base?: string): Promise<OpenDocsProposal | null> {\n return findOpenDocsProposal(await gh.listPullRequests('open'), component, base);\n}\n\n/**\n * Adds a send to the open proposal: one commit with the docs.json on its branch (nothing when the text is the same),\n * and the author line of its description brought up to date. Returns the commit sha, or '' when nothing changed.\n */\nexport async function continueDocsProposalOnGitHub(\n gh: GitHubClient,\n open: Pick<OpenDocsProposal, 'number' | 'branch'>,\n edit: Pick<DocsFileEdit, 'path' | 'component' | 'after'>,\n opts: { authorLine?: string | undefined; message?: string | undefined } = {},\n): Promise<string> {\n const message = opts.message ?? `docs(${docsSlug(edit.component)}): edit usage guidance in the Bridge docs editor`;\n const cur = await gh.getFile(edit.path, open.branch);\n if (cur?.text === edit.after) return '';\n const sha = await gh.putFile({ path: edit.path, content: edit.after, branch: open.branch, message, sha: cur?.sha });\n if (opts.authorLine) {\n const line = opts.authorLine;\n await gh\n .getPullRequest(open.number)\n .then((pr) => gh.updatePullRequest(open.number, { body: withAuthorLine(pr.body, line) }))\n .catch(() => undefined);\n }\n return sha;\n}\n\n/** One pull request for the docs edits of a draft: branch, title, body, files with a patch changeset, the tier. */\nexport function docsProposal(\n edits: DocsFileEdit[],\n opts: { title?: string | undefined; notes?: string | undefined; date: Date; packageName?: string | undefined; changesetDir?: string | undefined; origin?: DocsOrigin | undefined; authorLine?: string | undefined },\n): DocsProposal {\n const origin = opts.origin ?? DOCS_EDITOR_ORIGIN;\n if (!edits.length) throw new Error('No docs edits in the draft.');\n const names = edits.map((e) => e.component);\n const list = names.length === 1 ? names[0]! : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;\n const title = opts.title?.trim() || `docs(${names.length === 1 ? edits[0]!.slug : 'components'}): usage guidance for ${list}`;\n const slug = docsSlug(names.length === 1 ? edits[0]!.slug : `${edits[0]!.slug}-and-${names.length - 1}-more`);\n const branch = `docs/${slug}-${slugDate(opts.date)}-${opts.date.getTime().toString(36).slice(-4)}`;\n const csPath = `${opts.changesetDir ?? '.changeset'}/docs-${slug}-${opts.date.getTime().toString(36)}.md`;\n const pkg = opts.packageName ?? '@bridge-ds/react';\n const changeset = `---\\n\"${pkg}\": patch\\n---\\n\\nUsage guidance for ${list}.\\n`;\n const files = [...edits.map((e) => ({ path: e.path, content: e.after })), { path: csPath, content: changeset }];\n const risk = classifyRisk({ files: files.map((f) => ({ path: f.path, status: 'modified' })) });\n const rows = edits.map((e) => {\n let state = 'edited';\n try {\n const d = JSON.parse(e.after) as ComponentDocsJson;\n const gaps = missingProse(d);\n state = gaps.length ? `still missing: ${gaps.join(', ')}` : 'every section filled';\n } catch {\n state = 'not valid JSON';\n }\n return `- \\`${e.path}\\` (${e.before === null ? 'new' : 'changed'}, ${state})`;\n });\n const body = [\n `## Docs change`,\n '',\n `Usage guidance for ${list}, written ${origin.where}.`,\n '',\n ...rows,\n '',\n `**Risk:** ${risk.label}. Docs only: the published components do not change. Changeset: patch.`,\n '',\n opts.notes?.trim() ? `## Notes\\n\\n${opts.notes.trim()}\\n` : '',\n '---',\n opts.authorLine?.trim() || defaultDocsFooter(edits, origin),\n ]\n .filter((x, i, a) => !(x === '' && a[i - 1] === ''))\n .join('\\n');\n return { branch, title, body, files, risk, bump: 'patch', labels: ['docs', origin.label, `tier-${risk.tier}`] };\n}\n\n\n/**\n * Opens one pull request with the docs edits from the default branch, the Jira key first in the title and the branch\n * name (Jira's GitHub integration links them). Returns its number, link and branch. Labels are best effort.\n * One open proposal per component: when the component already has one, the edit goes there as a new commit\n * (`continued`; `unchanged` when it already says this) instead of a second pull request.\n */\nexport async function proposeDocsOnGitHub(\n gh: GitHubClient,\n edits: DocsFileEdit[],\n opts: {\n base: string;\n title?: string | undefined;\n notes?: string | undefined;\n jira?: string | null | undefined;\n date?: Date | undefined;\n origin?: DocsOrigin | undefined;\n extraLabels?: string[] | undefined;\n commitNote?: string | undefined;\n /** Who wrote the text (docsAuthorLine). Without it, the origin's footer, never \"no AI\" over a Claude draft. */\n authorLine?: string | undefined;\n /** Default true: continue the component's open proposal. False always opens a new one. */\n continueOpen?: boolean | undefined;\n },\n): Promise<{ number: number; url: string; branch: string; title: string; continued: boolean; unchanged: boolean }> {\n if (opts.continueOpen !== false && edits.length === 1) {\n const e = edits[0]!;\n // A failed read does not block the send: it opens a new proposal, as before.\n const open = await findOpenDocsProposalOnGitHub(gh, { name: e.component, slug: e.slug }, opts.base).catch(() => null);\n if (open) {\n const sha = await continueDocsProposalOnGitHub(gh, open, e, { authorLine: opts.authorLine?.trim() || defaultDocsFooter(edits, opts.origin ?? DOCS_EDITOR_ORIGIN) });\n return { number: open.number, url: open.url, branch: open.branch, title: open.title, continued: true, unchanged: !sha };\n }\n }\n const p = docsProposal(edits, { title: opts.title, notes: opts.notes, date: opts.date ?? new Date(), origin: opts.origin, authorLine: opts.authorLine });\n const prTitle = titleWithJiraKey(p.title, opts.jira ?? null);\n const branch = branchWithJiraKey(p.branch, opts.jira ?? null);\n const mainSha = await gh.getBranchSha(opts.base);\n if (!mainSha) throw new Error(`Branch ${opts.base} not found.`);\n const tree = await gh.createTree(await gh.getCommitTree(mainSha), p.files.map((f) => ({ path: f.path, content: f.content })));\n const commit = await gh.createCommit(`${prTitle}\\n\\n${opts.commitNote ?? 'Proposed with the Bridge docs editor.'}`, tree, [mainSha]);\n await gh.createBranch(branch, commit);\n const pr = await gh.createPullRequest({ title: prTitle, head: branch, base: opts.base, body: p.body, draft: false });\n await gh.addLabels(pr.number, [...p.labels, ...(opts.extraLabels ?? [])]).catch(() => false);\n return { number: pr.number, url: pr.url, branch, title: prTitle, continued: false, unchanged: false };\n}\n\n/**\n * Rewrites one file on an open branch in one commit (`next` gets the current text). Returns the commit sha, or ''\n * when nothing changed. The Library editor saves an edited docs.json and accepts a Claude draft this way.\n */\nexport async function commitFileOnGitHub(gh: GitHubClient, input: { path: string; branch: string; message: string; next: (text: string) => string }): Promise<string> {\n const cur = await gh.getFile(input.path, input.branch);\n if (!cur) throw new Error(`${input.path} is not on ${input.branch}. Check the component name and the branch.`);\n const content = input.next(cur.text);\n if (content === cur.text) return '';\n return gh.putFile({ path: input.path, content, branch: input.branch, message: input.message, sha: cur.sha });\n}\n","// \"Share with a product team\" on a branch, shared by Bridge Studio, the MCP server and the CLI: a product team installs the change in its own app before it ships, the\n// designer's release candidate. Everything comes from what the Preview packages workflow\n// (.github/workflows/preview-packages.yml) really does:\n// - every update to an open or draft change builds the library packages (previews.packages in bridge.config.json)\n// and posts the install command in its sticky comment (`<!-- bridge-branch-preview -->`), about two minutes\n// after the update, whether or not the checks pass;\n// - with pkg.pr.new, one snapshot per update, kept after the change ships or closes;\n// - without it (this repository today), tarballs on a `preview-pr-<n>` GitHub prerelease: only the latest update\n// is kept, and the \"Remove the preview prerelease\" job deletes it when the change ships or closes.\n// Nothing is published to the npm registry per change: there is no dist-tag, the command installs by URL.\nimport { readPreviewComment } from './previews';\n\n/** The dialog's explanation, in designer words. */\nexport const SHARE_EXPLAIN = 'Product teams can install this branch in their app before it is merged, and remove it any time.';\n\nexport type ChangeLifecycle = 'open' | 'draft' | 'merged' | 'closed';\ntype Source = 'pkg.pr.new' | 'release' | 'other';\n\nexport type ShareState =\n /** The command for the latest update is posted. */\n | { kind: 'ready'; command: string; source: Source }\n /** No command for the latest update yet. */\n | { kind: 'building' }\n /** The workflow posted for the latest update but could not publish. */\n | { kind: 'failed' }\n /** The change touches none of the preview packages: there is nothing to install. */\n | { kind: 'no-packages' }\n /** Shipped or closed. `stillWorks` from where the preview lived; null when no preview was ever posted. */\n | { kind: 'shipped' | 'closed'; stillWorks: boolean | null; command: string | null };\n\n/** `@bridge-ds/react` -> `packages/react/`, the folder the workflow builds it from (PACKAGE_DIRS). */\nexport const packageDir = (name: string): string => `packages/${name.replace(/^@[^/]+\\//, '')}/`;\n\n/** True when a changed file is inside one of the preview packages. */\nexport function touchesPackages(files: readonly string[], packages: readonly string[]): boolean {\n const dirs = packages.map(packageDir);\n return files.some((f) => dirs.some((d) => f.startsWith(d)));\n}\n\n/**\n * Whether a change offers sharing at all: never from a fork (the workflow cannot publish from one) or when the\n * repository has no preview packages configured.\n */\nexport const canShare = (x: { fromFork: boolean; packages: readonly string[] }): boolean => !x.fromFork && x.packages.length > 0;\n\n/**\n * Where the preview of a change stands, from its lifecycle, its changed files and the sticky preview comment. A\n * comment about an older update than the head means the new one is still being prepared: its command is never shown.\n */\nexport function shareState(x: { lifecycle: ChangeLifecycle; files: readonly string[]; packages: readonly string[]; comment: string | null | undefined; headSha: string }): ShareState {\n // Checked first: a change outside the packages never has anything to install, before or after it ships.\n if (!touchesPackages(x.files, x.packages)) return { kind: 'no-packages' };\n const c = readPreviewComment(x.comment);\n if (x.lifecycle === 'merged' || x.lifecycle === 'closed') {\n const kind = x.lifecycle === 'merged' ? 'shipped' : 'closed';\n if (!c || !c.command || c.source === 'none') return { kind, stillWorks: null, command: null };\n // pkg.pr.new keeps every snapshot; the prerelease is deleted when the change ships or closes.\n return { kind, stillWorks: c.source === 'pkg.pr.new' ? true : c.source === 'release' ? false : null, command: c.command };\n }\n if (!c) return { kind: 'building' };\n if (c.sha7 && !x.headSha.startsWith(c.sha7)) return { kind: 'building' };\n if (!c.command || c.source === 'none') return { kind: 'failed' };\n return { kind: 'ready', command: c.command, source: c.source };\n}\n\n/**\n * Whether the change page shows the action: always while the change is open or a draft (the dialog says why there is\n * nothing to install yet), and after it ships or closes only when a preview was posted that a team may have installed.\n */\nexport const showShare = (lifecycle: ChangeLifecycle, s: ShareState): boolean =>\n lifecycle === 'open' || lifecycle === 'draft' || ((s.kind === 'shipped' || s.kind === 'closed') && !!s.command);\n\n/** The dialog's description: the explanation while the change can still be tried, where it stands once finished. */\nexport const shareDescription = (s: ShareState): string =>\n s.kind === 'shipped' || s.kind === 'closed' ? (stateSentence(s) ?? SHARE_EXPLAIN) : SHARE_EXPLAIN;\n\n/** How a product goes back to the released packages. */\nexport const stableCommand = (packages: readonly string[]): string => `npm i ${packages.map((p) => `${p}@latest`).join(' ')}`;\n\n/** The one sentence the dialog shows under its explanation, in designer words. Null when the message says it all. */\nexport function stateSentence(s: ShareState): string | null {\n switch (s.kind) {\n case 'ready':\n return null;\n case 'building':\n return 'The preview version is being prepared. It is usually ready a couple of minutes after each update to the branch.';\n case 'failed':\n return 'The preview version could not be prepared for the latest update. Update the branch to try again, or ask a developer to run it again on GitHub.';\n case 'no-packages':\n return 'This branch does not touch the library tokens or components, so there is no preview version to install.';\n case 'shipped':\n return s.stillWorks === true\n ? 'This branch was merged. Its preview version still installs, and products get it with the next library release.'\n : s.stillWorks === false\n ? 'This branch was merged, so its preview version was removed. Products get it with the next library release.'\n : 'This branch was merged. Products get it with the next library release.';\n case 'closed':\n return s.stillWorks === true\n ? 'This branch was closed without merging. Its preview version still installs, but it will not reach the library.'\n : s.stillWorks === false\n ? 'This branch was closed without merging, so its preview version was removed.'\n : 'This branch was closed without merging.';\n }\n}\n\nexport interface ShareMessageInput {\n title: string;\n state: ShareState;\n packages: readonly string[];\n /** \"Try it in the product\": the admin preview with this change, when GitHub reports one. */\n tryUrl?: string | null | undefined;\n /** The change on GitHub, for the developer. */\n url: string;\n}\n\nexport interface ShareMessage {\n subject: string;\n body: string;\n}\n\nconst quote = (t: string) => `\"${t.trim().replace(/\"/g, \"'\")}\"`;\n\n/**\n * The ready-to-paste message for a developer of a product team: the change, the preview install command, where to\n * see it first, how long the preview lasts and how to go back. Plain text, for a chat or an email. Null when there is\n * nothing to install and nothing to undo (still building, failed, no packages, or never posted).\n */\nexport function shareMessage(x: ShareMessageInput): ShareMessage | null {\n const back = stableCommand(x.packages);\n const s = x.state;\n if (s.kind === 'ready') {\n const lasts =\n s.source === 'pkg.pr.new'\n ? 'This preview stays available. Each update to the change makes a new one: ask me for the latest command.'\n : 'This preview is replaced on each update to the change and removed when it ships or closes: ask me for the latest command if the install fails.';\n return {\n subject: `Try the design system change ${quote(x.title)} before it ships`,\n body: [\n 'Hi,',\n '',\n `Could you try the design system change ${quote(x.title)} in our product before it ships?`,\n ...(x.tryUrl ? ['', `See it in the demo product first: ${x.tryUrl}`] : []),\n '',\n 'Install the preview version in a staging branch (not production):',\n s.command,\n '',\n lasts,\n '',\n 'To go back to the stable version:',\n back,\n '',\n `Details for developers: ${x.url}`,\n ].join('\\n'),\n };\n }\n if ((s.kind === 'shipped' || s.kind === 'closed') && s.command) {\n const what = s.kind === 'shipped' ? `The design system change ${quote(x.title)} has shipped. You get it with the next library release.` : `The design system change ${quote(x.title)} was closed without shipping.`;\n const preview = s.stillWorks === false ? 'Its preview version was removed, so reinstalling it fails.' : s.stillWorks === true ? 'Its preview version still installs, but it is not the released version.' : '';\n return {\n subject: `Design system change ${quote(x.title)} ${s.kind === 'shipped' ? 'has shipped' : 'was closed'}`,\n body: ['Hi,', '', [what, preview].filter(Boolean).join(' '), '', 'If you installed its preview, go back to the stable version:', back, '', `Details for developers: ${x.url}`].join('\\n'),\n };\n }\n return null;\n}\n\n/** \"Open in email\": a mailto link with the subject and body. Nothing is sent by Studio. */\nexport const mailtoHref = (m: ShareMessage): string => `mailto:?subject=${encodeURIComponent(m.subject)}&body=${encodeURIComponent(m.body.replace(/\\r?\\n/g, '\\r\\n'))}`;\n","// \"Try it in the product\" on a branch, shared by Bridge Studio, the MCP server and the CLI: the product preview Vercel\n// built for the branch, opened with the Bridge toolbar (`?bridge=<number>`, apps/admin/src/bridge) on a given screen.\n// The URL is only one GitHub reported (Vercel commit status, deployment or bot comment), never the config template:\n// Vercel shortens long branch aliases, so a template URL can point nowhere.\nimport { resolveBranchPreviews, type BranchPreviewSources, type PreviewApps } from './previews';\n\nexport interface ProductScreen {\n label: string;\n route: string;\n tenant: string;\n theme: string;\n}\n\n/** The admin preview of a change, or null when GitHub reports none (or the build failed, or it comes from a fork). */\nexport function productPreview(apps: PreviewApps, ctx: { branch: string; pr: number; sha: string; fromFork?: boolean }, sources: BranchPreviewSources): string | null {\n if (!apps.admin || ctx.fromFork) return null;\n const admin = resolveBranchPreviews(apps, { branch: ctx.branch, pr: ctx.pr, sha: ctx.sha }, sources).find((p) => p.app === 'admin');\n if (!admin?.url || admin.source === 'template' || admin.state === 'failed') return null;\n return admin.url;\n}\n\n/** The preview with the toolbar on, at that screen (shop and theme in the query, the hash route ra-core reads), else home. */\nexport function tryInProductUrl(preview: string, pr: number, screen: ProductScreen | null): string {\n const url = new URL(preview);\n url.pathname = '/';\n url.search = '';\n url.searchParams.set('bridge', String(pr));\n if (screen) {\n url.searchParams.set('tenant', screen.tenant);\n url.searchParams.set('theme', screen.theme);\n }\n url.hash = screen ? screen.route : '';\n return url.href;\n}\n","// Try 2 to 4 token branches together, the reads and the rules shared by Bridge Studio, the MCP server and the CLI:\n// which branches can be combined (token files only: code would need a real combined build), each branch's own token\n// edits read from GitHub (its start against its current version, token-combine changeEdits), and where the\n// combination opens (the admin demo with the Bridge toolbar, `?bridge=101,118`). Nothing is written anywhere.\nimport type { GitHubClient } from './github-client';\nimport { changeEdits, encodePicks, type ChangeEdits, type CombinePicks, type CombineSource } from './token-combine';\n\nexport const MIN_TOGETHER = 2;\n\nexport const MAX_TOGETHER = 4;\n\n/**\n * Whether a change only edits tokens: token files under the tokens root, the contrast gate and release notes\n * (changesets). Anything else is code. No file read yet (or none) is not a token change.\n */\nexport function onlyTokens(files: string[], tokensRoot: string): boolean {\n const root = `${tokensRoot.replace(/^\\/+|\\/+$/g, '')}/`;\n return files.length > 0 && files.every((f) => (f.startsWith(root) && f.endsWith('.tokens.json')) || /contrast\\.checks\\.json$/.test(f) || f.startsWith('.changeset/'));\n}\n\n/** Token files a change edits, relative to the tokens root. */\nexport function tokenFilesOf(files: string[], tokensRoot: string): string[] {\n const root = `${tokensRoot.replace(/^\\/+|\\/+$/g, '')}/`;\n return files.filter((f) => f.startsWith(root) && f.endsWith('.tokens.json')).map((f) => f.slice(root.length));\n}\n\n/** A list of changes in an address: \"101,118,120\" (commas stay readable). */\nexport const changeList = (numbers: number[]) => numbers.join(',');\n\n/**\n * The admin demo with the Bridge toolbar on the combination: production (no preview holds all of them), the tokens\n * applied live. `bridge-use` carries the picks.\n */\nexport function tryTogetherUrl(admin: string, numbers: number[], picks: CombinePicks): string {\n const url = new URL(admin);\n url.pathname = '/';\n url.hash = '';\n const use = encodePicks(picks);\n url.search = `?bridge=${changeList(numbers)}${use ? `&bridge-use=${encodeURIComponent(use)}` : ''}`;\n return url.href;\n}\n\n/** GitHub lists at most 300 files per compare: past that, a branch cannot be read whole, so it is not combined. */\nexport const COMBINE_COMPARE_LIMIT = 300;\n\nexport interface CombineBranch {\n number: number;\n title: string;\n /** Only token files (and release notes): it can be combined. */\n tokens: boolean;\n /** Its own token edits; null for a code change. */\n edits: ChangeEdits | null;\n}\n\n/**\n * One branch as the combination needs it: one compare against the default branch (the files it edits since it\n * started, and where it started), then its token files at its start and now. Without a token the client reads the\n * public raw host, so visitors spend no API read on file contents.\n */\nexport async function readCombineBranch(gh: GitHubClient, pull: { number: number; title: string; headSha: string }, opts: { base: string; tokensRoot: string }): Promise<CombineBranch> {\n const compare = await gh.compareDetailed(opts.base, pull.headSha);\n const files = compare.files;\n const names = files.flatMap((f) => (f.previous_filename ? [f.filename, f.previous_filename] : [f.filename]));\n const start = compare.mergeBase;\n if (!start || files.length >= COMBINE_COMPARE_LIMIT || !onlyTokens(names, opts.tokensRoot)) return { number: pull.number, title: pull.title, tokens: false, edits: null };\n const root = opts.tokensRoot.replace(/^\\/+|\\/+$/g, '');\n const tokenFiles = files.filter((f) => tokenFilesOf([f.filename], root).length);\n const source: CombineSource = { number: pull.number, base: {}, head: {}, files: tokenFiles.map((f) => tokenFilesOf([f.filename], root)[0]!) };\n await Promise.all(\n tokenFiles.map(async (f) => {\n const rel = tokenFilesOf([f.filename], root)[0]!;\n source.base[rel] = f.status === 'added' ? undefined : await gh.readFile(f.previous_filename ?? f.filename, start);\n source.head[rel] = f.status === 'removed' ? undefined : await gh.readFile(f.filename, pull.headSha);\n }),\n );\n return { number: pull.number, title: pull.title, tokens: true, edits: changeEdits(source) };\n}\n","// Product branches and their library branches on GitHub, shared by Bridge Studio (in the browser, with the viewer's\n// token), the MCP server and the CLI: read what a product branch changes, record its missing pieces, open the library\n// branch of a piece and link both ways, let the product branch use the library branch's preview (Bridge merges the\n// library branch in), read where each linked library branch stands, and switch to the published version once it\n// ships. The pure rules are in prod-branch.ts; finding the pieces (the audit) is in audit/missing-pieces.ts.\n\nimport { EXPLORATION_NOTES_DIR, EXPLORATION_PREFIX, isExplorationBranch } from './explorations';\nimport { startExplorationOnGitHub, type ExplorationSettings } from './explorations-github';\nimport { GitHubError, type GitHubClient, type PullRequestSummary } from './github-client';\nimport { defaultProduct, productOfBranch, type ProductConfig } from './products';\nimport {\n libraryBranchPlan,\n linkStatus,\n mergePiecesRecord,\n NEEDED_BY_LABEL,\n parsePiecesRecord,\n libraryPreviewState,\n productBranchSentence,\n withLink,\n withNeededBy,\n withPiecesRecord,\n type LibraryBranchPlan,\n type LibraryLink,\n type LinkStatus,\n type MissingPiece,\n type PiecesRecord,\n type LibraryPreviewState,\n type ProductBranchRef,\n} from './prod-branch';\nimport { composeRequestIssue, type RequestSource } from './requests';\n\n/** Files the audit reads (styles, scripts, markup). Kept here so this module never loads the audit. */\nconst PRODUCT_FILE = /\\.(css|scss|sass|less|tsx|jsx|ts|js|mjs|cjs|mts|cts|astro|vue|svelte)$/;\nconst SKIP_FILE = /\\.d\\.[cm]?ts$|\\.(test|spec|stories|story)\\.[cm]?[jt]sx?$|\\.min\\.(css|js)$/;\n/** At most this many product files are read per check (two reads each). */\nexport const PIECES_FILE_LIMIT = 40;\n\ntype Pull = PullRequestSummary & { body: string; mergeable: boolean | null; requestedReviewers: string[] };\n\nexport interface ProductBranchRead {\n pull: Pull;\n product: ProductConfig;\n /** The product's changed files, their texts at the branch start (merge base with main) and at its head. */\n files: { path: string; before: string | null; after: string | null }[];\n /** Product files left unread past the limit. */\n skipped: number;\n record: PiecesRecord | undefined;\n}\n\nconst cleanPath = (p: string) => p.trim().replace(/^\\.?\\/+|\\/+$/g, '');\n\n/** The product of a branch, refusing the library itself: missing pieces are about a product built on the library. */\nfunction productOf(products: readonly ProductConfig[], pull: Pick<Pull, 'labels'>, files: string[]): ProductConfig {\n const product = productOfBranch(products, { labels: pull.labels, files });\n if (product.key === defaultProduct(products).key) throw new GitHubError(422, `This branch is a library branch (${product.name}), not a product branch: missing pieces are checked on a branch started for a product.`);\n return product;\n}\n\n/**\n * Reads a product branch for the check: the pull request, its product, and the product files it changes with their\n * text before and after (two reads per file, up to PIECES_FILE_LIMIT files).\n */\nexport async function readProductBranchOnGitHub(gh: GitHubClient, pr: number, opts: { products: readonly ProductConfig[] }): Promise<ProductBranchRead> {\n const pull = await gh.getPullRequest(pr);\n const cmp = await gh.compareDetailed(pull.baseRef, pull.headSha);\n const product = productOf(opts.products, pull, cmp.files.map((f) => f.filename));\n const dir = product.path ? `${cleanPath(product.path)}/` : '';\n const changed = cmp.files.filter((f) => f.status !== 'removed' && (!dir || f.filename.startsWith(dir)) && PRODUCT_FILE.test(f.filename) && !SKIP_FILE.test(f.filename) && !f.filename.split('/').includes('node_modules'));\n const read = changed.slice(0, PIECES_FILE_LIMIT);\n const start = cmp.mergeBase ?? pull.baseRef;\n const files = await Promise.all(\n read.map(async (f) => {\n const [before, after] = await Promise.all([f.status === 'added' ? Promise.resolve(undefined) : gh.getFileText(f.previous_filename ?? f.filename, start), gh.getFileText(f.filename, pull.headSha)]);\n return { path: f.filename, before: before ?? null, after: after ?? null };\n }),\n );\n return { pull, product, files, skipped: changed.length - read.length, record: parsePiecesRecord(pull.body) };\n}\n\n/** Saves a check in the product branch body, keeping the library branches already opened for its pieces. */\nexport async function recordPiecesOnGitHub(gh: GitHubClient, pr: number, check: { pieces: MissingPiece[]; fixes: number; headSha?: string | undefined; checkedAt?: string | undefined }): Promise<PiecesRecord> {\n const pull = await gh.getPullRequest(pr);\n const record = mergePiecesRecord(parsePiecesRecord(pull.body), { checkedAt: check.checkedAt ?? new Date().toISOString(), headSha: check.headSha ?? pull.headSha, pieces: check.pieces, fixes: check.fixes });\n await gh.updatePullRequest(pr, { body: withPiecesRecord(pull.body, record) });\n return record;\n}\n\n/** The client that may write a product branch: explorations need the `explore/` prefix. */\nconst productWriter = (gh: GitHubClient, branch: string) => (isExplorationBranch(branch) ? gh.withBranchPrefix(EXPLORATION_PREFIX) : gh);\n\nexport interface PreviewMerge {\n status: 'merged' | 'up-to-date' | 'conflict';\n sha: string | null;\n said: string;\n}\n\n/**\n * The product branch uses the library branch's preview: Bridge merges the library branch into it, so the product\n * preview deploy and anyone working on the branch get the real library change. A conflict is left to a developer.\n */\nexport async function useLibraryPreviewOnGitHub(gh: GitHubClient, input: { productBranch: string; libraryBranch: string; libraryNumber: number }): Promise<PreviewMerge> {\n const message = `chore(bridge): use the preview of ${input.libraryBranch} (#${input.libraryNumber})\\n\\nThe product branch takes the library branch before it ships. Switch to the published version once it does.`;\n try {\n const r = await productWriter(gh, input.productBranch).mergeIntoBranch(input.productBranch, input.libraryBranch, message);\n return { ...r, said: r.status === 'merged' ? 'Your branch now uses the preview of the library branch.' : 'Your branch already has the latest preview.' };\n } catch (err) {\n if (err instanceof GitHubError && err.status === 409) return { status: 'conflict', sha: null, said: `Your branch and the library branch change the same lines. A developer merges ${input.libraryBranch} into ${input.productBranch} by hand.` };\n throw err;\n }\n}\n\nexport interface OpenLibraryBranchInput {\n /** The product branch (pull request number). */\n pr: number;\n /** The piece id, from the recorded check. */\n piece: string;\n /** Branch library work starts from (the default branch). */\n base: string;\n products: readonly ProductConfig[];\n /** Previews and snapshot packages for a library exploration. */\n exploration: Pick<ExplorationSettings, 'packages' | 'apps'>;\n /**\n * Opens the token change of a token piece (planTokenProposal + writeTokenProposalOnGitHub where the caller has the\n * token files and contrast pairs). Without it a token piece is refused.\n */\n writeTokens?: ((plan: Extract<LibraryBranchPlan, { kind: 'token-change' }>) => Promise<{ number: number; url: string; branch: string }>) | undefined;\n /** Who opens it, and the AI agent behind it (\"claude\"). */\n openedBy?: string | undefined;\n agent?: string | undefined;\n source?: RequestSource | undefined;\n /** Merge the new library branch into the product branch when it already changes something (default true). */\n usePreview?: boolean | undefined;\n dryRun?: boolean | undefined;\n}\n\nexport interface OpenedLibraryBranch {\n status: 'opened' | 'already-linked' | 'dry-run';\n plan: LibraryBranchPlan;\n link: LibraryLink | null;\n preview: PreviewMerge | null;\n warnings: string[];\n}\n\n/** The product branch as the library side names it. */\nexport function productBranchRef(pull: Pick<Pull, 'number' | 'title' | 'headRef' | 'url' | 'author' | 'body'>, product: ProductConfig): ProductBranchRef {\n const name = /<!-- bridge-exploration (\\{[\\s\\S]*?\\}) -->/.exec(pull.body ?? '');\n let title = pull.title.replace(/^[A-Z][A-Z0-9_]*-\\d+\\s+/, '').replace(/^Exploration:\\s*/i, '');\n let author = pull.author;\n if (name) {\n try {\n const e = JSON.parse(name[1]!) as { name?: string; author?: string };\n if (e.name) title = e.name;\n if (e.author) author = e.author;\n } catch {\n // The pull request title is enough.\n }\n }\n return { pr: pull.number, title: title.charAt(0).toUpperCase() + title.slice(1), branch: pull.headRef, url: pull.url, productKey: product.key, productName: product.name, ...(author ? { author } : {}) };\n}\n\n/**\n * Opens the library side of a missing piece and links both ways: the library branch (or request) says \"Needed by\" the\n * product branch and carries the `needed-by-product` label; the product branch records the link. A token piece opens a\n * token change (through `writeTokens`), a variant a library exploration, a new component a request. When the new\n * library branch already changes something (a token change), the product branch takes its preview.\n */\nexport async function openLibraryBranchOnGitHub(gh: GitHubClient, input: OpenLibraryBranchInput): Promise<OpenedLibraryBranch> {\n const pull = await gh.getPullRequest(input.pr);\n const record = parsePiecesRecord(pull.body);\n const piece = record?.pieces.find((p) => p.id === input.piece);\n if (!record || !piece) throw new GitHubError(404, record ? `No piece \"${input.piece}\" on #${input.pr}. Pieces: ${record.pieces.map((p) => p.id).join(', ') || 'none'}.` : `#${input.pr} was not checked yet: find its missing pieces first (bridge_missing_pieces with record, or \\`bridge pieces ${input.pr} --record\\`).`);\n const product = productOf(input.products, pull, await gh.listPullRequestFiles(input.pr).then((f) => f.map((x) => x.filename), () => []));\n const plan = libraryBranchPlan(piece, productBranchRef(pull, product), { source: input.source, requestedBy: input.openedBy });\n const existing = record.links.find((l) => l.piece === piece.id);\n if (existing) return { status: 'already-linked', plan, link: existing, preview: null, warnings: [] };\n if (input.dryRun) return { status: 'dry-run', plan, link: null, preview: null, warnings: [] };\n if (!gh.canWrite) throw new GitHubError(401, 'Opening a library branch needs a GitHub token (contents, pull requests and issues: write).');\n const warnings: string[] = [];\n const at = new Date().toISOString();\n const who = { ...(input.openedBy ? { openedBy: input.openedBy } : {}), ...(input.agent ? { agent: input.agent } : {}) };\n let link: LibraryLink;\n if (plan.kind === 'token-change') {\n if (!input.writeTokens) throw new GitHubError(422, 'This piece is a token: open it where the token files are read (Bridge Studio, bridge_open_library_branch or `bridge pieces open`).');\n const r = await input.writeTokens(plan);\n link = { piece: piece.id, kind: 'token-change', number: r.number, url: r.url, title: plan.title, branch: r.branch, at, ...who };\n } else if (plan.kind === 'exploration') {\n const r = await startExplorationOnGitHub(gh, { ...plan.exploration, ...(input.openedBy ? { author: input.openedBy } : {}), ...(input.agent ? { agent: input.agent } : {}) }, { base: input.base, ...input.exploration, labels: [NEEDED_BY_LABEL] });\n link = { piece: piece.id, kind: 'exploration', number: r.pr, url: r.url, title: plan.title, branch: r.branch, at, ...who };\n } else {\n const issue = composeRequestIssue(plan.request, { labels: [NEEDED_BY_LABEL] });\n const r = await gh.createIssue(issue);\n link = { piece: piece.id, kind: 'request', number: r.number, url: r.url, title: plan.title, at, ...who };\n }\n // The library side says who needs it; the product side records the link.\n try {\n if (link.kind === 'request') {\n const issue = await gh.getIssue(link.number);\n await gh.updateIssue(link.number, { body: withNeededBy(issue.body, plan.neededBy) });\n } else {\n const lib = await gh.getPullRequest(link.number);\n await gh.updatePullRequest(link.number, { body: withNeededBy(lib.body, plan.neededBy) });\n await gh.addLabels(link.number, [NEEDED_BY_LABEL]);\n }\n } catch (err) {\n if (err instanceof GitHubError && err.auth === 'rejected') throw err;\n warnings.push(`The library side does not say who needs it yet (${(err as Error).message}). Add \"Needed by #${input.pr}\" to #${link.number} on GitHub.`);\n }\n const fresh = await gh.getPullRequest(input.pr);\n const next = withLink(parsePiecesRecord(fresh.body) ?? record, link);\n await gh.updatePullRequest(input.pr, { body: withPiecesRecord(fresh.body, next) });\n let preview: PreviewMerge | null = null;\n if ((input.usePreview ?? true) && link.kind === 'token-change' && link.branch) {\n preview = await useLibraryPreviewOnGitHub(gh, { productBranch: pull.headRef, libraryBranch: link.branch, libraryNumber: link.number }).catch((err: Error) => {\n warnings.push(`Your branch does not use the preview yet: ${err.message}`);\n return null;\n });\n }\n return { status: 'opened', plan, link, preview, warnings };\n}\n\nexport interface LinkedLibraryBranch {\n link: LibraryLink;\n piece: MissingPiece | undefined;\n status: LinkStatus;\n preview: LibraryPreviewState;\n /** Requested reviewers of a library pull request, or assignees of a request. */\n people: string[];\n}\n\nexport interface ProductBranchView {\n pull: Pull;\n product: ProductConfig;\n record: PiecesRecord | undefined;\n sentence: ReturnType<typeof productBranchSentence>;\n linked: LinkedLibraryBranch[];\n /** Pieces with no library branch yet. */\n open: MissingPiece[];\n}\n\nconst isNote = (path: string) => path.startsWith(`${EXPLORATION_NOTES_DIR}/`);\n\n/** Where one linked library branch stands, and what its preview means for the product branch. */\nexport async function linkedLibraryBranchOnGitHub(gh: GitHubClient, link: LibraryLink, product: { headSha: string; baseRef: string }, piece?: MissingPiece): Promise<LinkedLibraryBranch> {\n const nearest = piece?.nearest?.label;\n if (link.kind === 'request') {\n const issue = await gh.getIssue(link.number);\n const status = linkStatus({ kind: 'request', state: issue.state, stateReason: issue.stateReason });\n const lifecycle = issue.state === 'closed' ? (issue.stateReason === 'not_planned' ? 'closed' : 'merged') : 'open';\n const behindMain = lifecycle === 'merged' ? await gh.compare(product.baseRef, product.headSha).then((c) => c.behindBy, () => null) : null;\n const preview = libraryPreviewState({ kind: 'request', lifecycle, hasChanges: false, missing: null, total: null, behindMain, nearest });\n return { link, piece, status, preview, people: status.people };\n }\n const lib = await gh.getPullRequest(link.number);\n const reviews = await gh.listReviews(link.number).catch(() => []);\n const status = linkStatus({ kind: link.kind, state: lib.state, draft: lib.draft, labels: lib.labels, requestedReviewers: lib.requestedReviewers, reviews: reviews.map((r) => ({ user: r.user, state: r.state })) });\n const lifecycle = lib.state === 'merged' ? 'merged' : lib.state === 'open' ? 'open' : 'closed';\n let missing: number | null = null;\n let total: number | null = null;\n let behindMain: number | null = null;\n let hasChanges = true;\n if (lifecycle === 'open') {\n const [files, own, inProduct] = await Promise.all([\n gh.listPullRequestFiles(link.number).catch(() => null),\n gh.compare(lib.baseRef, lib.headSha).catch(() => null),\n gh.compare(product.headSha, lib.headSha).catch(() => null),\n ]);\n hasChanges = files ? files.some((f) => !isNote(f.filename)) : true;\n total = own?.aheadBy ?? null;\n missing = inProduct?.aheadBy ?? null;\n } else if (lifecycle === 'merged') {\n behindMain = await gh.compare(product.baseRef, product.headSha).then((c) => c.behindBy, () => null);\n }\n const preview = libraryPreviewState({ kind: link.kind, lifecycle, hasChanges, missing, total, behindMain, nearest });\n return { link, piece, status, preview, people: status.people };\n}\n\n/**\n * Everything a product branch page shows: the record, the sentence, and each linked library branch with its status,\n * its reviewers and what its preview means for the product branch. A few reads per linked branch.\n */\nexport async function productBranchViewOnGitHub(gh: GitHubClient, pr: number, opts: { products: readonly ProductConfig[]; viewer?: string | null | undefined; agentName?: string | undefined }): Promise<ProductBranchView> {\n const pull = await gh.getPullRequest(pr);\n const files = await gh.listPullRequestFiles(pr).then((f) => f.map((x) => x.filename), () => []);\n const product = productOf(opts.products, pull, files);\n const record = parsePiecesRecord(pull.body);\n const linked = await Promise.all(\n (record?.links ?? []).map((l) => linkedLibraryBranchOnGitHub(gh, l, { headSha: pull.headSha, baseRef: pull.baseRef }, record?.pieces.find((p) => p.id === l.piece))),\n );\n const open = (record?.pieces ?? []).filter((p) => !record!.links.some((l) => l.piece === p.id));\n return { pull, product, record, sentence: productBranchSentence(record, { viewer: opts.viewer, agentName: opts.agentName }), linked, open };\n}\n\n/**\n * \"Switch to the published version\": once the library branch shipped, main comes into the product branch (GitHub's\n * update branch), so the product branch stops carrying the library change and uses the shipped one. Conflicts are\n * left to bridge_update_from_main or a developer.\n */\nexport async function switchToPublishedOnGitHub(gh: GitHubClient, pr: number): Promise<{ status: 'switched' | 'up-to-date'; said: string }> {\n if (!gh.canWrite) throw new GitHubError(401, 'Switching needs a GitHub token (contents and pull requests: write).');\n const pull = await gh.getPullRequest(pr);\n if (pull.state !== 'open') throw new GitHubError(422, `#${pr} is ${pull.state}: only an open branch switches.`);\n const cmp = await gh.compare(pull.baseRef, pull.headSha);\n if (cmp.behindBy === 0) return { status: 'up-to-date', said: 'Your branch already uses the published version.' };\n try {\n await gh.updatePullRequestBranch(pr, pull.headSha);\n } catch (err) {\n if (err instanceof GitHubError && err.status === 422) throw new GitHubError(422, `Your branch and ${pull.baseRef} change the same lines, so Bridge cannot switch it alone. Use \"Update from main\" to pick the token values, or ask a developer.`, err.detail);\n throw err;\n }\n return { status: 'switched', said: `Your branch now uses the published version from ${pull.baseRef}.` };\n}\n","// A token change proposal: token edits checked like every Bridge write (no new validation error, no contrast pair that\n// starts failing), tiered by the shared classifier, with the designer-friendly body and a changeset; then, on GitHub, a\n// new branch with one commit and a pull request (a draft from tier 2), labelled. The MCP server\n// (bridge_propose_token_change), the CLI (`bridge propose`) and Studio (a library branch for a product branch's missing\n// token) all write it through these two functions.\nimport type { BridgeConfig } from './config';\nimport type { GitHubClient } from './github-client';\nimport { branchWithJiraKey, titleWithJiraKey } from './jira';\nimport { LayeredTokenSet, validateLayered, type LayerIssue } from './layered';\nimport { classifyLayered, composeProposalBody, contrastDelta, diffLayered, layeredImpact, runLayeredContrast, type ChangeTier, type ContrastDelta, type ImpactEntry, type LayeredChange } from './layered-review';\nimport { slugify } from './pr-composer';\nimport { applyTokenEdits, type TokenEdit } from './token-edits';\nimport type { ContrastPair } from './wcag';\nimport { formatChangeset } from './changeset';\n\nexport interface TokenProposalPlan {\n title: string;\n summary: string;\n before: LayeredTokenSet;\n after: LayeredTokenSet;\n changes: LayeredChange[];\n tier: ChangeTier;\n contrast: ContrastDelta[];\n newFailures: ContrastDelta[];\n newErrors: LayerIssue[];\n impact: { total: number; entries: ImpactEntry[] };\n notes: string[];\n /** Token files edited, as repo paths. */\n touched: string[];\n /** Every file the commit writes: the token files and the changeset. */\n files: { path: string; content: string | null }[];\n body: string;\n /** Branch slug from the title. */\n slug: string;\n /** Why it cannot be opened (new validation errors, failing contrast pairs), or null. */\n blocked: string | null;\n}\n\nconst issueKey = (i: LayerIssue) => `${i.code}|${i.path ?? ''}|${i.file ?? ''}|${i.message}`;\n\n/**\n * What a token change would do, without writing: the token diff, validation and contrast against `before`, the tier,\n * the body and the files. `blocked` says why it must not be opened. Null when the edits change nothing.\n */\nexport function planTokenProposal(input: {\n before: LayeredTokenSet;\n pairs: ContrastPair[];\n edits: TokenEdit[];\n title: string;\n summary?: string | undefined;\n config: BridgeConfig;\n /** \"Bridge MCP\", \"Bridge Studio\". */\n tool?: string | undefined;\n /** More body paragraphs, after the generated body (the product line, \"Needed by\"). */\n bodyExtra?: string[] | undefined;\n}): TokenProposalPlan | null {\n const { before, config } = input;\n const r = applyTokenEdits(before, input.edits);\n const after = new LayeredTokenSet(before.config, r.files);\n const changes = diffLayered(before, after);\n if (!changes.length) return null;\n const prevErrors = new Set(validateLayered(before).map(issueKey));\n const newErrors = validateLayered(after).filter((i) => i.level === 'error' && !prevErrors.has(issueKey(i)));\n const modes = config.contrast?.modes;\n const contrast = input.pairs.length ? contrastDelta(runLayeredContrast(before, input.pairs, modes), runLayeredContrast(after, input.pairs, modes)) : [];\n const newFailures = contrast.filter((d) => d.passBefore && !d.passAfter);\n const impact = layeredImpact(before, after, changes);\n const tier = classifyLayered(changes, [], config);\n const summary = input.summary?.trim() || input.title;\n const body = [composeProposalBody({ summary, changes, contrast, impact, tier, validationErrors: newErrors.length, tool: input.tool ?? 'Bridge MCP' }), ...(input.bodyExtra ?? [])].filter(Boolean).join('\\n\\n');\n const slug = slugify(input.title, 48) || 'change';\n const changesetPath = `${config.changesets?.dir ?? '.changeset'}/bridge-${slug}.md`;\n const touched = r.touched.map((f) => after.repoPath(f));\n const files = [\n ...r.touched.map((f) => ({ path: after.repoPath(f), content: after.files.get(f)! as string | null })),\n ...(config.changesets ? [{ path: changesetPath, content: formatChangeset(config.changesets.package, tier.bump, summary) as string | null }] : []),\n ];\n const blocked = newErrors.length || newFailures.length ? [newErrors.length ? `${newErrors.length} new validation error(s)` : '', newFailures.length ? `${newFailures.length} contrast pair(s) would fail` : ''].filter(Boolean).join(' and ') : null;\n return { title: input.title, summary, before, after, changes, tier, contrast, newFailures, newErrors, impact, notes: r.notes, touched, files, body, slug, blocked };\n}\n\nexport interface OpenedTokenProposal {\n branch: string;\n commit: string;\n pr: number;\n url: string;\n labels: string[];\n draft: boolean;\n}\n\n/**\n * Opens a planned token change on GitHub: a new branch from `base` (the agent prefix, the Jira key, -2, -3 when the name\n * is taken), one commit, a pull request (a draft from tier 2, until design review) and its labels. Refuses a blocked plan.\n */\nexport async function writeTokenProposalOnGitHub(\n gh: GitHubClient,\n plan: TokenProposalPlan,\n opts: {\n base: string;\n branchPrefix: string;\n jira?: string | null | undefined;\n /** Labels before the tier ones (governance.labels), and after them (the product label). */\n labels?: string[] | undefined;\n labelsAfter?: string[] | undefined;\n /** Who proposes it, in the commit message: \"Bridge MCP (source: mcp)\". */\n tool?: string | undefined;\n },\n): Promise<OpenedTokenProposal> {\n if (plan.blocked) throw new Error(`Not opened: ${plan.blocked}. Bridge never opens a branch that breaks the gate.`);\n const jira = opts.jira ?? null;\n let branch = branchWithJiraKey(`${opts.branchPrefix}${plan.slug}`, jira);\n for (let i = 2; await gh.getBranchSha(branch).then(Boolean, () => false); i++) branch = branchWithJiraKey(`${opts.branchPrefix}${plan.slug}-${i}`, jira);\n const commit = await gh.commitToNewBranch({ base: opts.base, branch, message: `feat(tokens): ${plan.title}\\n\\nProposed through ${opts.tool ?? 'Bridge MCP'}. Tier ${plan.tier.tier}.`, files: plan.files });\n const labels = [...new Set([...(opts.labels ?? []), `tier: ${plan.tier.tier}`, ...(plan.tier.tier === 3 ? ['tokens'] : []), ...(plan.tier.bump === 'major' ? ['breaking'] : []), ...(opts.labelsAfter ?? [])])];\n const draft = plan.tier.tier >= 2;\n const pr = await gh.createPullRequest({ base: opts.base, head: branch, title: titleWithJiraKey(`feat(tokens): ${plan.title}`, jira), body: plan.body, draft });\n await gh.addLabels(pr.number, labels);\n return { branch, commit: commit.sha, pr: pr.number, url: pr.url, labels, draft };\n}\n"],"names":["issueKey","i","t","p","modesOf","a","_","j","s","idOf","k","n","names","x","tokensPath","norm","STEPS","L","C","h","A","B","w","text","cell","shape","plural","at","before","after","by","sentences","MARK","u","quote","y","code","lower","status","lifecycle","behindMain","preview"],"mappings":";;;;;;AA4CA,MAAMA,aAAW,CAACC,OAAa,GAAGA,GAAE,IAAI,IAAIA,GAAE,QAAQ,EAAE,IAAIA,GAAE,QAAQ,EAAE,IAAIA,GAAE,SAAS,iBAAiBA,GAAE,UAAU,EAAE;AACtH,MAAM,WAAW,CAAC,SAAkB,SAAS,cAAc,cAAc,gBAAgB,IAAI;AAE7F,MAAM,YAAY,CAACC,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