// Plain-language guard — user-visible product copy uses standard software // terms, never the retired internal metaphors (the owner's ruling, 2026-08-27: // "door", "shelves", "rooms" and the gazette-era voice are out of everything // a user or an assistant reads). // // This file guards FOUR roots: the APP CATALOG (every user-visible string the // app ships), the two sources of the generated AGENTS.md — the partials and // the generator itself — and, since step 5's R19, the SITE's user-facing // literals. (`docs/` was swept too until it was emptied on 2026-09-26.) The MCP tool // descriptions have their own typed guard in // packages/server/__tests__/toolLanguage.test.ts, and the phone's and the // Mac's Swift sources have theirs in each app's `LanguageSweepTests.swift`. // `RETIRED_TERM_READERS` at the foot of this file names all six sweeps and // proves no sixth reader of the declaration exists unlisted (four since the site became four plain pages on 8 Nov 2026, swept here). // // AGENTS.md itself is NOT guarded, on purpose: half of it is the owner's own // memory sentences, and his words are never edited by a test. What can be held // is everything the repo writes around them — which is exactly where the // generator's `ROOM_PLACEHOLDER` ("room block not rendered") sat, rendering a // retired metaphor into the doc every agent loads whenever the generator ran // without credentials. import { existsSync, readFileSync, readdirSync } from "node:fs"; import { join, relative, sep } from "node:path"; import ts from "typescript"; import { describe, expect, it } from "vitest"; const ROOT = join(__dirname, "..", ".."); // WHERE THE DICTIONARY COMES FROM (step 5, R18). A term is retired in the RUST // CORE lane — `crates/cotton-core/src/language/` — and a // `cargo test` there renders the list to the JSON below and fails on drift, the // same guarantee `gen:check` gives. This sweep runs on Node and cannot read a // Rust `const`, so it reads that file BY PATH; the read is asserted before any // comparison, because a sweep over an empty list is a sweep that passes while // the rule goes unenforced. If the path moves, the emitting test and this // reader move together. Regenerate the file with: // COTTON_UPDATE_RETIRED_TERMS=1 cargo test -p cotton-core --lib language::emit const RETIRED_TERMS_JSON = join( ROOT, "crates", "cotton-core", "src", "language", "retired-terms.json", ); interface RetiredTerm { /** Stable id, so a test can assert coverage without matching prose. */ slug: string; pattern: RegExp; /** What to say instead — this is the message a failing guard prints. */ instead: string; } interface EmittedTerm { slug: string; pattern: string; instead: string; } interface Emitted { /** The flags a JavaScript reader must apply — `i`, and deliberately not `u`. */ flags: string; terms: EmittedTerm[]; strict: EmittedTerm[]; } function readOrNull(path: string): string | null { try { return readFileSync(path, "utf8"); } catch { return null; } } let cached: { terms: RetiredTerm[]; strict: RetiredTerm[] } | null = null; /** * The emitted dictionary, read once. The read and its emptiness are asserted * here — before any caller compares anything — so a moved or truncated file is * a loud failure naming the path rather than every sweep quietly turning green. */ function dictionary(): { terms: RetiredTerm[]; strict: RetiredTerm[] } { if (cached) return cached; const raw = readOrNull(RETIRED_TERMS_JSON); expect( raw, `the retired vocabulary is not at ${RETIRED_TERMS_JSON} any more — it is emitted there by ` + "`cargo test -p cotton-core --lib language::emit`, which is the one place a term is " + "retired; find where it moved to and update this reader with it", ).not.toBeNull(); const emitted = JSON.parse(raw as string) as Emitted; expect( emitted.terms?.length ?? 0, `${RETIRED_TERMS_JSON} carries no terms — a sweep over an empty dictionary passes over ` + "every retired metaphor in the repo", ).toBeGreaterThan(0); expect(emitted.flags, `${RETIRED_TERMS_JSON} must name the flags to apply`).toBe("i"); const compile = (term: EmittedTerm): RetiredTerm => ({ slug: term.slug, instead: term.instead, // `i` and NOT `u`: the declared patterns match the ASCII word class and // fold case within ASCII only, which is what every vector pinning them was // captured against. pattern: new RegExp(term.pattern, emitted.flags), }); cached = { terms: emitted.terms.map(compile), strict: emitted.strict.map(compile) }; return cached; } /** * Catalog values allowed to trip a pattern — each one is plain English that * happens to share a word with a banned metaphor. Keep this list short and * justified; a new entry needs the same scrutiny as a new metaphor. */ const ALLOWED_VALUES = new Set([ // Disk space, not the app-section metaphor. "There isn't room to record. Free up about {room} and try again.", "There isn't room to record. Free up some space and try again.", // A sample todo about a real shelf on a real wall, not the app-section metaphor. "Put up the hallway shelf", // Cinemas' empty film table, its first open: a seat in a cinema, not the group-member metaphor. "A seat for your first film.", // Trips' boarding pass (cards.trip.seat): the seat printed on a ticket, a real seat on a plane or train, not the group-member metaphor. "SEAT", ]); /** * Phrases on the site allowed to trip a pattern: the legal English of the terms, not a metaphor. Same scrutiny as * ALLOWED_VALUES. */ const SITE_ALLOWED_PHRASES = [ // The terms' liability sentence (owner's words, 23 Nov 2026): the law of the land, not the project-rule metaphor. "To the extent the law allows", ]; describe("plain product language", () => { it("the phone's string catalogue carries no retired metaphor", () => { // Was `packages/i18n/catalogs/en-GB.json`, the Lingui catalogue, which went // with the Expo app in step 5c. The phone's sentences now live in an Xcode // string catalogue — the same 3,101-ish strings, a different container. // // THE PATH BELONGS TO THE PHONE LANE, so the read fails LOUDLY and names it // before any sweep runs: a sweep over an empty catalogue is a guard that // passes over nothing, which is the whole failure this file exists to stop. const catalogPath = join( ROOT, "apps", "cotton", "Sources", "CottonUI", "Resources", "Localizable.xcstrings", ); expect( existsSync(catalogPath), `${catalogPath} is missing — the phone lane owns this path. Move this ` + `sweep with it rather than letting it run over nothing.`, ).toBe(true); const parsed = JSON.parse(readFileSync(catalogPath, "utf8")) as { strings?: Record; }>; }; const entries = Object.entries(parsed.strings ?? {}); // THE PHONE'S WORDS MOVED (22 Oct, the `refactor(lines)` rows). Its // sentences now ship as the shell's line snapshot the app bundles — // `CottonValues/Resources/lines/.json`, byte copies of the kit's line // files — and the catalogue keeps only what Xcode itself still needs. So // the sweep reads both containers, and the floor below counts both: a // sweep that kept reading only the catalogue would pass over the words a // person actually reads. const linesDir = join(ROOT, "apps", "loom", "Sources", "CottonValues", "Resources", "lines"); expect( existsSync(linesDir), `${linesDir} is missing — the phone lane owns this path. Move this ` + `sweep with it rather than letting it run over nothing.`, ).toBe(true); const lines: Record = {}; const gather = (label: string, node: unknown): void => { if (typeof node === "string") lines[label] = node; else if (Array.isArray(node)) node.forEach((child, i) => gather(`${label}[${i}]`, child)); else if (node && typeof node === "object") { for (const [key, child] of Object.entries(node)) gather(`${label}.${key}`, child); } }; for (const file of readdirSync(linesDir).filter((name) => name.endsWith(".json")).sort()) { const { format_version: _version, id: _id, ...set } = JSON.parse( readFileSync(join(linesDir, file), "utf8"), ) as Record; gather(`lines/${file.replace(/\.json$/, "")}`, set); } // A floor, not a headcount. It catches the two shapes that make this sweep // meaningless — an empty parse and a truncated write — and it is set well // under today's size on purpose: the catalogue GROWS as the phone's screen // lanes land (4b onward), and a floor that tracks the ceiling turns into a // second thing to remember on every one of them. expect( entries.length + Object.keys(lines).length, "the catalogue parsed to no strings", ).toBeGreaterThan(25); // A key IS the source string in an Xcode catalogue, and a localisation may // restate it; both are swept, because either can carry the metaphor. const catalog: Record = {}; for (const [key, entry] of entries) { catalog[key] = key; for (const [locale, unit] of Object.entries(entry.localizations ?? {})) { const value = unit.stringUnit?.value; if (typeof value === "string") catalog[`${key} [${locale}]`] = value; } } Object.assign(catalog, lines); const violations: string[] = []; for (const [key, value] of Object.entries(catalog)) { if (typeof value !== "string") continue; if (ALLOWED_VALUES.has(value)) continue; for (const { pattern, instead } of dictionary().terms) { if (pattern.test(value)) { violations.push(`${key}: ${JSON.stringify(value)} — ${instead}`); } } } expect(violations, violations.join("\n")).toEqual([]); }); /** * The one line allowed to carry every banned term: the dictionary itself, * which names them in order to retire them. Identified by the ruling slug it * cites, so the exemption cannot silently spread to a second line. */ const DICTIONARY_LINE = "[product-language-must-be-plain-software-tool-terms-everywhere-us]"; /** * Line-by-line, against whichever list the root earns. * * The AGENTS.md partials and the generator take the STRICTER list: * stricter than the catalog's list on ONE word, because those two sources * never talk about disk space, so a bare `room` there is always the retired * metaphor — which is what "room block not rendered" was, and what the * narrow pattern the catalog needs would have let straight through. * * The site takes the PLAIN list, which is what R19 says: it genuinely talks * about disk space, a physical room and a bounding box, and the narrow * patterns are the ones written for exactly that. */ function sweep( label: string, text: string, violations: string[], terms: readonly { pattern: RegExp; instead: string }[] = dictionary().strict, ): void { text.split("\n").forEach((line, i) => { if (line.includes(DICTIONARY_LINE)) return; for (const { pattern, instead } of terms) { if (pattern.test(line)) { violations.push(`${label}:${i + 1}: ${line.trim().slice(0, 120)} — ${instead}`); } } }); } /** Every retired term a piece of text trips, by slug. */ function violationsIn(text: string): string[] { return dictionary() .terms.filter(({ pattern }) => pattern.test(text)) .map(({ slug }) => slug); } it("guards every term the dictionary retires", () => { // The AGENTS.md language section names twelve metaphors. A guard that // checks four of them is a guard that says the rule is enforced when it is // not. The last three are not metaphors at all — they are sentences the // product must never say — and they live in the Rust declaration so the one // list carries them here and to both Swift sweeps (R19). const covered = dictionary() .terms.map((term) => term.slug) .sort(); expect(covered).toEqual([ "box", "canon", "door", "law", "life-record", "mark", "model-on-device", "nudge", "pack", "room", // The hosted multi-account database, retired: no shared database, no // account row, no row-level policy. "row-level-security", "seat", "shelf", "the-memory-room", "your-file", ]); }); it.each([ ["a seat", "Two seats left in this group."], ["a nudge", "Send a nudge."], ["a law", "The laws that bind this project."], ["the box", "Restart the box."], ["the mark", "Change the mark."], ["the pack", "Read the pack before you start."], ["a door", "Open the door to your database."], ["a life record", "Every life record you keep."], ["a promise about where the model runs", "The AI runs on your Mac."], ])("catches %s", (_label, text) => { expect(violationsIn(text)).not.toEqual([]); }); it.each([ ["Mark read"], ["Mark all as read"], ["Cotton writes it down, marks who spoke, and keeps the audio."], ["There isn't room to record. Free up some space and try again."], ["Unpack the archive"], ["Your inbox is empty."], ])("does not catch plain English: %s", (text) => { expect(violationsIn(text)).toEqual([]); }); // AGENTS.md IS HAND-WRITTEN AND SHORT NOW, so it is swept whole where its // partials used to be swept one by one. The partials and their generator went // on 2026-09-26 with everything in the repo that was not code: the procedures // an agent used to read as skills are Cotton notes, and only a stub that // points at them is left here. it("AGENTS.md carries no retired metaphor", () => { const violations: string[] = []; sweep("AGENTS.md", readFileSync(join(ROOT, "AGENTS.md"), "utf8"), violations); sweep("CLAUDE.md", readFileSync(join(ROOT, "CLAUDE.md"), "utf8"), violations); expect(violations, violations.join("\n")).toEqual([]); }); // ── The site, and the living documentation (step 5, R19) ───────────────── /** * Every file under `dir` the filter keeps, as repo-relative paths. * * A DIRECTORY WALK, never a file list: a three-file list is green on the day * a fourth file starts writing sentences, which is the whole failure mode * this sweep exists to prevent. */ function walk(dir: string, keep: (path: string) => boolean): string[] { const found: string[] = []; for (const entry of readdirSync(dir, { withFileTypes: true })) { if (entry.name === "node_modules" || entry.name === "dist") continue; const full = join(dir, entry.name); if (entry.isDirectory()) found.push(...walk(full, keep)); else if (keep(full)) found.push(relative(ROOT, full)); } return found.sort(); } /** * Rule (a) of AGENTS.md's "a guard that reads another package's file BY PATH" * — a read that finds NOTHING fails LOUDLY, with the path in the message, * before any regex runs. A sweep over an empty file list is a pass. */ function mustFind(paths: string[], root: string): string[] { expect( paths.length, `no files found under ${root} — did the tree move? Grep that path repo-wide ` + `(__tests__ and every open worktree included) before changing this guard.`, ).toBeGreaterThan(0); return paths; } /** * Every string a VISITOR could read out of a TypeScript/TSX source: string * literals, the fixed chunks of a template, and JSX text. * * Literals ONLY, and that is the judgement call in this root. R19 gives the * sweep "the site's user-facing literals", not the site's code — a sweep * over identifiers would demand a rename of somebody else's public API to * satisfy a rule about product copy. Comments are out for the same reason the Swift sweeps * strip them: a rule written down in prose beside a rule being kept must not * fail the rule. */ function userFacingLiterals(source: string, name: string): { line: number; text: string }[] { const parsed = ts.createSourceFile( name, source, ts.ScriptTarget.Latest, true, name.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS, ); const out: { line: number; text: string }[] = []; const visit = (node: ts.Node): void => { const isChunk = ts.isStringLiteralLike(node) || ts.isJsxText(node) || node.kind === ts.SyntaxKind.TemplateHead || node.kind === ts.SyntaxKind.TemplateMiddle || node.kind === ts.SyntaxKind.TemplateTail; if (isChunk) { const value = (node as ts.LiteralLikeNode).text; if (value.trim()) { out.push({ line: parsed.getLineAndCharacterOfPosition(node.getStart(parsed)).line + 1, text: value, }); } } node.forEachChild(visit); }; visit(parsed); return out; } it("the site's pages and user-facing literals carry no retired metaphor", async () => { const site = join(ROOT, "apps", "cotton-site"); const sources = mustFind( walk(join(site, "src"), (path) => path.endsWith(".ts") || path.endsWith(".tsx")), "apps/cotton-site/src", ); const violations: string[] = []; for (const name of sources) { for (const { line, text: value } of userFacingLiterals( readFileSync(join(ROOT, name), "utf8"), name, )) { if (value.includes(DICTIONARY_LINE)) continue; for (const { pattern, instead } of dictionary().terms) { if (pattern.test(value)) { violations.push( `${name}:${line}: ${value.replace(/\s+/g, " ").trim().slice(0, 120)} — ${instead}`, ); } } } } // The pages themselves: the whole of each is copy, so each is swept whole, // with the HTML comments taken out first. Since 3102ac9d8e the site's pages // are rendered by src/site/pages.ts (renderSite, what build.ts writes to // dist/); the internal apps page still stands as a file beside them. // By a path, so the scripts' type check does not walk into the site's own project. const pagesModule = join(site, "src", "site", "pages.ts"); const { renderSite } = (await import(pagesModule)) as { renderSite: () => Record }; const rendered = renderSite(); for (const name of ["index.html", "404.html", "privacy.html", "terms.html"]) { expect(Object.keys(rendered), `apps/cotton-site renders no ${name}: did the pages move?`).toContain(name); } const files = readdirSync(site).filter((name) => name.endsWith(".html")).sort(); const pages: Array<[string, string]> = [ ...Object.entries(rendered).map(([name, html]): [string, string] => [`apps/cotton-site (rendered) ${name}`, html]), ...files.map((name): [string, string] => [`apps/cotton-site/${name}`, readFileSync(join(site, name), "utf8")]), ]; for (const [where, html] of pages) { expect(html.length, `${where} is empty`).toBeGreaterThan(0); const swept = SITE_ALLOWED_PHRASES.reduce((t, phrase) => t.replaceAll(phrase, ""), html.replace(//g, "")); sweep(where, swept, violations, dictionary().terms); } expect(violations, violations.join("\n")).toEqual([]); }); /** * THERE IS NO `docs/` SWEEP ANY MORE, because there is no `docs/`. It was * emptied on 2026-09-26 under the owner's rule that only code lives in the * repository: the specs, plans, dated accounts, subsystem pages and runbooks * all became notes in Cotton, and every rule a test could hold became a test. * The sweep that used to walk those pages was REMOVED rather than repointed — * a sweep whose directory is gone reads nothing and passes, which is the * failure this whole file exists to make loud. * * **WHAT NO SWEEP READS, said out loud:** Rust and the CI workflow YAML. * This file walks `apps/cotton-site`, AGENTS.md, CLAUDE.md and one named * script; `LanguageSweepTests` walks `apps/cotton/Sources`; `language_tests.rs` * sweeps the crate's own declared product strings, not its comments. So a * retired term in a `.rs` comment, in a Cotton note, or in a * `.forgejo/workflows` file is caught by a reader or not at all. Extending a sweep to either is a change of its own; * what must not happen is a reader believing they are covered. */ }); /** * ONE DECLARATION, FOUR READERS. * * `packages/core/src/language/retiredTerms.ts` is the only place a retired * term is declared, and step 5's R19 widened who has to obey it. The value of * "one declaration" is entirely in the count of readers being KNOWN: a sweep * that quietly stops reading the list, or a sixth surface that quietly starts, * is the same failure — a rule enforced somewhere and free somewhere else. * * So the readers are named here, and the two directions are both held: * * • every sweep named below exists, and still names the declaration; * • every file in the tree that reads the declaration is named below, * either as a sweep or as a carrier, so a sixth cannot appear unlisted. * * Discovery is by the TypeScript AST rather than by grep, so that a file which * merely MENTIONS `RETIRED_TERMS` in a comment (`recipes.ts`, `templates.ts` * and `moneyLanguage.ts` all do) is not counted as a reader, and a file that * reads it is counted whether it imports the symbol or loads the emitted * `retired-terms.json` (R18's second form, which 5e moves this file onto). */ describe("one declaration, four readers", () => { interface Sweep { /** What it sweeps, in words — this is the list the count is pinned to. */ name: string; /** The file that implements it, repo-relative. */ file: string; } const SWEEPS: readonly Sweep[] = [ { name: "the app catalog, AGENTS.md and CLAUDE.md", file: "scripts/__tests__/plainLanguage.test.ts", }, { name: "the site's pages and user-facing literals", file: "scripts/__tests__/plainLanguage.test.ts", }, { name: "the MCP tool surface — every name, title, description and parameter", // Rust since the flip: `retired_hits` is the sweep and `language_tests.rs` // drives it over every tool definition and every recipe. file: "crates/cotton-tools/src/mcp/language.rs", }, { name: "the phone's Swift sources", file: "apps/cotton/Tests/CottonUITests/LanguageSweepTests.swift", }, ]; /** * Reads the declaration, but enforces nothing — these CARRY the list to a * surface rather than sweeping one, and each needs its sentence. */ const CARRIERS: readonly { file: string; why: string }[] = [ { file: "crates/cotton-core/src/language/retired_terms.rs", why: "the declaration itself, since the flip folded the file that was generated into the one that wrapped it", }, { file: "crates/cotton-core/src/language/emit_json_tests.rs", why: "renders the declaration to the JSON this sweep reads, and fails on drift — the seam between Rust and Node", }, { file: "crates/cotton-gen/src/retired.rs", why: "carries the list into both apps' Generated/RetiredTerms.swift, where the two Swift sweeps read it", }, ]; /** Names the declaration in CODE — comments and strings that merely say the * words do not count. `retired-terms.json` is R18's emitted form. */ function readsTheDeclaration(source: string, name: string): boolean { const parsed = ts.createSourceFile( name, source, ts.ScriptTarget.Latest, true, name.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS, ); let found = false; const visit = (node: ts.Node): void => { if (found) return; if (ts.isIdentifier(node) && /^RETIRED_TERMS(_STRICT)?$/.test(node.text)) found = true; else if (ts.isStringLiteralLike(node) && node.text.includes("retired-terms.json")) found = true; else node.forEachChild(visit); }; visit(parsed); return found; } function walkFiles(dir: string, keep: (path: string) => boolean): string[] { const found: string[] = []; for (const entry of readdirSync(dir, { withFileTypes: true })) { if (entry.name === "node_modules" || entry.name === "dist" || entry.name === "target") continue; const full = join(dir, entry.name); if (entry.isDirectory()) found.push(...walkFiles(full, keep)); else if (keep(full)) found.push(relative(ROOT, full)); } return found.sort(); } it("names four sweeps, and each one's file is still there and still reads the list", () => { expect(SWEEPS.map((s) => s.name)).toEqual([ "the app catalog, AGENTS.md and CLAUDE.md", "the site's pages and user-facing literals", "the MCP tool surface — every name, title, description and parameter", "the phone's Swift sources", ]); for (const { name, file } of SWEEPS) { let source: string | null = null; try { source = readFileSync(join(ROOT, file), "utf8"); } catch { source = null; } expect( source, `could not read ${file} — the sweep over ${name} names it. Did the file move? ` + `Grep that path repo-wide (__tests__ and every open worktree included).`, ).not.toBeNull(); // The Swift halves reach the list through the generated `RetiredTerms` // type rather than through the TypeScript symbol, so the token differs. const token = file.endsWith(".swift") ? "RetiredTerm" : "RETIRED_TERMS"; expect(source, `${file} no longer names ${token} — it has stopped reading the declaration`) .toContain(token); } }); it("no sixth reader of the declaration exists unlisted", () => { const listed = new Set([...SWEEPS.map((s) => s.file), ...CARRIERS.map((c) => c.file)]); const typescript = ["scripts", "apps"].flatMap((top) => walkFiles(join(ROOT, top), (path) => /\.tsx?$/.test(path)), ); const found = typescript.filter((name) => { const source = readFileSync(join(ROOT, name), "utf8"); // Cheap pre-filter; the AST decides. if (!/RETIRED_TERMS|retired-terms\.json/.test(source)) return false; return readsTheDeclaration(source, name); }); // The Swift sweeps read the GENERATED vocabulary, not a TypeScript symbol, // so they are discovered by their own shape: a `LanguageSweepTests.swift` // under an app's Tests tree is a sweep by definition. const swift = walkFiles(join(ROOT, "apps"), (path) => path.endsWith(`${sep}LanguageSweepTests.swift`), ); expect(found.length, "the AST discovery found nothing — did the walk roots move?") .toBeGreaterThan(0); expect(swift.length, "no LanguageSweepTests.swift found under apps/").toBeGreaterThan(0); const unlisted = [...found, ...swift].filter((name) => !listed.has(name)).sort(); expect( unlisted, `these files read the retired vocabulary but are named in neither SWEEPS nor CARRIERS:\n` + `${unlisted.join("\n")}\n` + `Add each one — a sweep with what it sweeps, a carrier with why it is not a sweep.`, ).toEqual([]); // The other direction: nothing listed has quietly stopped being found. // The Rust readers are named above for the map and are held by `cargo // test`, not by this walk — it parses TypeScript and reads Swift by shape, // and neither can see a `.rs` file. Excluding them here is what keeps the // other direction honest for the files this walk CAN reach. const discovered = new Set([...found, ...swift]); const missing = [...listed] .filter((file) => !discovered.has(file) && !file.startsWith("crates/")) .sort(); expect( missing, `named as a reader but not discovered — it has stopped reading the declaration, ` + `or it moved:\n${missing.join("\n")}`, ).toEqual([]); }); it("every carrier says why it is not a sweep", () => { for (const { file, why } of CARRIERS) { expect(why.length, `${file} needs a sentence saying why it carries the list, not sweeps`) .toBeGreaterThan(20); } }); });