// ONE generated place may hold a colour, and this proves no other does —// PaletteGuardTests.swift (CottonUITests), ported to vitest: it only ever read// the Swift sources as text. The describe keeps the Swift suite's name, so a// source comment that names `PaletteGuardTests` still finds its guard here.//// AN EXEMPTION IS SCOPED TO ONE SWEEP, NEVER TO A FILE. There are four sweeps —// hex, channel constructors, system colour names, colours reached by a STRING —// and the files below are exempt from exactly the sweeps their sentences name.// A new entry must carry a sentence saying why that colour cannot come off the// palette, and must name the sweeps it covers; an exempt file that no longer// trips its sweep fails, so dead furniture is deleted.//// THE COLOUR RULE this defends: monochrome plus ONE accent. Colour never names// a KIND — a kind is a glyph and a word. NO user-chosen colour renders// anywhere. Destructive controls wear the ERROR tone, never the accent.//// Path ownership: everything swept is `apps/cotton/Sources/**` and// `apps/loom/Sources/**`. The generated file's SOURCE is// `crates/cotton-core/src/design/palette.rs`; drift against it is caught by// `pnpm gen:design:check`, not here.import { describe, expect, it } from"vitest";import { matches, typeSource, swiftSources, withoutComments } from"./helpers/swift-source-sweep";typeColourSweep = "hex" | "channels" | "systemNames" | "reachedByName";const allSweeps: ColourSweep[] = ["hex", "channels", "systemNames", "reachedByName"];/** The four ways this file sweeps for a colour. An exemption names one. */const patterns: Record<ColourSweep, string[]> = {// `#RRGGBB` and its shorter and longer forms. hex: [String.raw`#[0-9a-fA-F]{3,8}\b`],// `Color(red:`, `Color(hue:`, `UIColor(red:`, `.init(red:`. channels: [String.raw`Color\s*\(\s*red\s*:`, String.raw`Color\s*\(\s*hue\s*:`, String.raw`UIColor\s*\(\s*red\s*:`, String.raw`\.init\s*\(\s*red\s*:`],// `Color.red`, `UIColor.systemBlue` — somebody else's palette. systemNames: ["red", "orange", "yellow", "green", "mint", "teal", "cyan", "blue", "indigo", "purple", "pink", "brown", "white", "gray", "grey"].flatMap( (colour) => [String.raw`\bColor\s*\.\s*${colour}\b`, String.raw`\bUIColor\s*\.\s*${colour}\b`], ),// A colour reached by a STRING: these compile when the asset is gone and render nothing. reachedByName: [String.raw`Color\s*\(\s*white\s*:`, String.raw`Color\s*\(\s*"`, String.raw`UIColor\s*\(\s*named\s*:`],};interfacePaletteException { exemptFrom: ColourSweep[]; reason: string;}const material = (thing: string): string =>`${thing} The colour of a THING, not a palette role, and it does not flip with the theme. Built with \`Color(red:green:blue:)\`, the one constructor it is exempt from; it writes no hex and names nothing.`;/** Keyed on the path's TAIL, so a move INSIDE `Sources/` cannot silently widen it. */const allowed: Record<string, PaletteException> = {"Generated/Palette.swift": { exemptFrom: ["hex", "channels", "reachedByName"], reason:"the generated palette itself — the one place a colour is written, and it is generated from `crates/cotton-core/src/design/palette.rs` rather than authored. The hexes ARE its content; the channel constructors are how it turns one into a `Color`/`UIColor`; and `UIColor(named:)` is how it loads a colorset out of the bundle. It is NOT exempt from the system-name sweep: a generated file naming `Color.red` would mean the generator started inventing a palette.", },"CottonUI/Chrome/LookModel.swift": { exemptFrom: ["channels"], reason:"Look's colours as the core answers them (owner, 23 Nov 2026; shared/DECISIONS.md \"Look\"): the core's `look` says each app's tokens as hex for each appearance, and `LookAnswer.ui` is the one place they become a `UIColor`, the way the generated palette turns its own; before the core has answered, the app's own value is turned the same way. It writes no hex and names nothing.", },"CottonUI/Chrome/LookScreen.swift": { exemptFrom: ["hex"], reason:"Look's screen draws each paper's halves from the core's tokens; its one hex, a mid grey, stands only for a token the core's answer lacks, so the gap shows on the card instead of passing as the app's ink. It builds no colour from channels and names nothing.", },"CottonKit/Books/BookFile.swift": { exemptFrom: ["channels"], reason:"a PDF's first page drawn as the BOOK's cover, on the white paper the PDF format itself assumes (an unpainted page is transparent, and a JPEG has no transparency). It is the page's own paper in a picture of the book, kept as the book's cover, never a colour the app draws with: one `CGColor(red: 1, green: 1, blue: 1, alpha: 1)` fill under the page. It writes no hex and names nothing.", },"CottonUI/Notes/NotesLookSeed.swift": { exemptFrom: ["channels"], reason:"Words Dev's look seed paints one invented picture (a sky over sand) to attach to an invented note, in the Dev build only: the colours of a made-up photograph, never a palette role, built with `UIColor(red:green:blue:alpha:)` and drawn once into a PNG. It writes no hex and names nothing.", },"Theme/PrintInk.swift": { exemptFrom: ["channels"], reason:"the ink printed on a PHOTOGRAPHED object — cream on a dark ground, near-black on a light one — which is paint on a photograph and fixed the way the photograph is: it is the OBJECT's own colour, not a palette role. `PrintInk`'s two paints, both built once with `Color(red:green:blue:)`, the one constructor it is exempt from, and the one declaration Home's bottle caps and its tool objects (`ToolPrint`) both print with; the caps and the objects themselves are imagesets, not colours. It writes no hex and names nothing.", },"Theme/PaperDye.swift": { exemptFrom: ["channels"], reason:"the seven paper dyes, and the two paints that are not a dye — the instant print's card and its empty window. A PAPER IS A PHOTOGRAPH: every number here is the MEASURED mean colour of one of the six card masters, or of the news sheet in the owner's reference, divided by the grain tile's mean so paint times grain lands back on the photograph. It is the colour of a material, not a role of the design system. Built with `Color(red:green:blue:)`, the one constructor it is exempt from; it writes no hex and names nothing.", },"Theme/CapEnamels.swift": { exemptFrom: ["hex", "channels"], reason:"the twelve cap enamels as flat discs, for a theme whose caps are not photographs: each hex is the colour of the enamel read off its own `cap-<colour>` imageset, so a database keeps its colour when its cap flattens. The colour of an object, as the dyes are, not a palette role; one channel constructor is the unreachable fallback for a hex that cannot fail to parse.", },"Theme/MusicMaterial.swift": { exemptFrom: ["channels"], reason: material("the music's materials: the charcoal wool felt a cassette lies on, the dark inside its window, its tape and the figures on its counter, drawn live beside its painted case and shell, read off the owner's chosen music pictures as a dye is read off its photograph.", ), },"Theme/StoryMaterial.swift": { exemptFrom: ["channels"], reason:"Cotton Story's look (contract, 17 Nov 2026): its ground, sheet, inks, bubbles and its one warm-red accent, light and dark. The one app whose owner asked for both themes, so unlike a material these flip with the phone's appearance, inside a dynamic `UIColor` provider. Built with `UIColor(red:green:blue:alpha:)` (and `Color(.sRGB, red:…)` where UIKit is absent), the constructors it is exempt from; it writes no hex and names nothing.", },"Theme/GroundMaterial.swift": { exemptFrom: ["channels"], reason: material("the colours of the apps' own grounds where their tiles are not drawn: the kitchen tile, amethyst desk, pegboard, rose linen, burnt-orange felt, teal baize, pink terrazzo, teal-blue leather, checker floor and charcoal desk mat, each its painted tile's mean, as a dye is read off its photograph.", ), },"Theme/ReaderMaterial.swift": { exemptFrom: ["channels"], reason:"the colours of the reader's two papers where they are not painted: the page's cream and ink, the lamp's near-black, its pool, its off-white ink and its dim amber, read off the owner's chosen reader pictures as a dye is read off its photograph. The colour of a THING, not a palette role. Built with `Color(red:green:blue:)`, the one constructor it is exempt from; it writes no hex and names nothing.", },"Theme/BookFaceMaterial.swift": { exemptFrom: ["channels"], reason: material("the colours of the book reader's three faces and its three pencils: each face's ground, ink and secondary ink, and the red, yellow and teal a passage is underlined in, fixed off the pictures picked for Cotton Books.", ), },"Theme/NotebookMaterial.swift": { exemptFrom: ["channels"], reason: material("the colours of the notebook's things where they are not painted: the near-black a note's words are written in and the grey its date is typed in, the torn page's cream, rules and margin where a build carries no pictures, read off the owner's chosen note picture as a dye is read off its photograph.", ), },"Theme/TodosMaterial.swift": { exemptFrom: ["channels"], reason: material("the colours of the todos' things where they are not painted: the ribbon black a todo's index card is typed in, the grey its DONE ring is printed in and the pencil it is ticked in, the card's cream, rules and head rule, the tabs' salmon and red and the tray's enamel where a build carries no pictures,, read off the owner's chosen todo picture as a dye is read off its photograph.", ), },"Theme/PodcastMaterial.swift": { exemptFrom: ["channels"], reason: material("the colours of the podcast radio's things where they are not painted: the brown its dial's words and scale are printed in on the glass, the cream its VOL and TUNE are engraved in, the brown cut into its keys and plate, and the felt's own oxblood, read off the owner's chosen radio picture as a dye is read off its photograph.", ), },"Theme/PeopleMaterial.swift": { exemptFrom: ["channels"], reason: material("the colours of the people's things where they are not painted: the near-black a rolodex card is typed in, the ribbon's red, the graphite of the line pencilled at its foot, the card's cream and rules and a blank print's paper where a build carries no pictures, read off the owner's chosen rolodex picture as a dye is read off its photograph.", ), },"Theme/BooksMaterial.swift": { exemptFrom: ["channels"], reason: material("the colours of the books' things where they are not painted: the ink a blank jacket, a band and a highlight are set in, the typewriter's black on a band, a slip, a sticker and a spine label, the red of a sticker's stars, the gold a highlight's cloth is stamped in, the cloth's and a plain sleeve's own colours and the papers' creams for the stand-ins where a build carries no pictures, and the baize's own claret, read off the chosen book and film pictures as a dye is read off its photograph.", ), },"Theme/CinemasMaterial.swift": { exemptFrom: ["channels"], reason: material("the colours of the cinema's things where they are not painted: the near-black a marquee, a season card and a stub's day are typed in, the red a stub's stamp is struck in, the dark blue field and cream title of a one-sheet typed for a film kept without a poster, the shade a progress strip's track is taken down by, and the velvet's own red, read off the chosen Picture House materials as a dye is read off its photograph.", ), },"Theme/JournalMaterial.swift": { exemptFrom: ["channels"], reason: material("the colours of the journal's things where they are not painted: the blue-black a diary page is written in, the brown its date is printed in and its weather stamped, and the page's cream and rules, the cloth's navy and each mood's wax where a build carries no pictures, read off the painted diary as a dye is read off its photograph.", ), },"Theme/PagesMaterial.swift": { exemptFrom: ["channels"], reason: material("the colours of Cotton Pages' things where they are not painted: a clipping's grey newsprint and its torn edge, the near-black it is printed in and the grey of its small print and rules, its halftone's ink, and its bulldog clip's steel or, when the page is starred, its brass, each lit and shaded, read off the things as a dye is read off its photograph.", ), },"Theme/CallingMaterial.swift": { exemptFrom: ["channels"], reason: material("the colours of Cotton Calling's things where they are not painted: a call's memory slip's paper, the black and the red of its two-colour ribbon and the grey of its rules, a contact's ivory card and its ink, a photograph's white border, the warm glow behind a lit line key and the ink its glyph is moulded in, the gilt a call's words are tooled in on the leather, and the telephone's cream where a build carries no pictures, read off the painted telephone and the things themselves as a dye is read off its photograph.", ), },"Theme/PhotosMaterial.swift": { exemptFrom: ["channels"], reason: material("the colours of the Photos tool's things where they are not painted: a lab print's white border, drawn as a shape over its photograph, the orange of the date burned into it and its bloom, the near-black an album's label is typed in, and the bookcloth's oxblood, the cork, the pine, an instant print's card, the label's paper and the pins' brass where a build carries no pictures, read off the owner's chosen Photos pictures as a dye is read off its photograph.", ), },"Theme/MoneyMaterial.swift": { exemptFrom: ["channels"], reason: material("the colours of the money's things where they are not painted: a till's and a posting machine's ribbon, a cheque's dark-blue print and the blue-black hand that fills it, a bank stamp's violet, an account card's green print, a pencil, and the papers and clip where a build carries no pictures, read off the money pictures as a dye is read off its photograph.", ), },"Theme/HealthMaterial.swift": { exemptFrom: ["channels"], reason: material("the colours of Cotton Health's instruments where they are not painted: a hand's blued steel, the usual's red lacquer tick, a dial's print, a tag's engraving and the light its cut catches, the four blues of a night's stages, the period's rose mark and the chalk words are written on the slate in, and the brass, nickel and enamel where a build carries no pictures, read off the painted instruments as a dye is read off its photograph.", ), },"Story/StoryBook.swift": { exemptFrom: ["channels"], reason:"a character's tint as the core sends it (`cotton_core::rules::story_writing::Tint`, a fixed set the core picks from, never one a person chooses): the ink their initial is ringed in and the paper their speech is written on, turned from the core's hex into a `Color` with `Color(red:green:blue:)`, the one constructor it is exempt from. The colour is decided in the core, not written here; this file writes no hex and names nothing.", },"CottonFaces/Shared/FixturePictures.swift": { exemptFrom: ["channels"], reason:"the mean colour of one of the faces' own invented photographs, read off the picture's one-pixel draw — a colour the picture holds, handed on as a cover's tint, never one written here. Built with `Color(red:green:blue:)` from the pixel's channels, the one constructor it is exempt from; it writes no hex and names nothing.", },"CottonWriting/WritingTheme.swift": { exemptFrom: ["channels"], reason:"the writing surface's theme reader: it turns the `#RRGGBB` the core's writing themes answer (`notes.look`) into a `Color`/`UIColor`, as `ThemeColor` does for the shell's themes. Every colour is the core's; this file writes none. Built with `UIColor(red:green:blue:alpha:)` from the parsed channels, the one constructor it is exempt from.", },// Each app is its own object in its own colours, with no look shared between apps (owner, 20 Nov 2026):// Story's Ink, Days' Blue pen and Notes' standing theme are drawn from their own design files, not the palette."CottonUI/Chrome/AppLook.swift": { exemptFrom: ["hex"], reason:"the app looks the shell's own pieces (sign-in, recovery, the gate, the toasts) draw inside Story and Days: each is its app's `:root` from its design file (ink.html, pen.html), the same inks Android's `InkCardLook` and `DaysCardLook` hold. They are an app's own object colours, light and dark alike, not palette roles.", },"CottonUI/Chat/ChatWarm.swift": { exemptFrom: ["hex"], reason:"Cotton Chat's Warm look, warm.html's `:root` (assets/design/chat/DECISIONS.md \"Look\"), day and night: Chat's own object colours, read by role across every Chat screen and the shell's pieces inside Chat, not palette roles.", },"CottonUI/Chat/ChatWarmSeed.swift": { exemptFrom: ["channels"], reason:"Chat Dev's invented pictures for the simulator (an invented person's face tone, a video's warm frames, the local camera's stand-in), never in a store build: the colours of invented photographs, not palette roles. Built with `Color(red:green:blue:)` and `UIColor(red:green:blue:alpha:)`; it writes no hex.", },"CottonUI/Chat/ChatThread.swift": { exemptFrom: ["channels"], reason:"the thread's bubble shadow, warm.html's warm brown at six per cent: a shadow cast by Chat's own paper, not a palette role. Built with `Color(red:green:blue:)`; it writes no hex.", },"CottonUI/Boot/LaunchGround.swift": { exemptFrom: ["reachedByName"], reason:"The launch screen's own ground: each flat flavour's `LaunchGround` colour asset, written by gen-launch-screens.py, read by name so the splash's first frame is the colour the launch screen just laid.", },"CottonUI/Notes/NotesLook.swift": { exemptFrom: ["hex", "reachedByName"], reason:"Notes' app look: every ink is the core's standing writing theme except its safe tone and scrim, written here as hex, and its launch ground is the launch screen's own `LaunchGround` asset, read by name so the first frame matches the launch screen the app ships.", },"CottonUI/Story/Ink/InkLook.swift": { exemptFrom: ["channels"], reason:"Story's Ink look reader: `Color(ink:)` turns one of ink.html's `0xRRGGBB` inks into a `Color` (as `WritingTheme` does for the core's themes), for Story and Days, which draw their own design file's colours. Built with `.init(red:green:blue:)`; it writes no hex.", },"CottonWriting/WritingBar.swift": { exemptFrom: ["systemNames"], reason:"the writing keyboard's mark keys stand white on the light panel, as the phone's own keyboard keys do; on a dark panel they take the theme's ink. The phone's key colour, not a palette role.", },"Theme/ThemeDefaults.swift": { exemptFrom: ["channels"], reason:"the built-in themes, which take every chrome colour off the generated palette and write exactly two paints as channels: the ribbon a typewriter prints with (paint on a photograph, kept as the channels it has been written in since the todo card) and the black a shadow is cast in. Built with `ThemeColor(red:green:blue:)`, the one constructor it is exempt from; it writes no hex and names nothing.", },};const exemption = (file: string): PaletteException | undefined =>Object.entries(allowed).find(([tail]) => file.endsWith(tail))?.[1];/** The files that must be swept for ONE sweep — a file exempt from another sweep is still read for this one. */const swept = (sweep: ColourSweep): Source[] => swiftSources().filter((file) => exemption(file.name)?.exemptFrom.includes(sweep) !== true);/** Every `name: hits` for `sweep`'s patterns over the files swept for it. */function offenders(sweep: ColourSweep): string[] {const found: string[] = [];for (const { name, text } of swept(sweep)) {const code = withoutComments(text);for (const pattern of patterns[sweep]) {const hits = matches(pattern, code);if (hits.length > 0) found.push(`${name}: ${hits.join(", ")}`); } }return found;}describe("PaletteGuardTests", () => {// RULE: Every sweep reads more than 120 files: a number much below that means the walk stopped walking, not that the app shrank. it("the sweep reads more than the allowed file", () => {for (const sweep of allSweeps) {const count = swept(sweep).length; expect(count, `the ${sweep} sweep read ${count} files — it would pass on nothing`).toBeGreaterThan(120); } });// RULE: No Swift source outside the generated palette writes a hex colour of its own. it("no Swift source writes a hex of its own", () => { expect(offenders("hex"), "these write their own colour — read it off CottonColors").toEqual([]); });// RULE: No Swift source builds a colour from channels (Color(red:, Color(hue:, UIColor(red:, .init(red:) unless exempt from that sweep with its reason. it("no Swift source builds a colour from channels", () => { expect(offenders("channels"), "these build a colour from channels").toEqual([]); });// RULE: An exemption that no longer earns its keep is furniture: every file exempt from a sweep must still exist and still TRIP that sweep. it("every exemption is still earned", () => {const sources = swiftSources();for (const [tail, exception] ofObject.entries(allowed)) {const file = sources.find((source) => source.name.endsWith(tail)); expect(file, `${tail} is allow-listed and no longer exists — delete the entry`).toBeDefined();if (!file) continue;const code = withoutComments(file.text);for (const sweep of exception.exemptFrom) {const hits = patterns[sweep].flatMap((pattern) => matches(pattern, code)); expect( hits.length,`${tail} is exempt from the ${sweep} sweep and no longer trips it. Delete that sweep from its entry — an exemption nobody needs is the space the next one grows into.`, ).toBeGreaterThan(0); } } });// RULE: No Swift source names a system colour (Color.red, UIColor.systemBlue…): a system colour is somebody else's palette and follows the system's appearance, which this app must not acquire by the back door; `.black` stays allowed for shadows. it("no Swift source names a system colour", () => { expect(offenders("systemNames"), "these name a system colour").toEqual([]); });// RULE: No Swift source reaches a colour by name (Color(white:), Color("…"), UIColor(named:)) — it compiles when the asset is gone and renders nothing. it("no Swift source reaches a colour by name", () => { expect(offenders("reachedByName"), "these reach a colour by name").toEqual([]); }); it("the system colour sweep would actually catch one", () => {const sample = 'let a = Color.red\nlet b = UIColor.systemBlue\nlet c = Color(white: 0.5)\nlet d = Color("ground")\n'; expect(matches(String.raw`\bColor\s*\.\s*red\b`, sample)).not.toEqual([]); expect(matches(String.raw`Color\s*\(\s*white\s*:`, sample)).not.toEqual([]); expect(matches(String.raw`Color\s*\(\s*"`, sample)).not.toEqual([]);// And it must leave the design system's own accessors alone. expect(matches(String.raw`\bColor\s*\.\s*red\b`, "let ground = CottonColors.ground; let ink = CottonColors.inkSecondary")).toEqual([]); });// RULE: Every allowed file carries a reason worth reading and names the sweeps it covers — never all four, which is the whole-file exemption this shape exists to stop. it("gives each allowed file a reason worth reading", () => {for (const [path, exception] ofObject.entries(allowed)) { expect(exception.reason.length, `${path}: a reason worth reading`).toBeGreaterThan(40); expect(exception.exemptFrom.length, `${path} is exempt from nothing in particular — name the sweep`).toBeGreaterThan(0); expect(newSet(exception.exemptFrom).size,`${path} is exempt from every sweep, which is the whole-file exemption this shape exists to stop. Name the sweeps its sentence justifies.`, ).toBeLessThan(allSweeps.length); } });});