Claude Skill

ubiquitous-language

Maintain a project thesaurus (domain glossary) following DDD ubiquitous language principles. Use PROACTIVELY when naming anything: variables, functions, classes, modules, database fields, API endpoints, events, files, or directories. Also use when the user asks to "create thesaur

LLM Mart · 0 points · 4 views 0 listing impressions 0 install-command copies
Download CodeAlive-AI-ai-driven-development-skills_ubiquitous-language-b1fbfa4.zip · 64 KB

Install

skills CLI npx skills add https://github.com/CodeAlive-AI/ai-driven-development/tree/main/skills/ubiquitous-language
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install codealive-ai-ai-driven-development@llmmart
Git git clone https://github.com/CodeAlive-AI/ai-driven-development.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole codealive-ai/ai-driven-development collection as a plugin from our marketplace. Git is the plain clone.

README

ubiquitous-language

Maintain a project thesaurus (domain glossary) following DDD ubiquitous language principles. Ensures all names in the codebase are consistent, descriptive, and aligned with the shared domain vocabulary.

Install

npx skills add CodeAlive-AI/ai-driven-development@ubiquitous-language -g -y

Quick start

After installing, try these in your project:

> Create a domain thesaurus for this project
> What should I call the entity that tracks user payments?
> Audit naming consistency in this codebase
> Resolve the unresolved naming issues using the git history

What it does

Four modes:

Mode When What loads
Naming consultation Every time the agent names anything SKILL.md (~590 lines)
Thesaurus generation User asks to create/update the thesaurus references/generating-thesaurus.md (~540 lines)
Naming audit User asks to check naming consistency references/naming-audit.md (~280 lines)
History mining (optional) Unresolved naming ambiguities need evidence references/git-history-mining.md (~425 lines) + scripts/git_term_index.py (~1310 lines)

Naming consultation (frequent)

Before proposing any name, the agent greps the project's THESAURUS.md for every candidate name and acts on the shape of the hit line (Index, Forbidden, Legacy, Unresolved, or nothing). If the concept is new, it tries four levers before minting a new term: Reuse, Compose, Qualify, Ask. Includes DDD naming rules for aggregates, entities, value objects, events, commands, queries, services, and repositories.

The grep-first thesaurus layout

THESAURUS.md is shaped so that one rg for any name answers "what do I do with this name?". Registry sections are one-line-per-item bullet lists with labelled tokens — not Markdown tables, because | is an alternation in ripgrep (the Grep tool of most agents), tables match by column position, and formatters re-pad them.

## Index                      ← one line per concept, every name for it
- **Order** `Order` kind:aggregate avoid: `Purchase`, `Transaction`, `Buy`
- **Account** `Account` kind:aggregate ctx:Billing avoid: `Wallet`, `Balance`

## Terms                      ← `### Term` entries: Definition / NOT / Related
## Forbidden                  ← - `Manager` use: `OrderFulfillment` — hides responsibility
## Legacy                     ← - `Basket` → `Cart` in: `api/v1/basket.ts` — renamed v2
## Unresolved                 ← `### Term — problem` entries awaiting a decision
rg -n -i 'basket'            # any role — the shape of the hit line tells you the section
rg -n 'avoid:.*`Purchase`'   # banned synonym → the canonical Identifier is at line start
rg -n 'kind:event'           # all events;  rg 'ctx:Billing' → everything one context owns
rg -n -F '**Order**'         # exact Term, not "Order Line Item"
rg -n '^### Order( \(|$)'    # the entry itself
  • Registry invariant: every name appears in exactly one registry line, so the shape of a hit gives its status and the line gives the canonical name — no -B/-A context reading.
  • Identifier is the PascalCase code form — what agents actually see in code and grep for; Term stays in the domain's own language (**Счёт-фактура** `Invoice` ).
  • Backticks around every name make rg '`Order`' an exact match that skips OrderLineItem.
  • kind: selects the DDD naming rule; ctx: appears only once bounded contexts are confirmed.
  • Existing thesauri (prose-only or table-index) are migrated in one pass without changing a definition.

Thesaurus generation (rare)

Scans high-signal structural files (DB schemas, API contracts, domain layer, directory structure) to extract domain terms. Separates active from legacy/obsolete terms. Collects ambiguities into an ## Unresolved section, then surfaces them to the user for resolution. Updates agent instruction files (CLAUDE.md, GEMINI.md, etc.) so the thesaurus is used even without the skill installed.

History mining (optional, offered at the end of generation)

The ## Unresolved section is the honest part of a mined thesaurus — the questions the current tree cannot answer. Git history often can. After generation (and after an audit), the skill offers to build a throwaway index of the repository's history and come back with evidence-backed proposals per unresolved item.

python3 scripts/git_term_index.py build --repo-dir . --content
python3 scripts/git_term_index.py query Account Customer
python3 scripts/git_term_index.py pair User Customer
python3 scripts/git_term_index.py contexts Account
python3 scripts/git_term_index.py search 'rename account'
python3 scripts/git_term_index.py clean

The index is dependency-free Python 3.9+ (stdlib sqlite3, only git required) and lives as a single SQLite file in $TMPDIR, never in the working tree. Commit messages go into an FTS5 table so message search is ranked by BM25 relevance, not recency; identifiers from every added/removed diff line go into an identifier × commit × file table with add/delete counts. Each identifier carries a casing-independent normal form, so OrderLineItem, order_line_item and ORDER_LINE_ITEM are one concept — which is what makes a PascalCase thesaurus Identifier findable in a snake_case codebase.

Per-file granularity is what makes the common case answerable. One commit touches many files, so commit-level co-occurrence cannot localise a name (measured: one identifier's directory distribution was 74% "wherever the code is"). With per-file rows the tool answers the flagship ## Unresolved question — Account in billing/ vs auth/ — directly: contexts Account shows the directory split, and pair reports files: A in N, B in M, both in K. both in 0 is evidence for two bounded contexts; shared files mean synonym drift. It also sharpens renames: an exchange inside one file outranks "both names appear somewhere in one commit".

The whole diff history is indexed, not a recent window — that is the difference between "born" and "first seen in the last N commits". Measured: git.git's full 21-year history builds in 111 s (232 MB), kubernetes' 12 years / 82 704 commits in 249 s (1 040 MB); queries then run in 0.1–1.3 s. Walking history per-term with git log -S instead costs 4 s per term on git.git and 84–98 s per term on kubernetes.

What that buys per ambiguity: birth (which spelling is the incumbent, and what the introducing commit said), dormancy (nothing has touched this name in years → retired vocabulary), trajectory (deletions ≫ additions = being phased out), ranked swap commits (the commits that remove one name while adding the other, strongest exchange first — these are the renames), the path split (do any files contain both names? which directories does each occupy? — the bounded-context signal), and stated intent from BM25-ranked messages and PR references.

pair ends in one labelled verdict — RENAME (strong / probable / possible), DRIFT, NOT A RENAME, or COEXISTENCE — with the direction inferred from the evidence rather than from argument order.

The thresholds behind those labels were set by falsification, not taste. Every one was added after a measured false positive on a real repository:

Rule The false positive that forced it
A swap needs a net exchange (≥3 each way), not any deletion + any addition 105 of 174 commits touching two unrelated integrations were labelled rename candidates — including commits where both names were net-removed
Identifiers carry a casing-independent normal form query OrderLineItem returned "never appears" on a snake_case repo — a false negative on the skill's own canonical input, since thesaurus Identifiers are PascalCase
Comparing two names uses concepts, not families the Account set contained BillingAccount, so its additions cancelled Account's deletions and masked the exchange
Exchanges must clear a noise floor (≥2 commits and ≥5% of shared commits) bisect/rebase in git.git: 2 exchanges in 145 shared commits read as "drift"
Same-file exchanges clear a lower bar, but still a bar making any same-file swap sufficient put bisect/rebase straight back to RENAME on 2 swaps in 111 commits
A rename announcement must name both sides "Rename Telegram meeting wrapper" certified club → meeting
Dormancy measured from last growth, not last touch git.git's get_sha1 was last touched in 2026 by a commit deleting a stale comment; last grown in 2017
Locale and changelog files excluded .po files made "l10n: zh_CN …" the top rename candidate for unrelated terms

Measured after those fixes: 18 negative controls across three repositories → zero false rename verdicts (the worst of them reaches 6 same-file exchanges in 1 193 shared commits and no naming subject), while every known rename — including kubernetes' Minion→Node, which lands with 35 same-file swaps and 6 announcing subjects — still lands as RENAME — strong.

Other defaults from measurement: HEAD only (side branches carry release notes and imported trees — on git.git, --all dated oid_array to a status email three days before the actual rename commit), vendored/generated/minified paths excluded, merges excluded. Shallow clones, truncated windows, and names present in the oldest indexed commit are each flagged in every report rather than silently producing a confident wrong date.

Known limits, stated in the skill: pair compares identifiers, so a rename that only moved files surfaces in query's file-renames section instead; and polysemy — one word meaning two things in two modules, the most common real ## Unresolved entry — is the weakest case for history mining, which will honestly return COEXISTENCE and leave the decision to the user.

Findings are reported in one batch with a confidence level and the commits behind each proposal; nothing is applied until the user approves, and each applied decision cites its commit (— renamed in a41f2c9 on the Legacy line, or a - **History**: entry line). History is treated as evidence of what happened, never as authority on what a term should be — it ranks candidates, the user decides. Squashed imports, shallow clones, bulk reformatting commits, and vendored code are called out as the failure modes they are.

Naming audit (periodic)

9-check protocol: thesaurus integrity (registry invariant, Index ↔ Terms), synonym violations, forbidden words, technical jargon leaks, synonym drift, polysemy, translation chains, abbreviation inconsistency, orphan terms. The Index is the audit's work-list. Produces a structured report grouped by severity (Critical / Warning / Info) with recommended fix priority.

Key features

  • Grep-first thesaurus — one labelled line per concept, registry invariant, exact-match backticks; built for agents that navigate by rg, not by reading whole files
  • Codebase is primary evidence, not automatic authority — supports both "as-is" (document current naming) and "to-be" (define target vocabulary) modes
  • Flat-first thesaurus — no bounded contexts by default; only introduced when polysemy is confirmed by the user with the invariant test
  • Forbidden list (lexical firewall) — maintained list of words banned from the domain layer (weasel words, implementation details)
  • Polysemy unpacking — detects overloaded terms and forces disambiguation into explicit facets
  • Cross-context bridges — when bounded contexts exist, one line per bridge with a SKOS mapping (exactMatch … relatedMatch, distinct) and loss notes
  • Git-history mining for ambiguities — a throwaway SQLite index (built outside the repo, deleted after) over the full diff history: BM25-ranked commit messages, renames, and every identifier's birth, dormancy and swap commits; proposes rename / deprecate / two-concepts / drift verdicts with citations and confidence, never silently
  • Legacy term tracking — continuity relations (rename/split/merge/retire/deprecate) with alias parsimony
  • Framework-aware — doesn't fight Active Record patterns; distinguishes domain noun from framework coupling
  • Language-agnostic — works with any programming language, no framework-specific rules
  • Non-English domain support — uses the domain's original language for canonical terms

Sources and methodology

This skill was built through a structured research and review process:

Primary sources

  1. Domain-Driven Design by Eric Evans — ubiquitous language, bounded contexts, aggregate naming, anti-corruption layers
  2. Learning Domain-Driven Design by Vlad Khononov — practical DDD patterns including brownfield adoption strategy, co-creation (not extraction) of domain language, tacit knowledge handling, translation chain anti-pattern, thesaurus scoping heuristics
  3. First Principles Framework (FPF) — formal tools for semantic precision:
    • A.1.1 U.BoundedContext — bounded contexts as declared semantic frames with the invariant test for justification
    • A.6.8 Service Polysemy Unpacking — "can you X it?" disambiguation tests for overloaded terms
    • A.6.9 Cross-Context Sameness Disambiguation — bridges with loss notes, direction, and relationship types
    • E.5.1 DevOps Lexical Firewall — protecting domain vocabulary from transient implementation jargon
    • F.2 Term Harvesting & Normalisation — context-local harvesting discipline
    • F.5 Naming Discipline — "name what the invariants make true", minimal generality
    • F.13 Lexical Continuity & Deprecation — five continuity relations (rename/alias/split/merge/retire)
    • F.14 Anti-Explosion Control — "four levers before minting a new name"
  4. ISO 25964 / SKOS — label model (prefLabel / altLabel / notation), BT/NT/RT relations and their integrity rules, mapping vocabulary for cross-context bridges — see Standards alignment
  5. Martin Fowler, Vaughn Vernon — bounded context maps, anti-corruption layers, context boundaries as language boundaries

Web research

  • DDD ubiquitous language best practices and common failures (synonym drift, naming chaos, acronym problems)
  • Domain glossary/thesaurus management formats and standards
  • DDD naming rules by construct type (aggregates, entities, value objects, events, commands)
  • Naming anti-patterns in domain code (weasel words, technical jargon leaks, implementation-driven naming)
  • Codebase auditing approaches for naming consistency

Multi-agent review

The skill was reviewed by external AI agents (OpenAI Codex CLI / GPT-5.4 and Google Gemini CLI / Gemini 3.1 Pro) via the pragmatic-orchestration skill for independent, unbiased assessment. The review identified 6 critical operational issues:

  1. Scanning impossibility — original instructions assumed whole-codebase scanning; replaced with bounded high-signal hub strategy
  2. O(N^2) audit check — field-overlap comparison replaced with grep-friendly stem+suffix heuristics
  3. External system assumptions — translation chain check rewritten for local-only filesystem access (git log, test descriptions, local docs)
  4. Missing language idiom exceptions — added durability boundary: DDD naming for domain-bearing identifiers, standard idioms (err, ctx, i) exempt
  5. Source of truth dogma — "trust the code" replaced with "code is evidence, not authority" with explicit brownfield/legacy override
  6. Framework antagonism — added caveat for Active Record patterns where domain and persistence are intentionally blended

Design decisions

  • Progressive disclosure: SKILL.md (naming consultation) loads on every trigger; references load only on demand — saves ~700 lines of context on the common path
  • Grep-first over read-everything: agents consult the thesaurus on every naming task, so lookup cost matters more than prose quality. The Index (one line per concept) is cheap to read whole; everything else is reached by a single rg whose hit is self-describing. Avoid lists live only in the Index so there is one place to drift from — none
  • Labelled lines, not tables, for registry data: Index, Forbidden (use:) and Legacy (→, in:) are one-line facts with position-free tokens — greppable without escaping |, immune to formatter re-padding, and each line's shape reveals its section. Definitions and open questions stay as prose entries
  • Non-English domains get two columns, not a compromise: Term holds the experts' word, Identifier the code form, so the thesaurus is greppable from either side
  • Flat-first thesaurus: bounded contexts are opt-in, not default — the agent cannot reliably determine context boundaries, so it surfaces evidence and asks the user
  • Unresolved section: ambiguities collected during scanning, surfaced as a batch after file creation — no blocking questions during generation
  • Agent instruction updates: after creating the thesaurus, the skill updates CLAUDE.md/GEMINI.md/etc. so the thesaurus works even without the skill installed
  • History as evidence, not authority: mining is an offer made after the Unresolved list is shown, not an automatic step, and it produces ranked hypotheses with commit citations — the user still makes every call. The index is deliberately throwaway (temp dir, one command to delete) rather than a committed artifact: it is derived data, it goes stale on the next commit, and nothing in a repository should be generated into the working tree
  • No format change: history provenance rides in existing free-text — the note tail of a ## Legacy line, or an optional - **History**: entry line — so thesaurus-format stays 2.0 and no migration is needed

Standards alignment

The layout is a plain-Markdown projection of a SKOS concept scheme (ISO 25964-compatible) — exportable to RDF/JSON-LD if ever needed, without being written in it.

Thesaurus SKOS / ISO 25964
**Term** skos:prefLabel — one per concept and context
`Identifier` skos:notation — machine code, distinct from the label
avoid: skos:altLabel + skos:hiddenLabel (ISO 25964: UF, use-for)
Definition / NOT skos:definition / skos:scopeNote
Broader / Narrower / Related BT / NT / RT — written on one side only, rg gives the inverse
### Term (Context) ISO 25964 homograph qualifier
Legacy `Old` → `New` owl:deprecated + skos:historyNote; A + B = compound equivalence
Bridge mapping skos:exactMatch … relatedMatch (+ explicit distinct); never owl:sameAs
Unresolved → Index → Legacy concept status: candidate → approved → deprecated

Deliberately not borrowed: ConceptScheme/Collection, facets, OWL axioms, RDF serialisation — kind:/ctx: and prose NOT cover the need without the weight.

Versioning

  • Skill: metadata.version in SKILL.md frontmatter (semver). Current: 2.1.0.
  • Thesaurus format: stamped in every THESAURUS.md as YAML frontmatter — thesaurus-format: "2.0", skill: ubiquitous-language. One rg '^thesaurus-format:' tells an agent which grammar to expect; a missing key means format 1.0 (the pre-index prose layout).
  • Format major = skill major. The skill reads any format ≤ its own and writes only the current one; a major gap triggers the one-pass migration, a minor gap only adds optional tokens.
  • Format history lives in references/generating-thesaurus.md → "Format history".

File structure

ubiquitous-language/
├── SKILL.md                         # Naming consultation (loaded on every trigger)
├── README.md                        # This file
├── references/
│   ├── generating-thesaurus.md      # Thesaurus generation workflow
│   ├── naming-audit.md              # 9-check naming audit protocol
│   └── git-history-mining.md        # Resolving `## Unresolved` items from git history
└── scripts/
    └── git_term_index.py            # Throwaway SQLite/FTS5 history index (build/query/pair/contexts/search/clean)

License

MIT

Skill manifest

Ubiquitous Language: Project Thesaurus Manager

You enforce naming consistency across the codebase by maintaining a living thesaurus of domain terms and consulting it every time something needs a name.

Four modes:

Foundations

This skill combines two bodies of knowledge:

  • Domain-Driven Design (DDD) by Eric Evans — ubiquitous language, bounded contexts, aggregate naming
  • First Principles Framework (FPF) — a transdisciplinary "operating system for thought" that provides formal tools for semantic precision: bounded contexts as declared semantic frames, polysemy unpacking, lexical firewalls, cross-context bridges with loss notes, term continuity relations, and anti-explosion naming control. References like "FPF F.5" or "FPF A.1.1" point to specific sections of the FPF specification.

Core Principle

"A project should use a single, shared vocabulary. Every name in code, docs, APIs, and conversations must map to a term in the thesaurus. If a concept isn't in the thesaurus — add it before naming anything."

— Domain-Driven Design, Eric Evans

The codebase is primary evidence, not automatic authority. Use code to discover which terms are currently in circulation. Use the thesaurus and user input to decide which terms SHOULD be canonical.

  • For what exists today — derive from code (classes, DB schemas, API routes, events)
  • For what should become the standard — ask the user/domain expert
  • If code contradicts the approved thesaurus — the thesaurus wins for new code
  • If the user says "fix legacy naming" — the user's directive overrides the codebase; map existing code names to ## Legacy lines and use the user's terms as canonical

Tacit knowledge: For areas not yet implemented, the most important domain knowledge exists only in experts' heads, not in any artifact.

Thesaurus File

Locating the thesaurus:

  1. If the user specified a path — use it
  2. If THESAURUS.md already exists somewhere in the repo — use that location
  3. Default: docs/THESAURUS.md

Single source of truth for domain vocabulary.

Versioning

The thesaurus declares its format version and the skill that maintains it in YAML frontmatter — machine-readable, outside the body, still one grep away:

---
thesaurus-format: "2.0"
skill: ubiquitous-language
---

# Project Thesaurus

Quote the version — unquoted 2.10 is the YAML float 2.1.

  • rg -n '^thesaurus-format:' THESAURUS.md → the version in one hit. No key = 1.0 (the pre-index prose layout shipped before skill 2.0) — unless the file already has - **Term** `Id` kind: Index lines: that is an unstamped 2.0 file from plugin 9.2.0; just add the stamp.
  • Format major = skill major (metadata.version in this file's frontmatter). Skill minor/patch releases never change the format.
  • Read any format ≤ your own; write only the current one. A major gap means migration first (see generating-thesaurus.md); a minor gap means new optional tokens — older readers keep working, you may add the tokens as you touch lines.
  • A thesaurus with a format newer than yours: read it, don't rewrite it — tell the user to update the skill.
  • Only the format is versioned in the file. The skill's own version is not recorded there — it would go stale on every edit and git log already answers "who wrote this". skill: is a pointer, so an agent without the skill knows what to install.
Format Layout Skill
1.0 ### Term entries with Synonyms to AVOID; ## Legacy Terms entries; ## Forbidden Lexicon table ≤ 1.x (plugin ≤ 9.1.1)
2.0 grep-first: ## Index lines with kind:/ctx:/avoid:, use: Forbidden lines, → Legacy lines, SKOS bridges 2.x

Layout: grep-first

The file is designed so that one rg/grep for any name answers "what do I do with this name?" without reading the surrounding text. Five sections, fixed order:

Section Shape One line answers
## Index one line per concept "Is there a term for this? Which name is canonical? What is banned?"
## Terms ### Term entries "What exactly does it mean / not mean / relate to?"
## Forbidden one line per word "Is this word banned from domain names?"
## Legacy one line per old name "This old name is in the code — what replaced it?"
## Unresolved ### Term — problem entries "Is this name an open question?"

Registry invariant: every name known to the project appears in exactly one registry line — an Index line (as Term, Identifier, or avoid), a Forbidden line, a Legacy line, or an Unresolved header. Each kind of registry line has its own shape, so the shape of the hit tells you its status and the line itself tells you the canonical name. No -B/-A context needed.

Registry lines are bullet lines with labelled tokens, not Markdown tables: tables need | (an alternation in rg), match by column position, and get re-padded by formatters. Tokens (kind:, ctx:, avoid:, use:, in:, →) are position-free, formatter-proof, and need no escaping.

# Project Thesaurus

## Index

- **Order** `Order` kind:aggregate avoid: `Purchase`, `Transaction`, `Buy`
- **Order Line Item** `OrderLineItem` kind:entity avoid: `LineItem`, `OrderItem`, `Item`
- **Order Placed** `OrderPlaced` kind:event avoid: `OrderCreated`, `NewOrder`

## Terms

### Order
- **Definition**: A customer's confirmed request to buy one or more products at agreed prices.
- **NOT**: A payment (that's `Payment`), a shipment, or a draft cart (that's `Cart`).
- **Related**: Order Line Item, Order Placed, Cart

## Forbidden

- `Manager` use: `OrderFulfillment` — hides responsibility; name the activity

## Legacy

- `UserManager` → `Customer` + `CustomerRegistration` in: `src/legacy/` — split in v3

## Unresolved

### Account — one word, two concepts (billing vs auth)
- **Found in**: `billing/Account.ts` (balance), `auth/Account.ts` (login)
- **Question**: Two bounded contexts, or one of them a naming mistake?
- **Impact**: 18 files
- **Options**: `BillingAccount` + `UserAccount`; or contexts Billing / Identity

Index line

- **<Term>** `<Identifier>` kind:<kind> [ctx:<Context>] [avoid: `<name>`, `<name>`]
Field Content Rules
Term Human name, as domain experts say it, in **bold** May be multi-word or non-English. Also the ### header text of the entry
Identifier PascalCase code form, in backticks The thing you grep in code. All other casings derive from it mechanically (see Casing)
kind: One of aggregate entity value event command query service role process state policy concept Picks the naming rule below. concept when nothing fits
ctx: Bounded context name Only present once contexts are confirmed (see generating-thesaurus.md); the header then becomes ### Term (Context)
avoid: Banned synonyms and abbreviations, each in backticks, comma-separated Last on the line because it is the only variable-length field. Omit when empty
  • One line per concept. All names for that concept live on that line — this is what makes reverse lookup (rg Purchase → "use Order") a single hit.
  • Backticks around every identifier-like name. rg '`Order`' is an exact match; rg Order would also hit OrderLineItem and Reorder. rg -F '**Order**' is the exact Term.
  • Sorted alphabetically by Term. Entries under ## Terms follow the same order.
  • avoid lists live only here. Entries do not repeat them — one place, no drift.

Forbidden and Legacy lines

- `<Word>` use: `<Identifier>`[, `<Identifier>`] — <why>
- `<OldName>` → `<Identifier>`[ + `<Identifier>`] in: <files/modules> — <note>
- `<OldName>` → — (see `<X>`, `<Y>`) in: <files> — retired

use: always points at an Index Identifier. → is the legacy marker: A + B means the old name was split; → — means retired with no single successor.

Entry

### [Term]
- **Definition**: What this concept means in the business domain — one sentence
- **NOT**: What this term does NOT mean; name the neighbouring term it is confused with
- **Related**: Other Index Terms this connects to, written exactly as in the Term field

Optional lines when they carry real information: **Broader**, **Narrower**, **Part of**, **Has parts**, **Example**. Write them on one side only — rg gives the inverse for free, mirrored copies only drift. Minimal viable entry is one line: - **Definition**: … — the Index line already holds the rest.

Anchor grammar (so lookups are one regex): the header is exactly ### <Term> or ### <Term> (<Context>) — nothing else. Tags, status, and context prefixes belong in the Index line, not in the header. Find an entry with rg -n '^### Order( \(|$)' — \b alone is not enough, it would also match ### Order Line Item.

The thesaurus captures concepts, not behavior. It's strong at nouns (entity names, roles, process names) but won't replace behavioral specs for business rules. Don't try to turn the thesaurus into a specification — keep entries short. If a concept has a critical invariant, note it briefly in the definition, not as a separate section.

Non-English domains: If the business domain operates in a non-English language, the Term uses the original language — the thesaurus should reflect how domain experts actually speak. The Identifier carries the code form: - **Счёт-фактура** `Invoice` kind:entity. This is exactly why both fields exist.

Lookup Protocol

Look up before inventing. This is the single most important step. Most naming tasks don't need a new term — the right name is already there.

  1. Locate the thesaurus (see above). If absent, tell the user and offer generation. Check rg -n '^thesaurus-format:' — no key or 1.x means the old layout: the protocol below still works by plain text search, but offer migration once, up front.

  2. Read the Index if it has ≤ ~60 lines — it is the entire vocabulary at one line per concept, cheaper than any search. For larger files, search instead.

  3. Search every candidate name you are considering, plus whatever the surrounding code already calls the thing. Use rg (the Grep tool) or grep -E — same patterns:

    rg -n -i 'invoice' docs/THESAURUS.md             # any role, any section
    rg -n '`OrderLineItem`' docs/THESAURUS.md        # exact identifier as seen in code
    rg -n -F '**Order**' docs/THESAURUS.md           # exact Term (not "Order Line Item")
    rg -n 'avoid:.*`Purchase`' docs/THESAURUS.md     # is this word a banned synonym?
    rg -n 'kind:event' docs/THESAURUS.md             # all terms of one kind
    rg -n 'ctx:Billing' docs/THESAURUS.md            # everything one context owns
    rg -n '`Basket` →' docs/THESAURUS.md             # legacy name and its replacement
    rg -n -A4 '^### Invoice( \(|$)' docs/THESAURUS.md  # the entry itself
    

    The only trap: * and | are regex metacharacters — use -F for **Term**, and never search for table pipes (there are none).

  4. Act on the shape of the line you hit:

    Hit line looks like Meaning Do
    - **X** `X` kind:… — your word is the Term or Identifier Concept exists Use the Identifier exactly. Stop
    - **X** … avoid: … `your word` You were about to use a banned synonym Use that line's Identifier instead
    - `word` use: … Word is banned from domain names Pick the Identifier after use:
    - `word` → … Old name still in code Use the replacement after → for new code; don't spread the legacy name
    ### word — … under ## Unresolved Open naming question Don't decide silently — surface it, ask the user, or offer history mining (see below)
    ### header / entry text only Related concept Read the entry; it may inform composition
    No hit New concept Go to "If the concept is new"
  5. Check the bounded context if Index lines carry ctx: — the same word may be canonical in one context and banned in another.

ALWAYS run this before naming: classes, interfaces, types, enums, aggregates, entities, value objects, functions, methods, commands, queries, domain events, variables, constants, fields, parameters, DB tables/columns/collections, API endpoints and response fields, files, directories, modules, packages, feature flags, config keys, environment variables, and commit messages or PR titles that reference domain concepts.

If the Concept Is New

Before minting a new term, try four levers (from FPF F.14 "Name less, express more"):

  1. Reuse — does an existing term already cover this? Maybe the concept is a variant, not a new thing
  2. Compose — can you combine existing terms? OrderLineItem reuses Order + LineItem
  3. Qualify — is this the same concept in a different state/window? Don't create NightOperator — use Operator with a time qualifier
  4. Ask — if still unclear: "I need to name [concept]. The thesaurus doesn't have a term for this. What does the domain call it?" If the user doesn't have an answer either — that's a white spot, not a dead end. Building a ubiquitous language is co-creation, not extraction. Add it to ## Unresolved with a [WHITE-SPOT] tag in the header. Don't force a name for an undefined concept.

Only after all four fail, mint a new term:

  1. Name what the invariants make true (FPF F.5) — don't name aspirationally. If the code doesn't enforce "Premium", don't call it PremiumCustomer
  2. Use minimal generality — choose the narrowest name whose rules you actually enforce. Don't upgrade Task to Activity to sound universal
  3. Keep it to 1-3 words — no rhetorical adjectives ("robust", "optimal", "advanced")
  4. Add it to the thesaurus: an Index line (Term, Identifier, kind:, avoid: — omit avoid: when empty) and a ### Term entry with at least a Definition. Keep both sorted
  5. Then use the term in code

If You Find an Inconsistency

When existing code uses a term that contradicts the thesaurus:

  • Flag it: "Found fetchPurchases() but the Index line says Order, with Purchase under avoid:"
  • Suggest a rename if scope is small
  • For large-scale renames, note as tech debt and ask user how to proceed

If the Ambiguity Won't Resolve Itself

When a name lands in ## Unresolved — two spellings for one concept, one spelling for two concepts, no obvious winner — the current tree can't settle it, but the repository's history often can: which identifier was born first, which commit removed one while adding the other, which one is dying.

Offer it, don't run it silently. Whenever you present ## Unresolved items — after generation, after an audit, or when a naming question hits one — offer once:

"I can mine the git history for these — when each name was born, which replaced which, which is growing vs dying. Temporary index outside the repo, deleted afterwards. Want me to try that before you answer them by hand?"

Skip the offer if there is no .git, history is shorter than ~50 commits or squashed from an import, or the items are [WHITE-SPOT] tags (an unnamed concept leaves no trace).

If the user accepts, read references/git-history-mining.md and follow it. The short version:

S=<skill-dir>/scripts/git_term_index.py
python3 $S build --repo-dir . --content   # throwaway SQLite index in $TMPDIR, never in the repo
python3 $S query Account Customer         # birth, dormancy, trajectory, renames, messages
python3 $S pair User Customer             # competing names: birth order + swap commits
python3 $S contexts Account               # where the name lives — the polysemy check
python3 $S search 'rename account'        # BM25 search over commit messages
python3 $S clean                          # delete the index when done

The index covers the whole diff history, so "born" means born. Use --pathspec src/ on large repos — it cuts build time and sharpens the signal at once.

pair ends in a labelled verdict — RENAME (strong / probable / possible), DRIFT, NOT A RENAME, COEXISTENCE — with the direction inferred from evidence, not argument order. Report the label as given; do not upgrade it. "RENAME — strong" means commits exchange the names and a subject announces it; everything weaker needs git show first.

For polysemy (one word, two meanings, two modules) use the path split: pair prints files: A in N, B in M, both in K, and contexts <name> gives the directory breakdown for a single word. both in 0 — no file ever contained both — is real evidence for two bounded contexts; shared files mean synonym drift, which history cannot settle. Only claim a path split when the tool printed one. File-only renames (the file moved, the identifier did not) appear in query's file-renames section, not in pair — run both.

History is evidence, not authority. It ranks candidates and cites commits; the user decides. Report proposals in one batch with confidence levels, apply only what is approved, and record the commit behind each applied decision (— renamed in a41f2c9 on the Legacy line, or a - **History**: line on the entry).

Naming Rules by DDD Construct

The Index Kind column selects the rule.

Aggregates & Aggregate Roots (aggregate)

Use the business domain term. Singular. No technical suffixes.

GOOD: Order, Invoice, UserAccount, ShoppingCart
BAD:  OrderAggregate, OrderRoot, OrderAggregateImpl, OrderEntity

Entities (entity)

Singular noun from the domain. Something with identity.

GOOD: OrderLineItem, PaymentTransaction, Customer
BAD:  OrderLineItemEntity, OrderLineItemImpl, OrderLineItemObj

Value Objects (value)

Singular noun describing an immutable concept. Describes what it is, not what it does.

GOOD: Money, Email, PhoneNumber, Address, DateRange
BAD:  MoneyValue, EmailValidator, PriceInfo, AmountData

Domain Events (event)

Past tense verb + noun. Something that happened.

GOOD: OrderPlaced, PaymentCaptured, InvoiceSent, InventoryReserved
BAD:  OrderEvent, OnOrderPlaced, CreateOrder (that's a command)

Commands (command)

Imperative verb + noun. An action requested.

GOOD: CreateOrder, CancelInvoice, ProcessRefund, ReserveInventory
BAD:  OrderCreated (that's an event), NewOrder, OrderCommand

Queries (query)

Question or retrieval. Verb + object or descriptive name.

GOOD: GetOrderById, FindInvoicesByCustomer, ListPendingOrders
BAD:  RetrieveOrderData, OrderQuery, GetterForOrder

Domain Services (service)

Named after business activities the domain expert recognizes.

GOOD: InvoiceCalculator, OrderFulfillment, NotificationSender
BAD:  OrderManager, GenericService, HelperService

Repositories

Repository suffix is acceptable — it's an infrastructure pattern. Repositories are not thesaurus terms; they take the name of the aggregate they store.

GOOD: OrderRepository, InvoiceRepository, CustomerRepository
BAD:  OrderStorage, OrderPersistence, OrderFinder, OrderDao

Methods on Aggregates

Commands (change state): Imperative verb, no "Get" prefix.

GOOD: order.Cancel(), order.AddLineItem(product, quantity), order.Recalculate()
BAD:  order.CancelOrderMethod(), order.GetCancelled(), order.DoCancelOrder()

Queries (read-only): Start with Get, Is, Has, Can, or a domain verb.

GOOD: order.GetTotal(), order.IsExpired(), order.CanBeShipped()
BAD:  order.FetchInfo(), order.CheckData()

Naming Anti-Patterns to Detect and Flag

Lexical Firewall: the ## Forbidden section

The domain layer must be protected from transient jargon, vague terms, and implementation details. The thesaurus's ## Forbidden section lists words that MUST NOT appear in domain names and must always be replaced with a specific domain term.

Weasel Words (never use in domain layer)

Weasel Word Problem Fix
Info Meaningless suffix Remove it: UserInfo -> User
Data Says nothing about the concept Use domain term: OrderData -> Order
Manager Vague, hides responsibility Split by actual responsibility
Handler Generic, unclear intent Name after what it handles
Service Overused catch-all Use specific domain activity name
Base Technical distraction Remove, use composition
Item Too generic Use domain term: Item -> OrderLineItem, Product
Util / Helper Indicates bad design Move logic to domain objects
Object / Obj Never appropriate Remove suffix
Record / Model Database concept leaking into domain Use domain term
Config / Settings Generic container hiding a concept Config -> LoanProduct, Settings -> NotificationPreferences

Technical Jargon in Domain Layer

Domain code must be free of implementation details:

BAD:  MongoOrder, SqlUserRepository, HttpOrderService, OrderDto, OrderEntity
GOOD: Order, OrderRepository (interface), PaymentGateway, Order (just Order)

Technical prefixes/suffixes belong ONLY in the infrastructure layer, and even there the domain role should lead:

INFRASTRUCTURE LAYER (OK): MongoOrderRepository, RedisSessionCache, HttpPaymentClient
DOMAIN LAYER (NEVER):      MongoOrder, RedisSession, HttpPayment
NAME THE ROLE, NOT THE TECH: SessionStore not RedisCache, EventPublisher not KafkaProducer

Framework caveat: In frameworks that intentionally blend domain and persistence (Active Record pattern, ORM-centric frameworks), the model IS the domain entity. Keep the domain noun clean and let framework coupling live in inheritance, annotations, or metadata — not in the class name. Flag technical jargon only when it becomes part of the business-facing name or leaks outside its boundary.

Synonym Drift

Same concept called different things in different parts of code:

PROBLEM: "Customer" in auth, "User" in API, "Account" in billing — all mean the same thing
FIX:     Pick ONE canonical term per bounded context. Put the others in that line's `avoid:` list.

Abbreviation Boundary

Ban abbreviations in durable, domain-bearing names: types, exported functions, modules, API fields, DB columns, events, config keys.

Allow conventional short-lived local identifiers when meaning is obvious in scope: i, j, ctx, req, res, err, tx, db, e for events.

Allow industry-standard acronyms when they are the dominant term: SKU, VAT, URL, ID, OAuth. Do NOT force unnatural expansions if experts use the acronym.

PROBLEM: usr, user, account, acct — competing abbreviations for the same durable concept
FIX:     Pick ONE canonical form for domain-bearing names. Short-lived locals are exempt.

Translation Chain ("Telephone Game")

When different artifacts use different terms for the same concept across the knowledge chain, information is lost at each translation:

SMELL: Domain expert says "Campaign" → PM writes "Promotion" in spec →
       Dev codes `marketing_push` → QA tests "advertising effort"
FIX:   Same term everywhere: expert, PM, dev, QA all say and write "Campaign"

This is worse than synonym drift because each translation also loses nuance and business rules. How to detect: compare terms in requirements/specs/tickets against code names. If they don't match, the ubiquitous language has a translation gap — adopt the domain expert's term everywhere.

Casing Conventions

The Index Identifier is PascalCase. Every other form is derived from it mechanically using the project's conventions — never re-worded:

Context Convention Example (Identifier: OrderLineItem)
Class/Type PascalCase OrderLineItem
Function/Method Project convention addOrderLineItem / add_order_line_item
Variable Project convention orderLineItem / order_line_item
Constant UPPER_SNAKE MAX_ORDER_LINE_ITEMS
Database table Project convention order_line_items
API endpoint kebab-case or convention /orders/{id}/line-items
Event/Message PascalCase with past-tense verb OrderLineItemAdded
File/Directory Project convention order_line_item.py, OrderLineItem.cs

Key rules:

  • Use the EXACT Identifier — don't abbreviate (ord), don't expand (orderObject), don't synonym (purchase)
  • Compound names combine Identifiers: OrderLineItem, not PurchaseLineItem
  • Technical suffixes for infrastructure roles are fine: OrderRepository, OrderDTO (in infra layer only)
  • Multi-word Identifiers keep all words in every casing: ProcessingStage → processing_stage, never proc_stage
  • Variables and parameters use full descriptive names: totalAmount not amt, customerEmail not cEmail

Updating the Thesaurus

When changing terms, use the least strong relation that tells the truth (from FPF F.13):

Operation When Effect on thesaurus
Add New concept Index line + entry. Minimum: Identifier, kind:, Definition
Rename Wording improved, sense unchanged Change Term/Identifier in the Index line and header; old Identifier → ## Legacy line `Old` → `New`; grep codebase, suggest renames
Split One term covered two senses Old line removed; two new lines + entries; old Identifier → ## Legacy line `Old` → `A` + `B`; disambiguation in each NOT
Merge Two terms are really one sense Keep one line; the other Identifier moves into its avoid: list; entries merged
Retire Term was misleading, no single successor ## Legacy line `Old` → — (see `X`, `Y`)
Deprecate Concept being phased out ## Legacy line with → replacement and in: locations

Key test: Can you point to the same concept before and after the change?

  • Yes, same concept, better wording → Rename (keep as legacy alias for reading old code)
  • No, the concept actually changed → Split or Merge (not a rename)

Alias parsimony: keep at most 1 legacy alias per term — the one readers will most likely encounter in old code. Registry invariant still holds after every edit: a name is under avoid: or in Legacy, never both.

Old layout? No thesaurus-format frontmatter key (or 1.x) means the pre-index prose layout — see "Migrating an Existing Thesaurus" in references/generating-thesaurus.md.

Quick Checklist Before Naming Anything

  1. Did I grep the thesaurus for this name and its synonyms? Where did the hit land?
  2. Would a domain expert recognize this name?
  3. Does it contain a weasel word (Manager, Service, Handler, Info, Data, Item, Base, Util)?
  4. Is it too generic (could mean multiple things in different contexts)?
  5. Does it reveal infrastructure details (Mongo, Sql, Http, Dto, Entity, Model)?
  6. Is it consistent with other uses of this term across the codebase?
  7. Am I using the EXACT Identifier from the Index, or a synonym from its avoid: list?
  8. Am I in the right bounded context for this term?
  9. Does the name match its Kind — past tense for event, imperative for command?
  10. Can I explain what this name represents in one sentence using domain language?
  11. If the concept is new — did I add the Index line and the entry before using it?

If any answer raises a concern — stop and fix before proceeding.

Files (ai-driven-development)
  • references
    • generating-thesaurus.md 25.4 KB
      Loading…
    • git-history-mining.md 24.9 KB
      Loading…
    • naming-audit.md 11.2 KB
      Loading…
  • scripts
    • git_term_index.py 56.9 KB
      Loading…
  • README.md 20.2 KB
    # ubiquitous-language
    
    Maintain a project thesaurus (domain glossary) following DDD ubiquitous language principles. Ensures all names in the codebase are consistent, descriptive, and aligned with the shared domain vocabulary.
    
    ## Install
    
    ```bash
    npx skills add CodeAlive-AI/ai-driven-development@ubiquitous-language -g -y
    ```
    
    ## Quick start
    
    After installing, try these in your project:
    
    ```
    > Create a domain thesaurus for this project
    > What should I call the entity that tracks user payments?
    > Audit naming consistency in this codebase
    > Resolve the unresolved naming issues using the git history
    ```
    
    ## What it does
    
    Four modes:
    
    | Mode | When | What loads |
    |------|------|-----------|
    | **Naming consultation** | Every time the agent names anything | `SKILL.md` (~590 lines) |
    | **Thesaurus generation** | User asks to create/update the thesaurus | `references/generating-thesaurus.md` (~540 lines) |
    | **Naming audit** | User asks to check naming consistency | `references/naming-audit.md` (~280 lines) |
    | **History mining** (optional) | Unresolved naming ambiguities need evidence | `references/git-history-mining.md` (~425 lines) + `scripts/git_term_index.py` (~1310 lines) |
    
    ### Naming consultation (frequent)
    
    Before proposing any name, the agent greps the project's `THESAURUS.md` for every candidate name and acts on the shape of the hit line (Index, Forbidden, Legacy, Unresolved, or nothing). If the concept is new, it tries four levers before minting a new term: Reuse, Compose, Qualify, Ask. Includes DDD naming rules for aggregates, entities, value objects, events, commands, queries, services, and repositories.
    
    ### The grep-first thesaurus layout
    
    `THESAURUS.md` is shaped so that **one `rg` for any name answers "what do I do with this name?"**. Registry sections are one-line-per-item bullet lists with labelled tokens — not Markdown tables, because `|` is an alternation in ripgrep (the Grep tool of most agents), tables match by column position, and formatters re-pad them.
    
    ```markdown
    ## Index                      ← one line per concept, every name for it
    - **Order** `Order` kind:aggregate avoid: `Purchase`, `Transaction`, `Buy`
    - **Account** `Account` kind:aggregate ctx:Billing avoid: `Wallet`, `Balance`
    
    ## Terms                      ← `### Term` entries: Definition / NOT / Related
    ## Forbidden                  ← - `Manager` use: `OrderFulfillment` — hides responsibility
    ## Legacy                     ← - `Basket` → `Cart` in: `api/v1/basket.ts` — renamed v2
    ## Unresolved                 ← `### Term — problem` entries awaiting a decision
    ```
    
    ```bash
    rg -n -i 'basket'            # any role — the shape of the hit line tells you the section
    rg -n 'avoid:.*`Purchase`'   # banned synonym → the canonical Identifier is at line start
    rg -n 'kind:event'           # all events;  rg 'ctx:Billing' → everything one context owns
    rg -n -F '**Order**'         # exact Term, not "Order Line Item"
    rg -n '^### Order( \(|$)'    # the entry itself
    ```
    
    - **Registry invariant**: every name appears in exactly one registry line, so the *shape* of a hit gives its status and the *line* gives the canonical name — no `-B`/`-A` context reading.
    - `Identifier` is the PascalCase code form — what agents actually see in code and grep for; `Term` stays in the domain's own language (``**Счёт-фактура** `Invoice` ``).
    - Backticks around every name make `` rg '`Order`' `` an exact match that skips `OrderLineItem`.
    - `kind:` selects the DDD naming rule; `ctx:` appears only once bounded contexts are confirmed.
    - Existing thesauri (prose-only or table-index) are migrated in one pass without changing a definition.
    
    ### Thesaurus generation (rare)
    
    Scans high-signal structural files (DB schemas, API contracts, domain layer, directory structure) to extract domain terms. Separates active from legacy/obsolete terms. Collects ambiguities into an `## Unresolved` section, then surfaces them to the user for resolution. Updates agent instruction files (`CLAUDE.md`, `GEMINI.md`, etc.) so the thesaurus is used even without the skill installed.
    
    ### History mining (optional, offered at the end of generation)
    
    The `## Unresolved` section is the honest part of a mined thesaurus — the questions the
    current tree cannot answer. Git history often can. After generation (and after an audit),
    the skill **offers** to build a throwaway index of the repository's history and come back
    with evidence-backed proposals per unresolved item.
    
    ```bash
    python3 scripts/git_term_index.py build --repo-dir . --content
    python3 scripts/git_term_index.py query Account Customer
    python3 scripts/git_term_index.py pair User Customer
    python3 scripts/git_term_index.py contexts Account
    python3 scripts/git_term_index.py search 'rename account'
    python3 scripts/git_term_index.py clean
    ```
    
    The index is dependency-free Python 3.9+ (stdlib `sqlite3`, only `git` required) and lives
    as a single SQLite file in `$TMPDIR`, **never in the working tree**. Commit messages go into
    an FTS5 table so message search is ranked by **BM25 relevance**, not recency; identifiers
    from every added/removed diff line go into an `identifier × commit × file` table with
    add/delete counts. Each identifier carries a casing-independent normal form, so
    `OrderLineItem`, `order_line_item` and `ORDER_LINE_ITEM` are one concept — which is what
    makes a PascalCase thesaurus Identifier findable in a snake_case codebase.
    
    **Per-file granularity is what makes the common case answerable.** One commit touches many
    files, so commit-level co-occurrence cannot localise a name (measured: one identifier's
    directory distribution was 74% "wherever the code is"). With per-file rows the tool answers
    the flagship `## Unresolved` question — `Account` in `billing/` vs `auth/` — directly:
    `contexts Account` shows the directory split, and `pair` reports `files: A in N, B in M,
    both in K`. `both in 0` is evidence for two bounded contexts; shared files mean synonym
    drift. It also sharpens renames: an exchange **inside one file** outranks "both names
    appear somewhere in one commit".
    
    **The whole diff history is indexed, not a recent window** — that is the difference between
    "born" and "first seen in the last N commits". Measured: git.git's full 21-year history
    builds in 111 s (232 MB), kubernetes' 12 years / 82 704 commits in 249 s (1 040 MB); queries
    then run in 0.1–1.3 s. Walking history per-term with `git log -S` instead costs 4 s per term on
    git.git and 84–98 s per term on kubernetes.
    
    What that buys per ambiguity: **birth** (which spelling is the incumbent, and what the
    introducing commit said), **dormancy** (nothing has touched this name in years → retired
    vocabulary), **trajectory** (deletions ≫ additions = being phased out), **ranked swap
    commits** (the commits that remove one name while adding the other, strongest exchange
    first — these are the renames), **the path split** (do any files contain
    both names? which directories does each occupy? — the bounded-context signal), and **stated
    intent** from BM25-ranked messages and PR references.
    
    `pair` ends in one labelled verdict — **RENAME (strong / probable / possible)**, **DRIFT**,
    **NOT A RENAME**, or **COEXISTENCE** — with the direction inferred from the evidence rather
    than from argument order.
    
    **The thresholds behind those labels were set by falsification, not taste.** Every one was
    added after a measured false positive on a real repository:
    
    | Rule | The false positive that forced it |
    |------|-----------------------------------|
    | A swap needs a **net** exchange (≥3 each way), not any deletion + any addition | 105 of 174 commits touching two unrelated integrations were labelled rename candidates — including commits where *both* names were net-removed |
    | Identifiers carry a casing-independent **normal form** | `query OrderLineItem` returned "never appears" on a snake_case repo — a false negative on the skill's own canonical input, since thesaurus Identifiers are PascalCase |
    | Comparing two names uses **concepts, not families** | the `Account` set contained `BillingAccount`, so its additions cancelled `Account`'s deletions and masked the exchange |
    | Exchanges must clear a **noise floor** (≥2 commits and ≥5% of shared commits) | `bisect`/`rebase` in git.git: 2 exchanges in 145 shared commits read as "drift" |
    | Same-file exchanges clear a lower bar, but still a bar | making any same-file swap sufficient put `bisect`/`rebase` straight back to RENAME on 2 swaps in 111 commits |
    | A rename announcement must name **both** sides | "Rename Telegram meeting wrapper" certified `club` → `meeting` |
    | Dormancy measured from **last growth**, not last touch | git.git's `get_sha1` was last *touched* in 2026 by a commit deleting a stale comment; last *grown* in 2017 |
    | Locale and changelog files excluded | `.po` files made "l10n: zh_CN …" the top rename candidate for unrelated terms |
    
    Measured after those fixes: **18 negative controls across three repositories → zero false
    rename verdicts** (the worst of them reaches 6 same-file exchanges in 1 193 shared commits
    and no naming subject), while every known rename — including kubernetes' `Minion`→`Node`,
    which lands with 35 same-file swaps and 6 announcing subjects — still lands as RENAME — strong.
    
    Other defaults from measurement: HEAD only (side branches carry release notes and imported
    trees — on git.git, `--all` dated `oid_array` to a status email three days before the actual
    rename commit), vendored/generated/minified paths excluded, merges excluded. Shallow clones,
    truncated windows, and names present in the oldest indexed commit are each flagged in every
    report rather than silently producing a confident wrong date.
    
    **Known limits, stated in the skill:** `pair` compares identifiers, so a rename that only
    moved files surfaces in `query`'s file-renames section instead; and polysemy — one word
    meaning two things in two modules, the most common real `## Unresolved` entry — is the
    weakest case for history mining, which will honestly return COEXISTENCE and leave the
    decision to the user.
    
    Findings are reported in one batch with a confidence level and the commits behind each
    proposal; nothing is applied until the user approves, and each applied decision cites its
    commit (`— renamed in a41f2c9` on the Legacy line, or a `- **History**:` entry line).
    History is treated as evidence of what happened, never as authority on what a term should
    be — it ranks candidates, the user decides. Squashed imports, shallow clones, bulk
    reformatting commits, and vendored code are called out as the failure modes they are.
    
    ### Naming audit (periodic)
    
    9-check protocol: thesaurus integrity (registry invariant, Index ↔ Terms), synonym violations, forbidden words, technical jargon leaks, synonym drift, polysemy, translation chains, abbreviation inconsistency, orphan terms. The Index is the audit's work-list. Produces a structured report grouped by severity (Critical / Warning / Info) with recommended fix priority.
    
    ## Key features
    
    - **Grep-first thesaurus** — one labelled line per concept, registry invariant, exact-match backticks; built for agents that navigate by `rg`, not by reading whole files
    - **Codebase is primary evidence, not automatic authority** — supports both "as-is" (document current naming) and "to-be" (define target vocabulary) modes
    - **Flat-first thesaurus** — no bounded contexts by default; only introduced when polysemy is confirmed by the user with the invariant test
    - **Forbidden list** (lexical firewall) — maintained list of words banned from the domain layer (weasel words, implementation details)
    - **Polysemy unpacking** — detects overloaded terms and forces disambiguation into explicit facets
    - **Cross-context bridges** — when bounded contexts exist, one line per bridge with a SKOS mapping (`exactMatch` … `relatedMatch`, `distinct`) and loss notes
    - **Git-history mining for ambiguities** — a throwaway SQLite index (built outside the repo, deleted after) over the *full* diff history: BM25-ranked commit messages, renames, and every identifier's birth, dormancy and swap commits; proposes rename / deprecate / two-concepts / drift verdicts with citations and confidence, never silently
    - **Legacy term tracking** — continuity relations (rename/split/merge/retire/deprecate) with alias parsimony
    - **Framework-aware** — doesn't fight Active Record patterns; distinguishes domain noun from framework coupling
    - **Language-agnostic** — works with any programming language, no framework-specific rules
    - **Non-English domain support** — uses the domain's original language for canonical terms
    
    ## Sources and methodology
    
    This skill was built through a structured research and review process:
    
    ### Primary sources
    
    1. **Domain-Driven Design** by Eric Evans — ubiquitous language, bounded contexts, aggregate naming, anti-corruption layers
    2. **Learning Domain-Driven Design** by Vlad Khononov — practical DDD patterns including brownfield adoption strategy, co-creation (not extraction) of domain language, tacit knowledge handling, translation chain anti-pattern, thesaurus scoping heuristics
    3. **[First Principles Framework (FPF)](https://github.com/ailev/FPF/blob/main/FPF-Spec.md)** — formal tools for semantic precision:
       - A.1.1 `U.BoundedContext` — bounded contexts as declared semantic frames with the invariant test for justification
       - A.6.8 Service Polysemy Unpacking — "can you X it?" disambiguation tests for overloaded terms
       - A.6.9 Cross-Context Sameness Disambiguation — bridges with loss notes, direction, and relationship types
       - E.5.1 DevOps Lexical Firewall — protecting domain vocabulary from transient implementation jargon
       - F.2 Term Harvesting & Normalisation — context-local harvesting discipline
       - F.5 Naming Discipline — "name what the invariants make true", minimal generality
       - F.13 Lexical Continuity & Deprecation — five continuity relations (rename/alias/split/merge/retire)
       - F.14 Anti-Explosion Control — "four levers before minting a new name"
    4. **ISO 25964 / SKOS** — label model (prefLabel / altLabel / notation), BT/NT/RT relations and their integrity rules, mapping vocabulary for cross-context bridges — see Standards alignment
    5. **Martin Fowler**, **Vaughn Vernon** — bounded context maps, anti-corruption layers, context boundaries as language boundaries
    
    ### Web research
    
    - DDD ubiquitous language best practices and common failures (synonym drift, naming chaos, acronym problems)
    - Domain glossary/thesaurus management formats and standards
    - DDD naming rules by construct type (aggregates, entities, value objects, events, commands)
    - Naming anti-patterns in domain code (weasel words, technical jargon leaks, implementation-driven naming)
    - Codebase auditing approaches for naming consistency
    
    ### Multi-agent review
    
    The skill was reviewed by external AI agents (OpenAI Codex CLI / GPT-5.4 and Google Gemini CLI / Gemini 3.1 Pro) via the [pragmatic-orchestration](https://github.com/CodeAlive-AI/pragmatic-orchestration) skill for independent, unbiased assessment. The review identified 6 critical operational issues:
    
    1. **Scanning impossibility** — original instructions assumed whole-codebase scanning; replaced with bounded high-signal hub strategy
    2. **O(N^2) audit check** — field-overlap comparison replaced with grep-friendly stem+suffix heuristics
    3. **External system assumptions** — translation chain check rewritten for local-only filesystem access (git log, test descriptions, local docs)
    4. **Missing language idiom exceptions** — added durability boundary: DDD naming for domain-bearing identifiers, standard idioms (`err`, `ctx`, `i`) exempt
    5. **Source of truth dogma** — "trust the code" replaced with "code is evidence, not authority" with explicit brownfield/legacy override
    6. **Framework antagonism** — added caveat for Active Record patterns where domain and persistence are intentionally blended
    
    ### Design decisions
    
    - **Progressive disclosure**: SKILL.md (naming consultation) loads on every trigger; references load only on demand — saves ~700 lines of context on the common path
    - **Grep-first over read-everything**: agents consult the thesaurus on every naming task, so lookup cost matters more than prose quality. The Index (one line per concept) is cheap to read whole; everything else is reached by a single `rg` whose hit is self-describing. Avoid lists live only in the Index so there is one place to drift from — none
    - **Labelled lines, not tables, for registry data**: Index, Forbidden (`use:`) and Legacy (`→`, `in:`) are one-line facts with position-free tokens — greppable without escaping `|`, immune to formatter re-padding, and each line's shape reveals its section. Definitions and open questions stay as prose entries
    - **Non-English domains get two columns, not a compromise**: `Term` holds the experts' word, `Identifier` the code form, so the thesaurus is greppable from either side
    - **Flat-first thesaurus**: bounded contexts are opt-in, not default — the agent cannot reliably determine context boundaries, so it surfaces evidence and asks the user
    - **Unresolved section**: ambiguities collected during scanning, surfaced as a batch after file creation — no blocking questions during generation
    - **Agent instruction updates**: after creating the thesaurus, the skill updates CLAUDE.md/GEMINI.md/etc. so the thesaurus works even without the skill installed
    - **History as evidence, not authority**: mining is an *offer* made after the Unresolved list is shown, not an automatic step, and it produces ranked hypotheses with commit citations — the user still makes every call. The index is deliberately throwaway (temp dir, one command to delete) rather than a committed artifact: it is derived data, it goes stale on the next commit, and nothing in a repository should be generated into the working tree
    - **No format change**: history provenance rides in existing free-text — the note tail of a `## Legacy` line, or an optional `- **History**:` entry line — so `thesaurus-format` stays `2.0` and no migration is needed
    
    ## Standards alignment
    
    The layout is a plain-Markdown projection of a SKOS concept scheme (ISO 25964-compatible) — exportable to RDF/JSON-LD if ever needed, without being written in it.
    
    | Thesaurus | SKOS / ISO 25964 |
    |-----------|------------------|
    | `**Term**` | `skos:prefLabel` — one per concept and context |
    | `` `Identifier` `` | `skos:notation` — machine code, distinct from the label |
    | `avoid:` | `skos:altLabel` + `skos:hiddenLabel` (ISO 25964: `UF`, use-for) |
    | `Definition` / `NOT` | `skos:definition` / `skos:scopeNote` |
    | `Broader` / `Narrower` / `Related` | `BT` / `NT` / `RT` — written on one side only, `rg` gives the inverse |
    | `### Term (Context)` | ISO 25964 homograph qualifier |
    | Legacy `` `Old` → `New` `` | `owl:deprecated` + `skos:historyNote`; `A + B` = compound equivalence |
    | Bridge mapping | `skos:exactMatch` … `relatedMatch` (+ explicit `distinct`); never `owl:sameAs` |
    | Unresolved → Index → Legacy | concept status: candidate → approved → deprecated |
    
    Deliberately not borrowed: `ConceptScheme`/`Collection`, facets, OWL axioms, RDF serialisation — `kind:`/`ctx:` and prose `NOT` cover the need without the weight.
    
    ## Versioning
    
    - **Skill**: `metadata.version` in `SKILL.md` frontmatter (semver). Current: **2.1.0**.
    - **Thesaurus format**: stamped in every `THESAURUS.md` as YAML frontmatter —
      `thesaurus-format: "2.0"`, `skill: ubiquitous-language`. One `rg '^thesaurus-format:'` tells an agent which grammar to expect; a missing key means format 1.0 (the pre-index prose layout).
    - Format major = skill major. The skill reads any format ≤ its own and writes only the current one; a major gap triggers the one-pass migration, a minor gap only adds optional tokens.
    - Format history lives in `references/generating-thesaurus.md` → "Format history".
    
    ## File structure
    
    ```
    ubiquitous-language/
    ├── SKILL.md                         # Naming consultation (loaded on every trigger)
    ├── README.md                        # This file
    ├── references/
    │   ├── generating-thesaurus.md      # Thesaurus generation workflow
    │   ├── naming-audit.md              # 9-check naming audit protocol
    │   └── git-history-mining.md        # Resolving `## Unresolved` items from git history
    └── scripts/
        └── git_term_index.py            # Throwaway SQLite/FTS5 history index (build/query/pair/contexts/search/clean)
    ```
    
    ## License
    
    MIT
    
  • SKILL.md 29.1 KB
    ---
    name: ubiquitous-language
    description: |
      Maintain a project thesaurus (domain glossary) following DDD ubiquitous language
      principles. Use PROACTIVELY when naming anything: variables, functions, classes,
      modules, database fields, API endpoints, events, files, or directories. Also use
      when the user asks to "create thesaurus", "update glossary", "add term", "rename
      to match domain", "check naming consistency", "what should I call this", "domain
      language", "ubiquitous language", or "naming conventions". Ensures all names in
      the codebase are consistent, descriptive, and aligned with the shared domain
      vocabulary. Also mines git history to resolve naming ambiguities — when a name
      was born, which name replaced which, which spelling is dying. Not for general
      code style or linting — only for domain term consistency.
    metadata:
      version: "2.1.0"
      thesaurus-format: "2.0"
    allowed-tools:
      - Read
      - Write
      - Edit
      - Grep
      - Glob
      - Bash
      - Agent
      - AskUserQuestion
    ---
    
    # Ubiquitous Language: Project Thesaurus Manager
    
    You enforce naming consistency across the codebase by maintaining a living thesaurus
    of domain terms and consulting it every time something needs a name.
    
    **Four modes:**
    - **Naming consultation** (frequent) — everything in this file
    - **Thesaurus generation** (rare) — read [references/generating-thesaurus.md](references/generating-thesaurus.md)
    - **Naming audit** (periodic) — read [references/naming-audit.md](references/naming-audit.md)
    - **History mining** (optional) — read [references/git-history-mining.md](references/git-history-mining.md)
      when `## Unresolved` items need evidence: which name came first, which replaced which,
      which is dying. Offered after generation, or on demand against an existing thesaurus.
    
    ## Foundations
    
    This skill combines two bodies of knowledge:
    
    - **Domain-Driven Design (DDD)** by Eric Evans — ubiquitous language, bounded contexts, aggregate naming
    - **[First Principles Framework (FPF)](https://github.com/ailev/FPF/blob/main/FPF-Spec.md)** — a transdisciplinary "operating system for thought" that provides formal tools for semantic precision: bounded contexts as declared semantic frames, polysemy unpacking, lexical firewalls, cross-context bridges with loss notes, term continuity relations, and anti-explosion naming control. References like "FPF F.5" or "FPF A.1.1" point to specific sections of the FPF specification.
    
    ## Core Principle
    
    > "A project should use a single, shared vocabulary. Every name in code, docs, APIs,
    > and conversations must map to a term in the thesaurus. If a concept isn't in the
    > thesaurus — add it before naming anything."
    >
    > — Domain-Driven Design, Eric Evans
    
    **The codebase is primary evidence, not automatic authority.** Use code to discover
    which terms are currently in circulation. Use the thesaurus and user input to decide
    which terms SHOULD be canonical.
    
    - For **what exists today** — derive from code (classes, DB schemas, API routes, events)
    - For **what should become the standard** — ask the user/domain expert
    - If code contradicts the approved thesaurus — the thesaurus wins for new code
    - If the user says "fix legacy naming" — the user's directive overrides the codebase;
      map existing code names to `## Legacy` lines and use the user's terms as canonical
    
    **Tacit knowledge**: For areas not yet implemented, the most important domain knowledge
    exists only in experts' heads, not in any artifact.
    
    ## Thesaurus File
    
    **Locating the thesaurus:**
    1. If the user specified a path — use it
    2. If `THESAURUS.md` already exists somewhere in the repo — use that location
    3. Default: `docs/THESAURUS.md`
    
    Single source of truth for domain vocabulary.
    
    ### Versioning
    
    The thesaurus declares its **format version** and the skill that maintains it in YAML
    frontmatter — machine-readable, outside the body, still one grep away:
    
    ```markdown
    ---
    thesaurus-format: "2.0"
    skill: ubiquitous-language
    ---
    
    # Project Thesaurus
    ```
    
    Quote the version — unquoted `2.10` is the YAML float `2.1`.
    
    - `rg -n '^thesaurus-format:' THESAURUS.md` → the version in one hit. **No key = 1.0**
      (the pre-index prose layout shipped before skill 2.0) — unless the file already has
      ``- **Term** `Id` kind: `` Index lines: that is an unstamped 2.0 file from plugin 9.2.0;
      just add the stamp.
    - Format major = skill major (`metadata.version` in this file's frontmatter). Skill
      minor/patch releases never change the format.
    - **Read** any format ≤ your own; **write** only the current one. A major gap means
      migration first (see generating-thesaurus.md); a minor gap means new optional tokens —
      older readers keep working, you may add the tokens as you touch lines.
    - A thesaurus with a format **newer** than yours: read it, don't rewrite it — tell the user
      to update the skill.
    - Only the format is versioned in the file. The skill's own version is not recorded there —
      it would go stale on every edit and `git log` already answers "who wrote this". `skill:`
      is a pointer, so an agent without the skill knows what to install.
    
    | Format | Layout | Skill |
    |--------|--------|-------|
    | 1.0 | `### Term` entries with `Synonyms to AVOID`; `## Legacy Terms` entries; `## Forbidden Lexicon` table | ≤ 1.x (plugin ≤ 9.1.1) |
    | 2.0 | grep-first: `## Index` lines with `kind:`/`ctx:`/`avoid:`, `use:` Forbidden lines, `→` Legacy lines, SKOS bridges | 2.x |
    
    ### Layout: grep-first
    
    The file is designed so that **one `rg`/`grep` for any name answers "what do I do with
    this name?"** without reading the surrounding text. Five sections, fixed order:
    
    | Section | Shape | One line answers |
    |---------|-------|------------------|
    | `## Index` | one line per concept | "Is there a term for this? Which name is canonical? What is banned?" |
    | `## Terms` | `### Term` entries | "What exactly does it mean / not mean / relate to?" |
    | `## Forbidden` | one line per word | "Is this word banned from domain names?" |
    | `## Legacy` | one line per old name | "This old name is in the code — what replaced it?" |
    | `## Unresolved` | `### Term — problem` entries | "Is this name an open question?" |
    
    **Registry invariant:** every name known to the project appears in **exactly one**
    registry line — an Index line (as Term, Identifier, or avoid), a Forbidden line, a Legacy
    line, or an Unresolved header. Each kind of registry line has its own shape, so the
    *shape of the hit* tells you its status and the *line itself* tells you the canonical
    name. No `-B`/`-A` context needed.
    
    Registry lines are **bullet lines with labelled tokens**, not Markdown tables: tables
    need `|` (an alternation in `rg`), match by column position, and get re-padded by
    formatters. Tokens (`kind:`, `ctx:`, `avoid:`, `use:`, `in:`, `→`) are position-free,
    formatter-proof, and need no escaping.
    
    ```markdown
    # Project Thesaurus
    
    ## Index
    
    - **Order** `Order` kind:aggregate avoid: `Purchase`, `Transaction`, `Buy`
    - **Order Line Item** `OrderLineItem` kind:entity avoid: `LineItem`, `OrderItem`, `Item`
    - **Order Placed** `OrderPlaced` kind:event avoid: `OrderCreated`, `NewOrder`
    
    ## Terms
    
    ### Order
    - **Definition**: A customer's confirmed request to buy one or more products at agreed prices.
    - **NOT**: A payment (that's `Payment`), a shipment, or a draft cart (that's `Cart`).
    - **Related**: Order Line Item, Order Placed, Cart
    
    ## Forbidden
    
    - `Manager` use: `OrderFulfillment` — hides responsibility; name the activity
    
    ## Legacy
    
    - `UserManager` → `Customer` + `CustomerRegistration` in: `src/legacy/` — split in v3
    
    ## Unresolved
    
    ### Account — one word, two concepts (billing vs auth)
    - **Found in**: `billing/Account.ts` (balance), `auth/Account.ts` (login)
    - **Question**: Two bounded contexts, or one of them a naming mistake?
    - **Impact**: 18 files
    - **Options**: `BillingAccount` + `UserAccount`; or contexts Billing / Identity
    ```
    
    ### Index line
    
    ```
    - **<Term>** `<Identifier>` kind:<kind> [ctx:<Context>] [avoid: `<name>`, `<name>`]
    ```
    
    | Field | Content | Rules |
    |-------|---------|-------|
    | **Term** | Human name, as domain experts say it, in `**bold**` | May be multi-word or non-English. Also the `### ` header text of the entry |
    | **Identifier** | PascalCase code form, in backticks | The thing you grep in code. All other casings derive from it mechanically (see Casing) |
    | **kind:** | One of `aggregate` `entity` `value` `event` `command` `query` `service` `role` `process` `state` `policy` `concept` | Picks the naming rule below. `concept` when nothing fits |
    | **ctx:** | Bounded context name | Only present once contexts are confirmed (see generating-thesaurus.md); the header then becomes `### Term (Context)` |
    | **avoid:** | Banned synonyms and abbreviations, each in backticks, comma-separated | Last on the line because it is the only variable-length field. Omit when empty |
    
    - **One line per concept.** All names for that concept live on that line — this is what
      makes reverse lookup (`rg Purchase` → "use `Order`") a single hit.
    - **Backticks around every identifier-like name.** `` rg '`Order`' `` is an exact match;
      `rg Order` would also hit `OrderLineItem` and `Reorder`. `rg -F '**Order**'` is the
      exact Term.
    - **Sorted alphabetically by Term.** Entries under `## Terms` follow the same order.
    - **avoid lists live only here.** Entries do not repeat them — one place, no drift.
    
    ### Forbidden and Legacy lines
    
    ```
    - `<Word>` use: `<Identifier>`[, `<Identifier>`] — <why>
    - `<OldName>` → `<Identifier>`[ + `<Identifier>`] in: <files/modules> — <note>
    - `<OldName>` → — (see `<X>`, `<Y>`) in: <files> — retired
    ```
    
    `use:` always points at an Index Identifier. `→` is the legacy marker: `A + B` means the
    old name was split; `→ —` means retired with no single successor.
    
    ### Entry
    
    ```markdown
    ### [Term]
    - **Definition**: What this concept means in the business domain — one sentence
    - **NOT**: What this term does NOT mean; name the neighbouring term it is confused with
    - **Related**: Other Index Terms this connects to, written exactly as in the Term field
    ```
    
    Optional lines when they carry real information: `**Broader**`, `**Narrower**`,
    `**Part of**`, `**Has parts**`, `**Example**`. Write them on one side only — `rg` gives
    the inverse for free, mirrored copies only drift. Minimal viable entry is one line:
    `- **Definition**: …` — the Index line already holds the rest.
    
    **Anchor grammar** (so lookups are one regex): the header is exactly `### <Term>` or
    `### <Term> (<Context>)` — nothing else. Tags, status, and context prefixes belong in
    the Index line, not in the header. Find an entry with `rg -n '^### Order( \(|$)'` —
    `\b` alone is not enough, it would also match `### Order Line Item`.
    
    **The thesaurus captures concepts, not behavior.** It's strong at nouns (entity names,
    roles, process names) but won't replace behavioral specs for business rules. Don't try
    to turn the thesaurus into a specification — keep entries short. If a concept has a
    critical invariant, note it briefly in the definition, not as a separate section.
    
    **Non-English domains**: If the business domain operates in a non-English language, the
    **Term** uses the original language — the thesaurus should reflect how domain experts
    actually speak. The **Identifier** carries the code form:
    ``- **Счёт-фактура** `Invoice` kind:entity``. This is exactly why both fields exist.
    
    ## Lookup Protocol
    
    **Look up before inventing. This is the single most important step.** Most naming tasks
    don't need a new term — the right name is already there.
    
    1. **Locate** the thesaurus (see above). If absent, tell the user and offer generation.
       Check `rg -n '^thesaurus-format:'` — no key or `1.x` means the old layout: the
       protocol below still works by plain text search, but offer migration once, up front.
    2. **Read the Index** if it has ≤ ~60 lines — it is the entire vocabulary at one line
       per concept, cheaper than any search. For larger files, search instead.
    3. **Search every candidate name** you are considering, plus whatever the surrounding
       code already calls the thing. Use `rg` (the Grep tool) or `grep -E` — same patterns:
    
       ```bash
       rg -n -i 'invoice' docs/THESAURUS.md             # any role, any section
       rg -n '`OrderLineItem`' docs/THESAURUS.md        # exact identifier as seen in code
       rg -n -F '**Order**' docs/THESAURUS.md           # exact Term (not "Order Line Item")
       rg -n 'avoid:.*`Purchase`' docs/THESAURUS.md     # is this word a banned synonym?
       rg -n 'kind:event' docs/THESAURUS.md             # all terms of one kind
       rg -n 'ctx:Billing' docs/THESAURUS.md            # everything one context owns
       rg -n '`Basket` →' docs/THESAURUS.md             # legacy name and its replacement
       rg -n -A4 '^### Invoice( \(|$)' docs/THESAURUS.md  # the entry itself
       ```
    
       The only trap: `*` and `|` are regex metacharacters — use `-F` for `**Term**`, and
       never search for table pipes (there are none).
    
    4. **Act on the shape of the line you hit:**
    
       | Hit line looks like | Meaning | Do |
       |---------------------|---------|----|
       | ``- **X** `X` kind:… `` — your word is the Term or Identifier | Concept exists | Use the Identifier exactly. Stop |
       | ``- **X** … avoid: … `your word` `` | You were about to use a banned synonym | Use that line's Identifier instead |
       | `` - `word` use: … `` | Word is banned from domain names | Pick the Identifier after `use:` |
       | `` - `word` → … `` | Old name still in code | Use the replacement after `→` for new code; don't spread the legacy name |
       | `### word — …` under `## Unresolved` | Open naming question | Don't decide silently — surface it, ask the user, or offer history mining (see below) |
       | `### ` header / entry text only | Related concept | Read the entry; it may inform composition |
       | No hit | New concept | Go to "If the concept is new" |
    
    5. **Check the bounded context** if Index lines carry `ctx:` — the same word may be
       canonical in one context and banned in another.
    
    **ALWAYS** run this before naming: classes, interfaces, types, enums, aggregates,
    entities, value objects, functions, methods, commands, queries, domain events,
    variables, constants, fields, parameters, DB tables/columns/collections, API endpoints
    and response fields, files, directories, modules, packages, feature flags, config keys,
    environment variables, and commit messages or PR titles that reference domain concepts.
    
    ## If the Concept Is New
    
    **Before minting a new term, try four levers** (from FPF F.14 "Name less, express more"):
    
    1. **Reuse** — does an existing term already cover this? Maybe the concept is a variant, not a new thing
    2. **Compose** — can you combine existing terms? `OrderLineItem` reuses `Order` + `LineItem`
    3. **Qualify** — is this the same concept in a different state/window? Don't create `NightOperator` — use `Operator` with a time qualifier
    4. **Ask** — if still unclear: "I need to name [concept]. The thesaurus doesn't have a term for this. What does the domain call it?"
       **If the user doesn't have an answer either** — that's a white spot, not a dead end.
       Building a ubiquitous language is co-creation, not extraction. Add it to `## Unresolved`
       with a `[WHITE-SPOT]` tag in the header. Don't force a name for an undefined concept.
    
    Only after all four fail, mint a new term:
    1. **Name what the invariants make true** (FPF F.5) — don't name aspirationally. If the code doesn't enforce "Premium", don't call it `PremiumCustomer`
    2. **Use minimal generality** — choose the narrowest name whose rules you actually enforce. Don't upgrade `Task` to `Activity` to sound universal
    3. **Keep it to 1-3 words** — no rhetorical adjectives ("robust", "optimal", "advanced")
    4. **Add it to the thesaurus**: an Index line (Term, Identifier, `kind:`, `avoid:` —
       omit `avoid:` when empty) **and** a `### Term` entry with at least a Definition. Keep both sorted
    5. **Then** use the term in code
    
    ## If You Find an Inconsistency
    
    When existing code uses a term that contradicts the thesaurus:
    - Flag it: "Found `fetchPurchases()` but the Index line says `Order`, with `Purchase` under `avoid:`"
    - Suggest a rename if scope is small
    - For large-scale renames, note as tech debt and ask user how to proceed
    
    ## If the Ambiguity Won't Resolve Itself
    
    When a name lands in `## Unresolved` — two spellings for one concept, one spelling for two
    concepts, no obvious winner — the current tree can't settle it, but the repository's history
    often can: which identifier was born first, which commit removed one while adding the other,
    which one is dying.
    
    **Offer it, don't run it silently.** Whenever you present `## Unresolved` items — after
    generation, after an audit, or when a naming question hits one — offer once:
    
    > "I can mine the git history for these — when each name was born, which replaced which,
    > which is growing vs dying. Temporary index outside the repo, deleted afterwards.
    > Want me to try that before you answer them by hand?"
    
    Skip the offer if there is no `.git`, history is shorter than ~50 commits or squashed from
    an import, or the items are `[WHITE-SPOT]` tags (an unnamed concept leaves no trace).
    
    If the user accepts, read [references/git-history-mining.md](references/git-history-mining.md)
    and follow it. The short version:
    
    ```bash
    S=<skill-dir>/scripts/git_term_index.py
    python3 $S build --repo-dir . --content   # throwaway SQLite index in $TMPDIR, never in the repo
    python3 $S query Account Customer         # birth, dormancy, trajectory, renames, messages
    python3 $S pair User Customer             # competing names: birth order + swap commits
    python3 $S contexts Account               # where the name lives — the polysemy check
    python3 $S search 'rename account'        # BM25 search over commit messages
    python3 $S clean                          # delete the index when done
    ```
    
    The index covers the **whole** diff history, so "born" means born. Use `--pathspec src/`
    on large repos — it cuts build time and sharpens the signal at once.
    
    `pair` ends in a labelled verdict — **RENAME (strong / probable / possible)**, **DRIFT**,
    **NOT A RENAME**, **COEXISTENCE** — with the direction inferred from evidence, not argument
    order. **Report the label as given; do not upgrade it.** "RENAME — strong" means commits
    exchange the names *and* a subject announces it; everything weaker needs `git show` first.
    
    For **polysemy** (one word, two meanings, two modules) use the path split: `pair` prints
    `files: A in N, B in M, both in K`, and `contexts <name>` gives the directory breakdown for a
    single word. `both in 0` — no file ever contained both — is real evidence for two bounded
    contexts; shared files mean synonym drift, which history cannot settle. **Only claim a path
    split when the tool printed one.** File-only renames (the file moved, the identifier did not)
    appear in `query`'s file-renames section, not in `pair` — run both.
    
    **History is evidence, not authority.** It ranks candidates and cites commits; the user
    decides. Report proposals in one batch with confidence levels, apply only what is approved,
    and record the commit behind each applied decision (`— renamed in a41f2c9` on the Legacy
    line, or a `- **History**:` line on the entry).
    
    ## Naming Rules by DDD Construct
    
    The Index `Kind` column selects the rule.
    
    ### Aggregates & Aggregate Roots (`aggregate`)
    Use the business domain term. Singular. No technical suffixes.
    
    ```
    GOOD: Order, Invoice, UserAccount, ShoppingCart
    BAD:  OrderAggregate, OrderRoot, OrderAggregateImpl, OrderEntity
    ```
    
    ### Entities (`entity`)
    Singular noun from the domain. Something with identity.
    
    ```
    GOOD: OrderLineItem, PaymentTransaction, Customer
    BAD:  OrderLineItemEntity, OrderLineItemImpl, OrderLineItemObj
    ```
    
    ### Value Objects (`value`)
    Singular noun describing an immutable concept. Describes **what it is**, not what it does.
    
    ```
    GOOD: Money, Email, PhoneNumber, Address, DateRange
    BAD:  MoneyValue, EmailValidator, PriceInfo, AmountData
    ```
    
    ### Domain Events (`event`)
    **Past tense verb + noun.** Something that happened.
    
    ```
    GOOD: OrderPlaced, PaymentCaptured, InvoiceSent, InventoryReserved
    BAD:  OrderEvent, OnOrderPlaced, CreateOrder (that's a command)
    ```
    
    ### Commands (`command`)
    **Imperative verb + noun.** An action requested.
    
    ```
    GOOD: CreateOrder, CancelInvoice, ProcessRefund, ReserveInventory
    BAD:  OrderCreated (that's an event), NewOrder, OrderCommand
    ```
    
    ### Queries (`query`)
    Question or retrieval. Verb + object or descriptive name.
    
    ```
    GOOD: GetOrderById, FindInvoicesByCustomer, ListPendingOrders
    BAD:  RetrieveOrderData, OrderQuery, GetterForOrder
    ```
    
    ### Domain Services (`service`)
    Named after **business activities** the domain expert recognizes.
    
    ```
    GOOD: InvoiceCalculator, OrderFulfillment, NotificationSender
    BAD:  OrderManager, GenericService, HelperService
    ```
    
    ### Repositories
    Repository suffix is acceptable — it's an infrastructure pattern. Repositories are not
    thesaurus terms; they take the name of the aggregate they store.
    
    ```
    GOOD: OrderRepository, InvoiceRepository, CustomerRepository
    BAD:  OrderStorage, OrderPersistence, OrderFinder, OrderDao
    ```
    
    ### Methods on Aggregates
    
    **Commands (change state):** Imperative verb, no "Get" prefix.
    ```
    GOOD: order.Cancel(), order.AddLineItem(product, quantity), order.Recalculate()
    BAD:  order.CancelOrderMethod(), order.GetCancelled(), order.DoCancelOrder()
    ```
    
    **Queries (read-only):** Start with Get, Is, Has, Can, or a domain verb.
    ```
    GOOD: order.GetTotal(), order.IsExpired(), order.CanBeShipped()
    BAD:  order.FetchInfo(), order.CheckData()
    ```
    
    ## Naming Anti-Patterns to Detect and Flag
    
    ### Lexical Firewall: the `## Forbidden` section
    
    The domain layer must be protected from transient jargon, vague terms, and
    implementation details. The thesaurus's `## Forbidden` section lists words that MUST NOT
    appear in domain names and must always be replaced with a specific domain term.
    
    ### Weasel Words (never use in domain layer)
    
    | Weasel Word | Problem | Fix |
    |-------------|---------|-----|
    | `Info` | Meaningless suffix | Remove it: `UserInfo` -> `User` |
    | `Data` | Says nothing about the concept | Use domain term: `OrderData` -> `Order` |
    | `Manager` | Vague, hides responsibility | Split by actual responsibility |
    | `Handler` | Generic, unclear intent | Name after what it handles |
    | `Service` | Overused catch-all | Use specific domain activity name |
    | `Base` | Technical distraction | Remove, use composition |
    | `Item` | Too generic | Use domain term: `Item` -> `OrderLineItem`, `Product` |
    | `Util` / `Helper` | Indicates bad design | Move logic to domain objects |
    | `Object` / `Obj` | Never appropriate | Remove suffix |
    | `Record` / `Model` | Database concept leaking into domain | Use domain term |
    | `Config` / `Settings` | Generic container hiding a concept | `Config` -> `LoanProduct`, `Settings` -> `NotificationPreferences` |
    
    ### Technical Jargon in Domain Layer
    
    Domain code must be free of implementation details:
    
    ```
    BAD:  MongoOrder, SqlUserRepository, HttpOrderService, OrderDto, OrderEntity
    GOOD: Order, OrderRepository (interface), PaymentGateway, Order (just Order)
    ```
    
    Technical prefixes/suffixes belong ONLY in the infrastructure layer, and even there the
    domain role should lead:
    ```
    INFRASTRUCTURE LAYER (OK): MongoOrderRepository, RedisSessionCache, HttpPaymentClient
    DOMAIN LAYER (NEVER):      MongoOrder, RedisSession, HttpPayment
    NAME THE ROLE, NOT THE TECH: SessionStore not RedisCache, EventPublisher not KafkaProducer
    ```
    
    **Framework caveat**: In frameworks that intentionally blend domain and persistence
    (Active Record pattern, ORM-centric frameworks), the model IS the domain entity.
    Keep the **domain noun clean** and let framework coupling live in inheritance,
    annotations, or metadata — not in the class name. Flag technical jargon only when
    it becomes part of the business-facing name or leaks outside its boundary.
    
    ### Synonym Drift
    
    Same concept called different things in different parts of code:
    
    ```
    PROBLEM: "Customer" in auth, "User" in API, "Account" in billing — all mean the same thing
    FIX:     Pick ONE canonical term per bounded context. Put the others in that line's `avoid:` list.
    ```
    
    ### Abbreviation Boundary
    
    Ban abbreviations in **durable, domain-bearing names**: types, exported functions,
    modules, API fields, DB columns, events, config keys.
    
    Allow **conventional short-lived local identifiers** when meaning is obvious in scope:
    `i`, `j`, `ctx`, `req`, `res`, `err`, `tx`, `db`, `e` for events.
    
    Allow **industry-standard acronyms** when they are the dominant term: `SKU`, `VAT`,
    `URL`, `ID`, `OAuth`. Do NOT force unnatural expansions if experts use the acronym.
    
    ```
    PROBLEM: usr, user, account, acct — competing abbreviations for the same durable concept
    FIX:     Pick ONE canonical form for domain-bearing names. Short-lived locals are exempt.
    ```
    
    ### Translation Chain ("Telephone Game")
    
    When different artifacts use different terms for the same concept across the
    knowledge chain, information is lost at each translation:
    
    ```
    SMELL: Domain expert says "Campaign" → PM writes "Promotion" in spec →
           Dev codes `marketing_push` → QA tests "advertising effort"
    FIX:   Same term everywhere: expert, PM, dev, QA all say and write "Campaign"
    ```
    
    This is worse than synonym drift because each translation also loses nuance and
    business rules. **How to detect:** compare terms in requirements/specs/tickets
    against code names. If they don't match, the ubiquitous language has a translation
    gap — adopt the domain expert's term everywhere.
    
    ## Casing Conventions
    
    The Index `Identifier` is PascalCase. Every other form is derived from it mechanically
    using the project's conventions — never re-worded:
    
    | Context | Convention | Example (Identifier: `OrderLineItem`) |
    |---------|-----------|------------------------|
    | Class/Type | PascalCase | `OrderLineItem` |
    | Function/Method | Project convention | `addOrderLineItem` / `add_order_line_item` |
    | Variable | Project convention | `orderLineItem` / `order_line_item` |
    | Constant | UPPER_SNAKE | `MAX_ORDER_LINE_ITEMS` |
    | Database table | Project convention | `order_line_items` |
    | API endpoint | kebab-case or convention | `/orders/{id}/line-items` |
    | Event/Message | PascalCase with past-tense verb | `OrderLineItemAdded` |
    | File/Directory | Project convention | `order_line_item.py`, `OrderLineItem.cs` |
    
    **Key rules:**
    - Use the EXACT Identifier — don't abbreviate (`ord`), don't expand (`orderObject`), don't synonym (`purchase`)
    - Compound names combine Identifiers: `OrderLineItem`, not `PurchaseLineItem`
    - Technical suffixes for infrastructure roles are fine: `OrderRepository`, `OrderDTO` (in infra layer only)
    - Multi-word Identifiers keep all words in every casing: `ProcessingStage` → `processing_stage`, never `proc_stage`
    - Variables and parameters use full descriptive names: `totalAmount` not `amt`, `customerEmail` not `cEmail`
    
    ## Updating the Thesaurus
    
    When changing terms, use the **least strong** relation that tells the truth (from FPF F.13):
    
    | Operation | When | Effect on thesaurus |
    |-----------|------|---------------------|
    | **Add** | New concept | Index line + entry. Minimum: Identifier, `kind:`, Definition |
    | **Rename** | Wording improved, sense unchanged | Change Term/Identifier in the Index line and header; old Identifier → `## Legacy` line `` `Old` → `New` ``; grep codebase, suggest renames |
    | **Split** | One term covered two senses | Old line removed; two new lines + entries; old Identifier → `## Legacy` line `` `Old` → `A` + `B` ``; disambiguation in each `NOT` |
    | **Merge** | Two terms are really one sense | Keep one line; the other Identifier moves into its `avoid:` list; entries merged |
    | **Retire** | Term was misleading, no single successor | `## Legacy` line `` `Old` → — (see `X`, `Y`) `` |
    | **Deprecate** | Concept being phased out | `## Legacy` line with `→` replacement and `in:` locations |
    
    **Key test**: Can you point to the **same concept** before and after the change?
    - Yes, same concept, better wording → **Rename** (keep as legacy alias for reading old code)
    - No, the concept actually changed → **Split** or **Merge** (not a rename)
    
    **Alias parsimony**: keep at most 1 legacy alias per term — the one readers will most
    likely encounter in old code. **Registry invariant** still holds after every edit: a name
    is under `avoid:` *or* in Legacy, never both.
    
    **Old layout?** No `thesaurus-format` frontmatter key (or `1.x`) means the pre-index prose layout —
    see "Migrating an Existing Thesaurus" in
    [references/generating-thesaurus.md](references/generating-thesaurus.md).
    
    ## Quick Checklist Before Naming Anything
    
    1. Did I grep the thesaurus for this name and its synonyms? Where did the hit land?
    2. Would a domain expert recognize this name?
    3. Does it contain a weasel word (Manager, Service, Handler, Info, Data, Item, Base, Util)?
    4. Is it too generic (could mean multiple things in different contexts)?
    5. Does it reveal infrastructure details (Mongo, Sql, Http, Dto, Entity, Model)?
    6. Is it consistent with other uses of this term across the codebase?
    7. Am I using the EXACT Identifier from the Index, or a synonym from its `avoid:` list?
    8. Am I in the right bounded context for this term?
    9. Does the name match its Kind — past tense for `event`, imperative for `command`?
    10. Can I explain what this name represents in one sentence using domain language?
    11. If the concept is new — did I add the Index line **and** the entry before using it?
    
    If any answer raises a concern — stop and fix before proceeding.
    

Comments (0)

Sign in to join the conversation.

No comments yet.

Reviews (0)

No reviews yet.