aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rwxr-xr-x.claude/hooks/validate-el.sh105
-rw-r--r--.claude/rules/commits.md66
-rw-r--r--.claude/rules/elisp-testing.md107
-rw-r--r--.claude/rules/elisp.md75
-rw-r--r--.claude/rules/testing.md277
-rw-r--r--.claude/rules/verification.md42
-rw-r--r--.gitignore20
-rw-r--r--LICENSE674
-rw-r--r--Makefile60
-rw-r--r--README.org20
-rw-r--r--docs/decisions/.gitkeep0
-rw-r--r--docs/design/gloss.org316
-rw-r--r--gloss-core.el32
-rw-r--r--gloss-display.el29
-rw-r--r--gloss-drill.el29
-rw-r--r--gloss-fetch.el35
-rw-r--r--gloss.el155
-rw-r--r--tests/fixtures/.gitkeep0
18 files changed, 2042 insertions, 0 deletions
diff --git a/.claude/hooks/validate-el.sh b/.claude/hooks/validate-el.sh
new file mode 100755
index 0000000..0c3a46c
--- /dev/null
+++ b/.claude/hooks/validate-el.sh
@@ -0,0 +1,105 @@
+#!/usr/bin/env bash
+# Validate and test .el files after Edit/Write/MultiEdit.
+# PostToolUse hook: receives tool-call JSON on stdin.
+#
+# On success: exit 0 silent.
+# On failure: emit JSON with hookSpecificOutput.additionalContext so Claude
+# sees a structured error in its context, THEN exit 2 to block the tool
+# pipeline. stderr still echoes the error for terminal visibility.
+#
+# Phase 1: check-parens + byte-compile
+# Phase 2: for non-test .el files, run matching tests/test-<stem>*.el
+
+set -u
+
+# Emit a JSON failure payload and exit 2. Arguments:
+# $1 — short failure type (e.g. "PAREN CHECK FAILED")
+# $2 — file path
+# $3 — emacs output (error body)
+fail_json() {
+ local ctx
+ ctx="$(printf '%s: %s\n\n%s\n\nFix before proceeding.' "$1" "$2" "$3" \
+ | jq -Rs .)"
+ cat <<EOF
+{"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": $ctx}}
+EOF
+ printf '%s: %s\n%s\n' "$1" "$2" "$3" >&2
+ exit 2
+}
+
+# Portable project root: prefer Claude Code's env var, fall back to deriving
+# from this script's location ($project/.claude/hooks/validate-el.sh).
+PROJECT_ROOT="${CLAUDE_PROJECT_DIR:-$(cd "$(dirname "$0")/../.." && pwd)}"
+
+f="$(jq -r '.tool_input.file_path // .tool_response.filePath // empty')"
+[ -z "$f" ] && exit 0
+[ "${f##*.}" = "el" ] || exit 0
+
+MAX_AUTO_TEST_FILES=20 # skip if more matches than this (large test suites)
+
+# --- Phase 1: syntax + byte-compile ---
+case "$f" in
+ */init.el|*/early-init.el)
+ # Byte-compile here would load the full package graph. Parens only.
+ if ! output="$(emacs --batch --no-site-file --no-site-lisp "$f" \
+ --eval '(check-parens)' 2>&1)"; then
+ fail_json "PAREN CHECK FAILED" "$f" "$output"
+ fi
+ ;;
+ *.el)
+ if ! output="$(emacs --batch --no-site-file --no-site-lisp \
+ -L "$PROJECT_ROOT" \
+ -L "$PROJECT_ROOT/modules" \
+ -L "$PROJECT_ROOT/tests" \
+ --eval '(package-initialize)' \
+ "$f" \
+ --eval '(check-parens)' \
+ --eval "(or (byte-compile-file \"$f\") (kill-emacs 1))" 2>&1)"; then
+ fail_json "VALIDATION FAILED" "$f" "$output"
+ fi
+ ;;
+esac
+
+# --- Phase 2: test runner ---
+# Determine which tests (if any) apply to this edit. Works for projects with
+# source at root, in modules/, or elsewhere — stem-based test lookup is the
+# common pattern.
+tests=()
+case "$f" in
+ */init.el|*/early-init.el)
+ : # Phase 1 handled it; skip test runner
+ ;;
+ "$PROJECT_ROOT/tests/testutil-"*.el)
+ stem="$(basename "${f%.el}")"
+ stem="${stem#testutil-}"
+ mapfile -t tests < <(find "$PROJECT_ROOT/tests" -maxdepth 1 -name "test-${stem}*.el" 2>/dev/null | sort)
+ ;;
+ "$PROJECT_ROOT/tests/test-"*.el)
+ tests=("$f")
+ ;;
+ *.el)
+ # Any other .el under the project — find matching tests by stem
+ stem="$(basename "${f%.el}")"
+ mapfile -t tests < <(find "$PROJECT_ROOT/tests" -maxdepth 1 -name "test-${stem}*.el" 2>/dev/null | sort)
+ ;;
+esac
+
+count="${#tests[@]}"
+if [ "$count" -ge 1 ] && [ "$count" -le "$MAX_AUTO_TEST_FILES" ]; then
+ load_args=()
+ for t in "${tests[@]}"; do load_args+=("-l" "$t"); done
+ # Run from tests/ so each file's `(require 'test-bootstrap (expand-file-name
+ # "test-bootstrap.el"))` resolves against the directory the bootstrap lives in,
+ # not the project root.
+ if ! output="$(cd "$PROJECT_ROOT/tests" && emacs --batch --no-site-file --no-site-lisp \
+ -L "$PROJECT_ROOT" \
+ -L "$PROJECT_ROOT/modules" \
+ -L "$PROJECT_ROOT/tests" \
+ --eval '(package-initialize)' \
+ -l ert "${load_args[@]}" \
+ --eval "(ert-run-tests-batch-and-exit '(not (tag :slow)))" 2>&1)"; then
+ fail_json "TESTS FAILED ($count test file(s))" "$f" "$output"
+ fi
+fi
+
+exit 0
diff --git a/.claude/rules/commits.md b/.claude/rules/commits.md
new file mode 100644
index 0000000..301c6ff
--- /dev/null
+++ b/.claude/rules/commits.md
@@ -0,0 +1,66 @@
+# Commit Rules
+
+Applies to: `**/*`
+
+## Author Identity
+
+All commits are authored as the user (repo owner / maintainer), never as
+Claude, Claude Code, Anthropic, or any AI tool. Git uses the configured
+`user.name` and `user.email` — do not modify git config to attribute
+otherwise.
+
+## No AI Attribution — Anywhere
+
+Absolutely no AI/LLM/Claude/Anthropic attribution in:
+
+- Commit messages (subject or body)
+- PR descriptions and titles
+- Issue comments and reviews
+- Code comments
+- Commit trailers
+- Release notes, changelogs, and any public-facing artifact
+
+This means:
+
+- **No** `Co-Authored-By: Claude …` (or Claude Code, or any AI) trailers
+- **No** "Generated with Claude Code" footers or equivalents
+- **No** 🤖 emojis or similar markers implying AI authorship
+- **No** references to "Claude", "Anthropic", "LLM", "AI tool" as a credited contributor
+- **No** attribution added via template defaults — strip them before committing
+
+If a tool, template, or default config inserts attribution, remove it. If
+settings.json needs it, set `attribution.commit: ""` and `attribution.pr: ""`
+to suppress the defaults.
+
+## Commit Message Format
+
+Conventional prefixes:
+
+- `feat:` — new feature
+- `fix:` — bug fix
+- `refactor:` — code restructuring, no behavior change
+- `test:` — adding or updating tests
+- `docs:` — documentation only
+- `chore:` — build, tooling, meta
+
+Subject line ≤72 characters. Body explains the *why* when not obvious.
+Skip the body entirely when the subject line is self-explanatory.
+
+## Before Committing
+
+1. Check author identity: `git log -1 --format='%an <%ae>'` — should be the user.
+2. Scan the message for AI-attribution language (including emojis and footers).
+3. Review the diff — only intended changes staged; no unrelated files.
+4. Run tests and linters (see `verification.md`).
+
+## If You Catch Yourself
+
+Typing any of the following — stop, delete, rewrite:
+
+- `Co-Authored-By: Claude`
+- `🤖 Generated with …`
+- "Created with Claude Code"
+- "Assisted by AI"
+
+Rewrite the commit as the user would write it: concise, focused on the
+change, no mention of how the change was produced.
diff --git a/.claude/rules/elisp-testing.md b/.claude/rules/elisp-testing.md
new file mode 100644
index 0000000..b5def78
--- /dev/null
+++ b/.claude/rules/elisp-testing.md
@@ -0,0 +1,107 @@
+# Elisp Testing Rules
+
+Applies to: `**/tests/*.el`
+
+Implements the core principles from `testing.md`. All rules there apply here —
+this file covers Elisp-specific patterns.
+
+## Framework: ERT
+
+Use `ert-deftest` for all tests. One test = one scenario.
+
+## File Layout
+
+- `tests/test-<module>.el` — tests for `<module>.el`
+- `tests/test-<module>--<helper>.el` — tests for a specific private helper (matches `<module>--<helper>` function naming)
+- `tests/testutil-<module>.el` — fixtures and mocks scoped to one module
+- `tests/testutil-*.el` — cross-module helpers (shared fixtures, generic mocks, filesystem helpers); name them for what they help with
+
+Tests must `(require 'module-name)` before the testutil file that stubs its internals, unless documented otherwise. Order matters — a testutil that defines a stub can be shadowed by a later `require` of the real module.
+
+## Test Naming
+
+```elisp
+(ert-deftest test-<module>-<function>-<scenario> ()
+ "Normal/Boundary/Error: brief description."
+ ...)
+```
+
+Put the category (Normal, Boundary, Error) in the docstring so the category is grep-able.
+
+## Required Coverage
+
+Every non-trivial function needs at least:
+- One **Normal** case (happy path)
+- One **Boundary** case (empty, nil, min, max, unicode, long string)
+- One **Error** case (invalid input, missing resource, failure mode)
+
+Missing a category is a test gap. If three cases look near-identical, parametrize with a loop or `dolist` rather than copy-pasting.
+
+## TDD Workflow
+
+Write the failing test first. A failing test proves you understand the change. Assume the bug is in production code until the test proves otherwise — never fix the test before proving the test is wrong.
+
+For untested code, write a **characterization test** that captures current behavior before you change anything. It becomes the safety net for the refactor.
+
+## Interactive vs Internal — Split for Testability
+
+When a function mixes business logic with user interaction, split it:
+
+- **Internal** (`cj/--foo`) — pure logic. All parameters explicit. No prompts,
+ no UI. Deterministic and trivially testable.
+- **Interactive wrapper** (`cj/foo`) — thin layer that reads user input and
+ delegates to the internal.
+
+```elisp
+(defun cj/--move-buffer-and-file (dir &optional ok-if-exists)
+ "Move the current buffer's file into DIR. Overwrite if OK-IF-EXISTS."
+ ...)
+
+(defun cj/move-buffer-and-file ()
+ "Interactive wrapper: prompt for DIR, delegate."
+ (interactive)
+ (let ((dir (read-directory-name "Move to: ")))
+ (cj/--move-buffer-and-file dir)))
+```
+
+Test the internal directly with parameter values — no `cl-letf` on
+`read-directory-name`, `yes-or-no-p`, etc. The wrapper gets a smoke test or
+nothing — Emacs already tests its own prompts. The internal also becomes
+reusable by other Elisp code without triggering UI.
+
+## Mocking
+
+Mock at boundaries:
+- Shell: `cl-letf` on `shell-command`, `shell-command-to-string`, `call-process`
+- File I/O when tests shouldn't touch disk
+- Network: URL retrievers, HTTP clients
+- Time: `cl-letf` on `current-time`, `format-time-string`
+
+Never mock:
+- The code under test
+- Core Emacs primitives (buffer ops, string ops, lists)
+- Your own domain logic — restructure it to be testable instead
+
+## Idioms
+
+- `cl-letf` for scoped overrides (self-cleaning)
+- `with-temp-buffer` for buffer manipulation tests
+- `make-temp-file` with `.el` suffix for on-disk fixtures
+- Tests must run in any order; no shared mutable state
+
+## Running Tests
+
+```bash
+make test # All
+make test-file FILE=tests/test-foo.el # One file
+make test-name TEST=pattern # Match by test name pattern
+```
+
+A PostToolUse hook runs matching tests automatically after edits to a module, when the match count is small enough to be fast.
+
+## Anti-Patterns
+
+- Hardcoded timestamps — generate relative to `current-time` or mock
+- Testing implementation details (private storage structure) instead of behavior
+- Mocking the thing you're testing
+- Skipping a failing test without an issue to track it
diff --git a/.claude/rules/elisp.md b/.claude/rules/elisp.md
new file mode 100644
index 0000000..e641058
--- /dev/null
+++ b/.claude/rules/elisp.md
@@ -0,0 +1,75 @@
+# Elisp / Emacs Rules
+
+Applies to: `**/*.el`
+
+## Style
+
+- 2-space indent, no tabs
+- Hyphen-case for identifiers: `cj/do-thing`, not `cj/doThing`
+- Naming prefixes:
+ - `cj/name` — user-facing functions and commands (bound to keys, called from init)
+ - `cj/--name` — private helpers (double-dash signals "internal")
+ - `<module>/name` — module-scoped where appropriate (e.g., `calendar-sync/parse-ics`)
+- File header: `;;; foo-config.el --- brief description -*- lexical-binding: t -*-`
+- `(provide 'foo-config)` at the bottom of every module
+- `lexical-binding: t` is mandatory — no file without it
+
+## Function Design
+
+- Keep functions under 15 lines where possible
+- One responsibility per function
+- Extract helpers instead of nesting deeply — 5+ levels of nesting is a refactor signal
+- Prefer named helpers over lambdas for anything nontrivial
+- No premature abstraction — three similar lines beats a clever macro
+
+Small functions are the single strongest defense against paren errors. Deeply nested code is where AI and humans both fail.
+
+## Requires and Loading
+
+- Every `(require 'foo)` must correspond to a loadable file on the load-path
+- Byte-compile warnings about free variables usually indicate a missing `require` or a typo in a symbol name — read them
+- Use `use-package` for external (MELPA/ELPA) packages
+- Use plain `(require 'foo-config)` for internal modules
+- For optional features, `(when (require 'foo nil t) ...)` degrades gracefully if absent
+
+## Lexical-Binding Traps
+
+- `(boundp 'x)` where `x` is a lexical variable always returns nil. Bind with `defvar` at top level if you need `boundp` to work, or use the value directly.
+- `setq` on an undeclared free variable is a warning — use `let` for locals or `defvar` for module-level state
+- Closures capture by reference. Avoid capturing mutating loop variables in nested defuns.
+
+## Regex Gotchas
+
+- `\s` is NOT whitespace in Emacs regex. Use `[ \t]` or `\\s-` (syntax class).
+- `^` in `string-match` matches after `\n` OR at position 0 — use `(= (match-beginning 0) start)` for positional checks when that matters.
+- `replace-regexp-in-string` interprets backslashes in the replacement. Pass `t t` (FIXEDCASE LITERAL) when the replacement contains literal backslashes.
+
+## Keybindings
+
+- `keymap-global-set` for global; `keymap-set KEYMAP ...` for mode-local
+- Group module-specific bindings inside the module's file
+- Autoload cookies (`;;;###autoload`) don't activate through plain `(require ...)` — use the form directly, not an autoloaded wrapper
+
+## Module Template
+
+```elisp
+;;; foo-config.el --- Foo feature configuration -*- lexical-binding: t -*-
+
+;;; Commentary:
+;; One-line description.
+
+;;; Code:
+
+;; ... code ...
+
+(provide 'foo-config)
+;;; foo-config.el ends here
+```
+
+Then `(require 'foo-config)` in `init.el` (or a config aggregator).
+
+## Editing Workflow
+
+- A PostToolUse hook runs `check-parens` and `byte-compile-file` on every `.el` save
+- If it blocks, read the error — don't retry blindly
+- Prefer Write over repeated Edits for nontrivial new code; incremental edits accumulate subtle paren mismatches
diff --git a/.claude/rules/testing.md b/.claude/rules/testing.md
new file mode 100644
index 0000000..b91b76c
--- /dev/null
+++ b/.claude/rules/testing.md
@@ -0,0 +1,277 @@
+# Testing Standards
+
+Applies to: `**/*`
+
+Core TDD discipline and test quality rules. Language-specific patterns
+(frameworks, fixture idioms, mocking tools) live in per-language testing files
+under `languages/<lang>/claude/rules/`.
+
+## Test-Driven Development (Default)
+
+TDD is the default workflow for all code, including demos and prototypes. **Write tests first, before any implementation code.** Tests are how you prove you understand the problem — if you can't write a failing test, you don't yet understand what needs to change.
+
+1. **Red**: Write a failing test that defines the desired behavior
+2. **Green**: Write the minimal code to make the test pass
+3. **Refactor**: Clean up while keeping tests green
+
+Do not skip TDD for demo code. Demos build muscle memory — the habit carries into production.
+
+### Understand Before You Test
+
+Before writing tests, invest time in understanding the code:
+
+1. **Explore the codebase** — Read the module under test, its callers, and its dependencies. Understand the data flow end to end.
+2. **Identify the root cause** — If fixing a bug, trace the problem to its origin. Don't test (or fix) surface symptoms when the real issue is deeper in the call chain.
+3. **Reason through edge cases** — Consider boundary conditions, error states, concurrent access, and interactions with adjacent modules. Your tests should cover what could actually go wrong, not just the obvious happy path.
+
+### Adding Tests to Existing Untested Code
+
+When working in a codebase without tests:
+
+1. Write a **characterization test** that captures current behavior before making changes
+2. Use the characterization test as a safety net while refactoring
+3. Then follow normal TDD for the new change
+
+## Test Categories (Required for All Code)
+
+Every unit under test requires coverage across three categories:
+
+### 1. Normal Cases (Happy Path)
+- Standard inputs and expected use cases
+- Common workflows and default configurations
+- Typical data volumes
+
+### 2. Boundary Cases
+- Minimum/maximum values (0, 1, -1, MAX_INT)
+- Empty vs null vs undefined (language-appropriate)
+- Single-element collections
+- Unicode and internationalization (emoji, RTL text, combining characters)
+- Very long strings, deeply nested structures
+- Timezone boundaries (midnight, DST transitions)
+- Date edge cases (leap years, month boundaries)
+
+### 3. Error Cases
+- Invalid inputs and type mismatches
+- Network failures and timeouts
+- Missing required parameters
+- Permission denied scenarios
+- Resource exhaustion
+- Malformed data
+
+## Combinatorial Coverage
+
+For functions with 3+ parameters that each take multiple values (feature-flag
+combinations, config matrices, permission/role interactions, multi-field
+form validation, API parameter spaces), the exhaustive test count explodes
+(M^N) while 3-5 ad-hoc cases miss pair interactions. Use **pairwise /
+combinatorial testing** — generate a minimal matrix that hits every 2-way
+combination of parameter values. Empirically catches 60-90% of combinatorial
+bugs with 80-99% fewer tests.
+
+Invoke `/pairwise-tests` on the offending function; continue using `/add-tests`
+and the Normal/Boundary/Error discipline for the rest. The two approaches
+complement: pairwise covers parameter *interactions*; category discipline
+covers each parameter's individual edge space.
+
+Skip pairwise when: the function has 1-2 parameters (just write the cases),
+the context requires *provably* exhaustive coverage (regulated systems — document
+in an ADR), or the testing target is non-parametric (single happy path,
+performance regression, a specific error).
+
+## Test Organization
+
+Typical layout:
+
+```
+tests/
+ unit/ # One test file per source file
+ integration/ # Multi-component workflows
+ e2e/ # Full system tests
+```
+
+Per-language files may adjust this (e.g. Elisp collates ERT tests into
+`tests/test-<module>*.el` without subdirectories).
+
+### Testing Pyramid
+
+Rough proportions for most projects:
+- Unit tests: 70-80% (fast, isolated, granular)
+- Integration tests: 15-25% (component interactions, real dependencies)
+- E2E tests: 5-10% (full system, slowest)
+
+Don't duplicate coverage: if unit tests fully exercise a function's logic,
+integration tests should focus on *how* components interact — not repeat the
+function's case coverage.
+
+## Integration Tests
+
+Integration tests exercise multiple components together. Two rules:
+
+**The docstring names every component integrated** and marks which are real vs
+mocked. Integration failures are harder to pinpoint than unit failures;
+enumerating the participants up front tells you where to start looking.
+
+Example:
+
+```
+def test_integration_refund_during_sync_updates_ledger_atomically():
+ """Refund processed mid-sync updates order and ledger in one transaction.
+
+ Components integrated:
+ - OrderService.refund (entry point)
+ - PaymentGateway.reverse (MOCKED — returns success)
+ - Ledger.credit (real)
+ - db.transaction (real)
+
+ Validates:
+ - Refund rolls back if ledger write fails
+ - Both tables updated or neither
+ """
+```
+
+**Write an integration test when** multiple components must work together,
+state crosses function boundaries, or edge cases combine. **Don't** when
+single-function behavior suffices, or when mocking would erase the interaction
+you meant to test.
+
+## Naming Convention
+
+- Unit: `test_<module>_<function>_<scenario>_<expected>`
+- Integration: `test_integration_<workflow>_<scenario>_<outcome>`
+
+Examples:
+- `test_cart_apply_discount_expired_coupon_raises_error`
+- `test_integration_order_sync_network_timeout_retries_three_times`
+
+Languages that prefer camelCase, kebab-case, or other conventions keep the
+structure but use their idiom. Consistency within a project matters more than
+the specific case choice.
+
+## Test Quality
+
+### Independence
+- No shared mutable state between tests
+- Each test runs successfully in isolation
+- Explicit setup and teardown
+
+### Determinism
+- Never hardcode dates or times — generate them relative to `now()`
+- No reliance on test execution order
+- No flaky network calls in unit tests
+
+### Performance
+- Unit tests: <100ms each
+- Integration tests: <1s each
+- E2E tests: <10s each
+- Mark slow tests with appropriate decorators/tags
+
+### Mocking Boundaries
+Mock external dependencies at the system boundary:
+- Network calls (HTTP, gRPC, WebSocket)
+- File I/O and cloud storage
+- Time and dates
+- Third-party service clients
+
+Never mock:
+- The code under test
+- Internal domain logic
+- Framework behavior (ORM queries, middleware, hooks, buffer primitives)
+
+### Signs of Overmocking
+
+Ask yourself:
+
+- Would this test still pass if I replaced the function body with `raise NotImplementedError` (or equivalent)? If yes, the mocks are doing the work — you're testing mocks, not code.
+- Is the mock more complex than the function being tested? Smell.
+- Am I mocking internal string / parsing / decoding helpers? Those aren't boundaries — they're the work.
+- Does the test break when I refactor without changing behavior? Good tests survive refactors; overmocked ones couple to implementation.
+
+When tests demand heavy internal mocking, the fix isn't better mocks — it's
+restructuring the code (see *If Tests Are Hard to Write* below).
+
+### Testing Code That Uses Frameworks
+
+When a function mostly delegates to framework or library code, test *your*
+integration logic:
+- ✓ "I call the library with the right arguments in the right context"
+- ✓ "I handle its return value correctly"
+- ✗ "The library works in 50 scenarios" — trust it; it has its own tests
+
+For polyglot behavior (e.g., comment handling across C/Java/Go/JS), test 2-3
+representative modes thoroughly plus a minimal smoke test in the others.
+Exhaustive permutations are diminishing returns.
+
+### Test Real Code, Not Copies
+
+Never inline or copy production code into test files. Always `require`/`import`
+the module under test. Copied code passes even when production breaks — the
+bug hides behind the duplicate.
+
+Mock dependencies at their boundary; exercise the real function body.
+
+### Error Behavior, Not Error Text
+
+Test that errors occur with the right type; don't assert exact wording:
+- ✓ Right exception type (`pytest.raises(ValueError)`, `(should-error ... :type 'user-error)`)
+- ✓ Regex on values the message *must* contain (e.g., the offending filename)
+- ✗ `assert str(e) == "File 'foo' not found"` — breaks when prose changes even though behavior is unchanged
+
+Production code should emit clear, contextual errors. Tests verify the
+behavior (raised, caught, returned nil) and values that must appear — not the
+prose.
+
+## If Tests Are Hard to Write, Refactor the Code
+
+If a test needs extensive mocking of internal helpers, elaborate fixture
+scaffolding, or mocks that recreate the function's own logic, the production
+code needs restructuring — not the test.
+
+Signals:
+- Deep nesting (callbacks inside callbacks)
+- Long functions doing multiple things ("fetch AND parse AND decode AND save")
+- Tests that mock internal string / parsing / I/O helpers
+- Tests that break on refactors with no behavior change
+
+Fix: extract focused helpers (one responsibility each), test each in isolation
+with real inputs, compose them in a thin outer function. Several small unit
+tests plus one composition test beats one monster test behind a wall of mocks.
+
+## Coverage Targets
+
+- Business logic and domain services: **90%+**
+- API endpoints and views: **80%+**
+- UI components: **70%+**
+- Utilities and helpers: **90%+**
+- Overall project minimum: **80%+**
+
+New code must not decrease coverage. PRs that lower coverage require justification.
+
+## TDD Discipline
+
+TDD is non-negotiable. These are the rationalizations agents use to skip it — don't fall for them:
+
+| Excuse | Why It's Wrong |
+|--------|----------------|
+| "This is too simple to need a test" | Simple code breaks too. The test takes 30 seconds. Write it. |
+| "I'll add tests after the implementation" | You won't, and even if you do, they'll test what you wrote rather than what was needed. Test-after validates implementation, not behavior. |
+| "Let me just get it working first" | That's not TDD. If you can't write a failing test, you don't understand the requirement yet. |
+| "This is just a refactor" | Refactors without tests are guesses. Write a characterization test first, then refactor while it stays green. |
+| "I'm only changing one line" | One-line changes cause production outages. Write a test that covers the line you're changing. |
+| "The existing code has no tests" | Start with a characterization test. Don't make the problem worse. |
+| "This is demo/prototype code" | Demos build habits. Untested demo code becomes untested production code. |
+| "I need to spike first" | Spikes are fine — then throw away the spike, write the test, and implement properly. |
+
+If you catch yourself thinking any of these, stop and write the test.
+
+## Anti-Patterns (Do Not Do)
+
+- Hardcoded dates or timestamps (they rot)
+- Testing implementation details instead of behavior
+- Mocking the thing you're testing
+- Mocking internal helpers (string ops, parsing, decoding) — those are the work
+- Inlining production code into test files — always `require` / `import` the real module
+- Asserting exact error-message text instead of type + key values
+- Shared mutable state between tests
+- Non-deterministic tests (random without seed, network in unit tests)
+- Testing framework behavior instead of your code
+- Ignoring or skipping failing tests without a tracking issue
diff --git a/.claude/rules/verification.md b/.claude/rules/verification.md
new file mode 100644
index 0000000..8993736
--- /dev/null
+++ b/.claude/rules/verification.md
@@ -0,0 +1,42 @@
+# Verification Before Completion
+
+Applies to: `**/*`
+
+## The Rule
+
+Do not claim work is done without fresh verification evidence. Run the command, read the output, confirm it matches the claim, then — and only then — declare success.
+
+This applies to every completion claim:
+- "Tests pass" → Run the test suite. Read the output. Confirm all green.
+- "Linter is clean" → Run the linter. Read the output. Confirm no warnings.
+- "Build succeeds" → Run the build. Read the output. Confirm no errors.
+- "Bug is fixed" → Run the reproduction steps. Confirm the bug is gone.
+- "No regressions" → Run the full test suite, not just the tests you added.
+
+## What Fresh Means
+
+- Run the verification command **now**, in the current session
+- Do not rely on a previous run from before your changes
+- Do not assume your changes didn't break something unrelated
+- Do not extrapolate from partial output — read the whole result
+
+## Red Flags
+
+If you find yourself using these words, you haven't verified:
+
+- "should" ("tests should pass")
+- "probably" ("this probably works")
+- "I believe" ("I believe the build is clean")
+- "based on the changes" ("based on the changes, nothing should break")
+
+Replace beliefs with evidence. Run the command.
+
+## Before Committing
+
+Before any commit:
+1. Run the test suite — confirm all tests pass
+2. Run the linter — confirm no new warnings
+3. Run the type checker — confirm no new errors
+4. Review the diff — confirm only intended changes are staged
+
+Do not commit based on the assumption that nothing broke. Verify.
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..621111a
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,20 @@
+/todo.org
+/.ai/
+/inbox/
+
+# Personal Claude tooling state
+/.claude/settings.local.json
+/.claude/.cache/
+
+# Elisp build artefacts
+*.elc
+*.eln
+
+# Test logs
+/tests/*-output.log
+
+# OS / editor noise
+.DS_Store
+*~
+\#*\#
+.\#*
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..047039a
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,60 @@
+# Makefile for gloss
+# Run `make help' for available targets.
+
+EMACS ?= emacs
+EMACSFLAGS = --batch -Q
+LOADPATH = -L . -L tests
+
+PACKAGE_FILES = $(filter-out gloss-pkg.el,$(wildcard gloss*.el))
+TEST_FILES = $(wildcard tests/test-*.el)
+UNIT_TESTS = $(filter-out tests/test-integration-%.el,$(TEST_FILES))
+INTEGRATION_TESTS = $(wildcard tests/test-integration-*.el)
+
+.PHONY: help test test-unit test-integration test-file test-name validate-parens compile lint clean
+
+help:
+ @echo "Targets:"
+ @echo " make test Run all tests"
+ @echo " make test-unit Unit tests only"
+ @echo " make test-integration Integration tests only"
+ @echo " make test-file FILE=path/to/test-foo.el Run one test file"
+ @echo " make test-name TEST=pattern Run tests whose name matches PATTERN"
+ @echo " make validate-parens check-parens on every .el"
+ @echo " make compile Byte-compile package files"
+ @echo " make lint elisp-lint pass"
+ @echo " make clean Remove .elc"
+
+test:
+ @$(EMACS) $(EMACSFLAGS) $(LOADPATH) -l ert $(addprefix -l ,$(TEST_FILES)) -f ert-run-tests-batch-and-exit
+
+test-unit:
+ @$(EMACS) $(EMACSFLAGS) $(LOADPATH) -l ert $(addprefix -l ,$(UNIT_TESTS)) -f ert-run-tests-batch-and-exit
+
+test-integration:
+ @$(EMACS) $(EMACSFLAGS) $(LOADPATH) -l ert $(addprefix -l ,$(INTEGRATION_TESTS)) -f ert-run-tests-batch-and-exit
+
+test-file:
+ @if [ -z "$(FILE)" ]; then echo "Usage: make test-file FILE=tests/test-NAME.el"; exit 1; fi
+ @$(EMACS) $(EMACSFLAGS) $(LOADPATH) -l ert -l "$(FILE)" -f ert-run-tests-batch-and-exit
+
+test-name:
+ @if [ -z "$(TEST)" ]; then echo "Usage: make test-name TEST=pattern"; exit 1; fi
+ @$(EMACS) $(EMACSFLAGS) $(LOADPATH) -l ert $(addprefix -l ,$(TEST_FILES)) --eval "(ert-run-tests-batch-and-exit \"$(TEST)\")"
+
+validate-parens:
+ @for f in $(PACKAGE_FILES) $(TEST_FILES); do \
+ echo " check-parens: $$f"; \
+ $(EMACS) --batch --eval "(progn (find-file \"$$f\") (check-parens))" 2>&1 | grep -v '^Loading' || true; \
+ done
+
+compile:
+ @for f in $(PACKAGE_FILES); do \
+ echo " byte-compile: $$f"; \
+ $(EMACS) $(EMACSFLAGS) $(LOADPATH) --eval "(byte-compile-file \"$$f\")"; \
+ done
+
+lint:
+ @$(EMACS) $(EMACSFLAGS) $(LOADPATH) -l elisp-lint --funcall elisp-lint-files-batch $(PACKAGE_FILES)
+
+clean:
+ @rm -f *.elc tests/*.elc
diff --git a/README.org b/README.org
new file mode 100644
index 0000000..659fc89
--- /dev/null
+++ b/README.org
@@ -0,0 +1,20 @@
+#+TITLE: gloss — Glossary Lookup with Online-Sourced Selection
+#+OPTIONS: toc:nil
+
+A personal Emacs glossary. =C-h g= looks up terms in a single git-tracked org file. On a local miss, =gloss= fetches candidate definitions from Wiktionary and prompts you to pick which one to save — with provenance recorded. The same org file feeds =org-drill= for spaced-repetition study.
+
+* Status
+
+In active development. v1 not yet released. See [[file:docs/design/gloss.org][docs/design/gloss.org]] for the full design.
+
+* Why not just =quick-sdcv= or =dictionary=?
+
+Domain jargon — government acronyms, technical terms, philosophy vocabulary, project-specific names — doesn't live in any general dictionary, so =quick-sdcv= and =M-x dictionary= can't help. =gloss= grows by use: encounter a term, save it once, and it's permanently looked-up-able and study-card-able.
+
+* Quick start
+
+(This section will fill out as v1 lands. For now, see [[file:docs/design/gloss.org][docs/design/gloss.org]].)
+
+* License
+
+GPL-3.0-or-later. See [[file:LICENSE][LICENSE]].
diff --git a/docs/decisions/.gitkeep b/docs/decisions/.gitkeep
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/docs/decisions/.gitkeep
diff --git a/docs/design/gloss.org b/docs/design/gloss.org
new file mode 100644
index 0000000..04efc38
--- /dev/null
+++ b/docs/design/gloss.org
@@ -0,0 +1,316 @@
+#+TITLE: Design — gloss (Glossary Lookup with Online-Sourced Selection)
+#+DATE: 2026-04-28
+#+STATUS: Draft
+
+* Problem
+
+A personal glossary inside Emacs, modelled on the existing =quick-sdcv= UX (=C-h d=) but for self-curated terms rather than packaged dictionaries. =C-h g= prompts for a term (defaulting to word-at-point), looks it up in a single git-tracked org file, and shows the definition in a side buffer that =q= dismisses. On a local miss, the package fetches candidate definitions from an online source, lets the user pick one, and saves it with provenance. The same org file feeds =org-drill= for spaced-repetition study.
+
+The pain point: domain jargon — government acronyms, technical terms, philosophy vocabulary, project-specific names — doesn't live in any general dictionary, so existing tools like =quick-sdcv= can't help. A personal glossary that grows by use (encounter term → save it once → it's permanently looked-up-able and study-card-able) closes that gap.
+
+* Non-Goals
+
+The following are explicitly out of scope for v1. Each is a defensible v2+ topic on its own.
+
+- *Multi-language support.* English only. Wiktionary returns French/Latin/etc. — v1 ignores everything but the =en= key.
+- *Synonyms, cross-references, related terms.* Even when the upstream source returns them, v1 stores only the picked definition.
+- *Audio pronunciation.* Not fetched, not played.
+- *Etymology, usage notes, parsed examples.* Discarded during HTML strip.
+- *Multiple glossaries / domain separation.* One file, one glossary.
+- *Backup or sync infrastructure.* Delegated to git on whatever path =gloss-file= points at.
+- *Org-drill scheduling control.* The exporter prepares entries; =org-drill= itself runs unmodified.
+
+In scope (kept after triage): edit-in-place via =C-h g e=, which jumps to the source file at the entry's heading.
+
+* Approaches Considered
+
+Six approaches evaluated during brainstorm. Three conventional, three tail samples for diversity.
+
+** Recommended: Layered multi-module package
+
+Five =.el= files, each owning one concern: =gloss-core= (data), =gloss-fetch= (network), =gloss-display= (UI), =gloss-drill= (drill export), =gloss= (orchestration entry point). Each layer mocks at its own natural boundary; no layer mocks another layer's internals.
+
+*Why this over the alternatives.* The codebase already prefers layering — =coverage-core= + =coverage-elisp= split, Hugo pure-helpers + interactive wrappers, LSP file-watch defvar + function. The four concerns (data, fetch, display, drill) have genuinely different test boundaries (file I/O, HTTP, mode UI, =org-element=). Mixing them in one file would force overmocking, which the project's testing rules flag as a smell. The package is also public-style — clear module boundaries reward cold readers.
+
+*What's traded away.* About 30 minutes more structural setup at the start, in exchange for boilerplate that may never pay off if the package stays personal forever. Cheap trade against the testing and reading wins.
+
+** Rejected: Single-file quick-sdcv-clone
+
+One =.el= file (~400 lines) covering all four concerns. Simplest path, lowest dependency footprint, but everything (data, HTTP, mode definition, drill) cohabits a single namespace. Test isolation gets awkward; refactor cost grows when one piece needs replacing.
+
+** Rejected: Backend-pluggable registry
+
+A =glossary-backend= protocol covering both local-org and online sources, with =lookup= / =save= / =list= operations. Local and online become interchangeable backends. Real future-proofing, but for v1 with two backends and probably never a third, the protocol is overkill — YAGNI risk. The forward-compat shape we did adopt (the =gloss-fetch-sources= registry, see Architecture) gets the same benefit at a fraction of the design weight, scoped only to where source variety is real.
+
+** Rejected: quick-sdcv + generated StarDict
+
+Round-trip the org file through StarDict format on save; reuse =quick-sdcv='s UI verbatim. Reuses 100% of an existing UI but loses provenance metadata in the round-trip, fights drill (which reads org, not StarDict), and forces a binary intermediate format for what should be a plain-text data store.
+
+** Rejected: Org-roam node per term
+
+Each entry is its own =org-roam= node. Free fuzzy/exact title search, free backlinks. But it's a heavy dependency for an otherwise self-contained package, file-explodes (1000 terms = 1000 files), and contradicts the locked single-file storage decision.
+
+** Rejected: Lazy-reactive minor mode
+
+Passive recognition — =gloss-mode= scans buffer text for known terms, underlines them, hover/click reveals definitions. Different and arguably more-natural mental model, but it reframes the brief (active =C-h g= lookup is what was asked for) and doesn't naturally support online fallback or auto-add. Probably belongs as a v3 feature on top of the layered architecture, not as the architecture itself.
+
+* Design
+
+** Architecture
+
+Five =.el= files:
+
+#+begin_example
+gloss-core.el data layer — org file I/O + in-memory cache
+gloss-fetch.el network layer — Wiktionary REST + HTML strip
+gloss-display.el UI layer — side buffer + picker
+gloss-drill.el drill export — :drill: tag + twosided property
+gloss.el entry point — defcustoms, prefix keymap, user commands
+#+end_example
+
+*Public API by layer.*
+
+=gloss-core=: =gloss-core-lookup TERM=, =gloss-core-save TERM DEFINITION SOURCE=, =gloss-core-list=, =gloss-core-find-buffer-position TERM=.
+
+=gloss-fetch=: =gloss-fetch-definitions TERM= → =(:ok DEFS) | (:empty :no-defs SOURCES :failed SOURCES)=. Internally a registry: =gloss-fetch--sources= alist (source-symbol → fetcher function), walked in order per the user-facing =gloss-fetch-sources= defcustom.
+
+=gloss-display=: =gloss-display-show-entry TERM BODY=, =gloss-display-pick-definition TERM DEFINITIONS=. Defines =gloss-mode= (derived from =special-mode=, =q= quits).
+
+=gloss-drill=: =gloss-drill-export-all=, =gloss-drill-untag-all=. Operates on the org file via =org-element=.
+
+=gloss=: =defcustom gloss-file= (path), =gloss-prefix-map= for =C-h g=, user commands =gloss-lookup=, =gloss-add=, =gloss-edit=, =gloss-fetch-online=, =gloss-drill-export=.
+
+** Data Flow
+
+*Shapes.*
+
+A definition (in flight from fetch through display to save) is a plist:
+
+#+begin_src emacs-lisp
+(:source wiktionary :text "Reference to something earlier in the discourse...")
+#+end_src
+
+An entry (saved in cache and on disk) is a plist:
+
+#+begin_src emacs-lisp
+(:term "anaphora"
+ :body "Reference to something earlier in the discourse..."
+ :source wiktionary
+ :added "2026-04-28"
+ :marker #<marker at 1247 in gloss.org>)
+#+end_src
+
+The cache is a hash table, term-string → entry-plist. The org file is the source of truth; the cache is a read-side index.
+
+*Lookup flow (=C-h g=).*
+
+1. Read input — word-at-point if available, else minibuffer prompt.
+2. =gloss-core-lookup TERM=. Cache loaded if cold.
+3. Hit → =gloss-display-show-entry=. Done.
+4. Miss → silent fall-through to =gloss-fetch-definitions TERM=.
+5. Orchestrate on result:
+ - 0 definitions or all-failures → side buffer message (see Error Handling).
+ - 1 definition → auto-save via =gloss-core-save=, then =gloss-display-show-entry=.
+ - >1 definitions → =gloss-display-pick-definition= → user picks → =gloss-core-save= → =gloss-display-show-entry=.
+
+*Add flow (=C-h g a=).*
+
+=gloss-add= prompts for term and body (small temp buffer for multi-line body, =C-c C-c= accepts). =gloss-core-save TERM BODY 'manual=. Then =gloss-display-show-entry=.
+
+*Edit flow (=C-h g e=).*
+
+=gloss-edit= resolves the term to a buffer position via =gloss-core-find-buffer-position=. Opens the org file at that heading in the *source* buffer (not the side buffer). User edits inline. On save, the buffer-local =after-save-hook= refreshes the cache for that single term.
+
+*Drill export (=C-h g D=).*
+
+=gloss-drill-export-all= walks the org file via =org-element=, ensures every term heading has =:drill:= tag and =:DRILL_CARD_TYPE: twosided= property. =M-x org-drill= runs the session — gloss does not wrap or invoke =org-drill= itself.
+
+** Persistence
+
+*File shape.* Single org file at =gloss-file= (default: =(expand-file-name "gloss.org" (or org-directory user-emacs-directory))=). One =* term= heading per entry, alphabetical order maintained on insert. Each entry has a =:PROPERTIES:= drawer with =:SOURCE:= and =:ADDED:=. Body is plain text immediately under the heading.
+
+#+begin_example
+#+TITLE: Glossary
+#+STARTUP: showall
+
+* anaphora
+:PROPERTIES:
+:SOURCE: wiktionary
+:ADDED: 2026-04-28
+:END:
+Reference to something earlier in the discourse...
+
+* SBIR
+:PROPERTIES:
+:SOURCE: wiktionary
+:ADDED: 2026-04-28
+:END:
+Initialism of Small Business Innovation Research...
+#+end_example
+
+After =gloss-drill-export-all=, the heading line gains a =:drill:= tag and the properties drawer gains =:DRILL_CARD_TYPE: twosided=.
+
+*Cache lifecycle.* Hash table loaded lazily on first lookup of the session. Populated by reading =gloss-file= once and parsing with =org-element-parse-buffer=. Subsequent lookups hit the cache directly.
+
+*Cache invalidation.* Four triggers, in order of cost:
+
+1. =gloss-core-save= mutates the cache directly when it writes.
+2. *mtime check on every lookup.* =file-attributes= the file before each =gloss-core-lookup= returns; if mtime > cached-mtime, reload before answering. Sub-millisecond cost; catches every out-of-band edit (other Emacs session, =git pull=, hand-edit, =sed=).
+3. =gloss-edit='s buffer-local =after-save-hook= updates the single edited term immediately; overlaps with #2 but doesn't wait for the next lookup.
+4. Manual =gloss-reload= command — nuclear option for paranoia.
+
+=file-notify-add-watch= rejected: platform-specific backend, async callback complicates the model, mtime path is already sub-millisecond.
+
+*Write strategy.* Append-on-add via direct buffer editing (=find-file-noselect=, insert at the alphabetically-correct heading position, save, kill the buffer if not previously open). No journal, no temp file — org-mode's =auto-save-mode= and the user's git tracking provide durability. Single-user, single-Emacs assumed; concurrent access isn't a concern.
+
+*Alphabetical order.* Maintained on insert via case-insensitive string compare. Cheap; the file stays diff-clean (only the inserted block changes).
+
+** Error Handling
+
+*Per-source status taxonomy.* Five internal values; three user-facing rollups.
+
+#+begin_src emacs-lisp
+;; Internal per-source result:
+(:source SYM :status STATUS :reason STRING)
+
+;; STATUS values:
+;; :ok :defs (def1 def2 ...) — success
+;; :no-defs — server reached, term not there (HTTP 404 or empty 200)
+;; :unreachable — network problem (DNS, refused, timeout)
+;; :server-error — HTTP 5xx, malformed JSON, schema mismatch, HTTP 4xx other than 404/429
+;; :rate-limited — HTTP 429
+#+end_src
+
+*=:reason= strings* carry the technical detail (=timeout (5s)=, =HTTP 503=, =malformed JSON: ...=) and land in =*gloss-debug*=. They are never user-facing.
+
+*User-facing rollup.* =gloss-fetch-definitions= aggregates per-source results into:
+
+#+begin_src emacs-lisp
+(:ok DEFS) ;; any source returned >=1 def
+(:empty :no-defs (...) :failed (...)) ;; everything else
+#+end_src
+
+=:failed= unions =:unreachable=, =:server-error=, =:rate-limited=.
+
+| Result shape | Message |
+|-------------------------------------------+--------------------------------------------------------------------|
+| Every source =:no-defs=, none failed | "No definition for X in Wiktionary." |
+| Every source failed, none =:no-defs= | "Couldn't reach Wiktionary." |
+| Mix of =:no-defs= and failures | "No definition in Wiktionary; couldn't reach DictionaryAPI." |
+| Any =:ok= with defs | Silent on others — picker shows what came back |
+
+When v2 starts surfacing =:rate-limited= regularly, the rollup wording will gain a third visible category. v1 with no-key Wiktionary doesn't need it.
+
+*libxml as a precondition, not a per-source failure.* First time =gloss-fetch-definitions= runs, probe =(libxml-parse-html-region 1 1)= on a temp buffer. If unavailable, online fetching is disabled package-wide for the session with a one-shot =user-error=: "Online fetch requires Emacs built with libxml2; manual add still works." Subsequent online attempts in the session short-circuit to that message.
+
+*Partial-success on per-sense HTML failures.* If libxml is available but fails on a specific sense's content, drop that sense and return the rest. Source status stays =:ok= with N-1 entries; the dropped sense logs to =*gloss-debug*=. A single bad sense doesn't poison the whole source.
+
+*Storage failures.* First call creates =gloss-file= and any missing parent directory with a =#+TITLE: Glossary= header. Permission denied raises =user-error= naming the path. Corrupt org file (=org-element-parse-buffer= raises) preserves the existing cache and surfaces "glossary file corrupt at line N; cache not refreshed" — operations fall back to the stale cache until the user fixes the file and runs =gloss-reload=. Term collision (saving an existing term) prompts: replace, append-with-separator, or cancel.
+
+*Drill.* =org-drill= checked via =featurep= before export runs. If absent: =user-error= with install hint.
+
+*User cancellations.* =C-g= during the picker → no save, side buffer shows the local-miss state. Empty term input from =gloss-add= → re-prompt once, then abort silently. Cancelled at the term-collision prompt → no write.
+
+** Testing
+
+Per-function test files; three categories (Normal/Boundary/Error) per function. TDD by default. Real production code via =require=, never inlined.
+
+*=gloss-core=.* Temp files + real =org-element-parse-buffer=. No mocking — exercises the actual file I/O and parser.
+
+#+begin_example
+test-gloss-core--lookup.el
+test-gloss-core--save.el
+test-gloss-core--invalidate-on-mtime.el
+test-gloss-core--corrupt-file-preserves-cache.el
+test-gloss-core--alphabetical-insert.el
+test-gloss-core--first-call-creates-file.el
+#+end_example
+
+*=gloss-fetch=.* =cl-letf= mock on =url-retrieve-synchronously=, injecting canned response buffers. Captured Wiktionary fixtures in =tests/fixtures/wiktionary-*.json= — real responses for SBIR, anaphora, API, frozen once, replayed forever.
+
+#+begin_example
+test-gloss-fetch--definitions-200-returns-ok.el
+test-gloss-fetch--definitions-404-returns-no-defs.el
+test-gloss-fetch--definitions-500-returns-server-error.el
+test-gloss-fetch--definitions-timeout-returns-unreachable.el
+test-gloss-fetch--strip-html.el
+test-gloss-fetch--multi-source-walks-registry.el
+test-gloss-fetch--libxml-probe.el
+#+end_example
+
+*=gloss-display=.* The candidate-formatting helper =gloss-display--format-candidate PLIST → "[wiktionary] text..."= is pure → full N/B/E coverage. =gloss-display-show-entry= and =gloss-mode= get one smoke test each (Emacs already tests =switch-to-buffer= and major-mode definition).
+
+#+begin_example
+test-gloss-display--format-candidate.el
+test-gloss-display--show-entry-smoke.el
+#+end_example
+
+*=gloss-drill=.* Temp file + real =org-element=. Tests assert tag/property changes on entries.
+
+#+begin_example
+test-gloss-drill--export-all-tags-untagged.el
+test-gloss-drill--export-all-skips-already-tagged.el
+test-gloss-drill--export-all-no-orgdrill-installed.el
+test-gloss-drill--untag-all.el
+#+end_example
+
+*=gloss=.* The orchestration policy =gloss--orchestrate-fetch-result RESULT → SYMBOL= is a pure pattern-matcher. Tested with shaped inputs covering every result variant.
+
+#+begin_example
+test-gloss--orchestrate-fetch-result.el
+#+end_example
+
+*Integration tests.* Three small ones, each with a docstring naming participants per project convention.
+
+#+begin_example
+test-integration-gloss-lookup-flow-local-hit.el
+test-integration-gloss-lookup-flow-online-fall-through.el
+test-integration-gloss-lookup-flow-online-failure.el
+#+end_example
+
+*Coverage targets.* 90%+ on =gloss-core=, =gloss-fetch=, =gloss-drill=, and pure helpers in =gloss-display= / =gloss=. 70%+ on display mode-glue. Overall ≥80%.
+
+** Observability
+
+*=*gloss-debug*= log buffer.* Off until =gloss-debug= defcustom is non-nil, or session-only =gloss-toggle-debug= flips it. One timestamped, layer-prefixed line per significant event.
+
+#+begin_example
+2026-04-28 11:14:02 [fetch:wiktionary] GET /API → 200, 12 senses
+2026-04-28 11:14:02 [fetch:wiktionary] sense 7 HTML parse failed, dropping
+2026-04-28 11:14:02 [core] cache hit for "anaphora"
+2026-04-28 11:14:09 [core] mtime change detected, reloading cache (47 terms)
+2026-04-28 11:14:11 [save] "API" → wiktionary, 11 alts not saved
+#+end_example
+
+Per-source statuses from Error Handling land here verbatim. No personal data beyond user-supplied terms.
+
+*=*Messages*= for user-facing events.* Saves, picker-shown, "no definition found" messages — short single-line =message= calls, persisted in =*Messages*= via Emacs idiom. Strict separation: =*Messages*= for things the user did or asked for; =*gloss-debug*= for everything else.
+
+*Inspection commands.*
+
+- =gloss-list-terms= — completing-read over every term in the cache. Pick one to jump to it.
+- =gloss-stats= — small buffer summarizing total terms, breakdown by =:source=, count of drill-tagged entries, file size, cache mtime.
+
+No metrics export, no telemetry, no profiling hooks — v3 territory if the package ever needs them.
+
+* Open Questions (will become ADRs)
+
+Each was decided during the brainstorm. Listed for traceability; each becomes an ADR in the gloss repo's =docs/decisions/=.
+
+- [ ] *ADR-1: storage path default* → =(expand-file-name "gloss.org" (or org-directory user-emacs-directory))=. Rationale: respects the user's existing =org-directory= convention; falls back gracefully.
+- [ ] *ADR-2: auto-fetch on local miss* → silent fall-through with graceful network-failure path. Rationale: y/n prompt is yes 99% of the time and an annoyance the other 1%; the offline case is better handled by detecting the failure than by pre-asking permission.
+- [ ] *ADR-3: drill direction* → =:DRILL_CARD_TYPE: twosided=. Rationale: tests both recognition and recall over time without doubling the deck.
+- [ ] *ADR-4: HTML strip strategy* → =libxml-parse-html-region= (plain text only, no italic/bold preservation). Rationale: more robust than regex on edge cases; libxml2 is standard on Linux/Mac; ~30 lines.
+
+* Next Steps
+
+1. *Scaffold the repo.* =~/code/gloss= with the claude-template structure: =.ai/= and =todo.org= and =inbox/= gitignored, =Makefile= for tests/lint/compile, =README.org= placeholder, =LICENSE=, package skeleton (=gloss.el= with package-header autoload entry).
+2. *Set up remotes.* Bare repo on cjennings.net at =/var/cjennings/git/gloss.git/= with the existing post-receive hook pattern that mirrors to =github.com/cjennings/gloss=.
+3. *Decompose into todo.org tasks.* One TODO per layer, in implementation order: core → fetch → display → drill → entry-point → integration tests → README. Each task carries its acceptance criteria from this design.
+4. *Implement v1 layer by layer*, TDD per project rules. Run =/start-work= once per task.
+5. *First-week shakedown.* Use the package on real terms for a week. File issues against any rough edges as v1.1 tasks.
+6. *Record the four ADRs* in =docs/decisions/= once the repo exists.
+
+* Status
+
+Draft. Pending: repo scaffold, ADR records, implementation.
diff --git a/gloss-core.el b/gloss-core.el
new file mode 100644
index 0000000..2e054c4
--- /dev/null
+++ b/gloss-core.el
@@ -0,0 +1,32 @@
+;;; gloss-core.el --- Data layer for gloss -*- lexical-binding: t -*-
+
+;; Copyright (C) 2026 Craig Jennings
+;; Author: Craig Jennings <c@cjennings.net>
+;; SPDX-License-Identifier: GPL-3.0-or-later
+
+;;; Commentary:
+
+;; Storage and lookup primitives for `gloss'. Owns the in-memory
+;; cache (a hash table keyed by term) and the org file I/O.
+;;
+;; Public API:
+;; `gloss-core-lookup' TERM -> entry plist or nil
+;; `gloss-core-save' TERM BODY SOURCE -> entry plist (saved)
+;; `gloss-core-list' -> (TERM ...)
+;; `gloss-core-find-buffer-position' TERM -> marker
+;;
+;; Entry plist shape:
+;; (:term "anaphora"
+;; :body "Reference to..."
+;; :source wiktionary
+;; :added "2026-04-28"
+;; :marker #<marker at N in gloss.org>)
+;;
+;; See `docs/design/gloss.org' for the full design.
+
+;;; Code:
+
+;; Implementation pending. Track via todo.org.
+
+(provide 'gloss-core)
+;;; gloss-core.el ends here
diff --git a/gloss-display.el b/gloss-display.el
new file mode 100644
index 0000000..c028698
--- /dev/null
+++ b/gloss-display.el
@@ -0,0 +1,29 @@
+;;; gloss-display.el --- Side-buffer UI for gloss -*- lexical-binding: t -*-
+
+;; Copyright (C) 2026 Craig Jennings
+;; Author: Craig Jennings <c@cjennings.net>
+;; SPDX-License-Identifier: GPL-3.0-or-later
+
+;;; Commentary:
+
+;; UI layer for `gloss'. Defines the side buffer's major mode and
+;; renders entries; also owns the picker shown when an online fetch
+;; returns multiple candidate definitions.
+;;
+;; Public API:
+;; `gloss-display-show-entry' TERM BODY
+;; `gloss-display-pick-definition' TERM DEFINITIONS -> chosen plist
+;;
+;; Pure helper (full N/B/E test coverage):
+;; `gloss-display--format-candidate' PLIST -> "[source] text..."
+;;
+;; `gloss-mode' is derived from `special-mode': `q' quits the window.
+;;
+;; See `docs/design/gloss.org' for the full design.
+
+;;; Code:
+
+;; Implementation pending. Track via todo.org.
+
+(provide 'gloss-display)
+;;; gloss-display.el ends here
diff --git a/gloss-drill.el b/gloss-drill.el
new file mode 100644
index 0000000..6771f4b
--- /dev/null
+++ b/gloss-drill.el
@@ -0,0 +1,29 @@
+;;; gloss-drill.el --- org-drill export for gloss -*- lexical-binding: t -*-
+
+;; Copyright (C) 2026 Craig Jennings
+;; Author: Craig Jennings <c@cjennings.net>
+;; SPDX-License-Identifier: GPL-3.0-or-later
+
+;;; Commentary:
+
+;; Spaced-repetition export for `gloss'. Walks the glossary org file
+;; via `org-element' and ensures every term entry carries a `:drill:'
+;; tag and a `:DRILL_CARD_TYPE: twosided' property — `org-drill' then
+;; runs unmodified against the file.
+;;
+;; Public API:
+;; `gloss-drill-export-all'
+;; `gloss-drill-untag-all'
+;;
+;; Idempotent: running export twice does not double-tag.
+;; Checks `(featurep 'org-drill)' before running; raises a helpful
+;; user-error if `org-drill' isn't installed.
+;;
+;; See `docs/design/gloss.org' for the full design.
+
+;;; Code:
+
+;; Implementation pending. Track via todo.org.
+
+(provide 'gloss-drill)
+;;; gloss-drill.el ends here
diff --git a/gloss-fetch.el b/gloss-fetch.el
new file mode 100644
index 0000000..e4477f2
--- /dev/null
+++ b/gloss-fetch.el
@@ -0,0 +1,35 @@
+;;; gloss-fetch.el --- Online definition fetcher for gloss -*- lexical-binding: t -*-
+
+;; Copyright (C) 2026 Craig Jennings
+;; Author: Craig Jennings <c@cjennings.net>
+;; SPDX-License-Identifier: GPL-3.0-or-later
+
+;;; Commentary:
+
+;; Network layer for `gloss'. Walks a registry of online sources
+;; (`gloss-fetch--sources') in the order specified by the user-facing
+;; `gloss-fetch-sources' defcustom; aggregates per-source results into
+;; a single response shape.
+;;
+;; Public API:
+;; `gloss-fetch-definitions' TERM
+;; -> (:ok DEFS) ; any source returned >=1 def
+;; | (:empty :no-defs (SYM ...) :failed (SYM ...))
+;;
+;; Each definition is a plist:
+;; (:source SYM :text "Reference to ...")
+;;
+;; Per-source internal status taxonomy:
+;; :ok :defs (...) :no-defs :unreachable :server-error :rate-limited
+;;
+;; libxml is treated as a precondition (probed once at first fetch);
+;; absent libxml disables online fetch package-wide for the session.
+;;
+;; See `docs/design/gloss.org' for the full design.
+
+;;; Code:
+
+;; Implementation pending. Track via todo.org.
+
+(provide 'gloss-fetch)
+;;; gloss-fetch.el ends here
diff --git a/gloss.el b/gloss.el
new file mode 100644
index 0000000..20aacb1
--- /dev/null
+++ b/gloss.el
@@ -0,0 +1,155 @@
+;;; gloss.el --- Glossary lookup with online-sourced selection -*- lexical-binding: t -*-
+
+;; Copyright (C) 2026 Craig Jennings
+
+;; Author: Craig Jennings <c@cjennings.net>
+;; Created: 28 Apr 2026
+;; Version: 0.1.0
+;; Package-Requires: ((emacs "27.1") (org "9.3"))
+;; Keywords: glossary dictionary terms vocabulary
+;; URL: https://github.com/cjennings/gloss
+
+;; This program is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+;;
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; gloss — Glossary Lookup with Online-Sourced Selection.
+;;
+;; A personal Emacs glossary on `C-h g'. Looks up terms in a single
+;; git-tracked org file. On a local miss, fetches candidate
+;; definitions from Wiktionary and prompts the user to pick one to
+;; save with provenance. The same org file feeds `org-drill' for
+;; spaced-repetition study.
+;;
+;; Quick start:
+;; (require 'gloss)
+;; (gloss-install-prefix) ; binds C-h g
+;;
+;; Default keys under C-h g:
+;; g gloss-lookup lookup term (default: word at point)
+;; a gloss-add add term manually
+;; e gloss-edit edit term in source file
+;; o gloss-fetch-online force online fetch
+;; D gloss-drill-export tag entries for org-drill
+;; l gloss-list-terms browse glossary
+;; s gloss-stats summary
+;; r gloss-reload refresh cache
+;; d gloss-toggle-debug toggle *gloss-debug*
+;;
+;; See `docs/design/gloss.org' for the full design.
+
+;;; Code:
+
+(require 'gloss-core)
+(require 'gloss-fetch)
+(require 'gloss-display)
+(require 'gloss-drill)
+
+(defgroup gloss nil
+ "Personal glossary with online-sourced definitions."
+ :group 'tools
+ :prefix "gloss-")
+
+(defcustom gloss-file
+ (expand-file-name "gloss.org" (or (bound-and-true-p org-directory)
+ user-emacs-directory))
+ "Path to the glossary org file."
+ :type 'file
+ :group 'gloss)
+
+(defcustom gloss-debug nil
+ "When non-nil, write diagnostic events to *gloss-debug*."
+ :type 'boolean
+ :group 'gloss)
+
+(defvar gloss-prefix-map (make-sparse-keymap)
+ "Keymap for `gloss' commands. Default prefix: C-h g.")
+
+;;;###autoload
+(defun gloss-lookup (term)
+ "Look up TERM in the glossary; fetch online on miss."
+ (interactive (list (read-string "Glossary lookup: " (thing-at-point 'word t))))
+ (ignore term)
+ (user-error "gloss-lookup: not yet implemented"))
+
+;;;###autoload
+(defun gloss-add (term)
+ "Add TERM to the glossary manually."
+ (interactive (list (read-string "Add term: ")))
+ (ignore term)
+ (user-error "gloss-add: not yet implemented"))
+
+;;;###autoload
+(defun gloss-edit (term)
+ "Open the source org file at TERM's heading."
+ (interactive (list (read-string "Edit term: ")))
+ (ignore term)
+ (user-error "gloss-edit: not yet implemented"))
+
+;;;###autoload
+(defun gloss-fetch-online (term)
+ "Force online fetch for TERM, bypassing the cache."
+ (interactive (list (read-string "Fetch online: ")))
+ (ignore term)
+ (user-error "gloss-fetch-online: not yet implemented"))
+
+;;;###autoload
+(defun gloss-drill-export ()
+ "Tag every entry as :drill: for `org-drill'."
+ (interactive)
+ (user-error "gloss-drill-export: not yet implemented"))
+
+;;;###autoload
+(defun gloss-list-terms ()
+ "Browse glossary terms via `completing-read'."
+ (interactive)
+ (user-error "gloss-list-terms: not yet implemented"))
+
+;;;###autoload
+(defun gloss-stats ()
+ "Summarize the glossary state."
+ (interactive)
+ (user-error "gloss-stats: not yet implemented"))
+
+;;;###autoload
+(defun gloss-reload ()
+ "Force reload of the glossary cache from disk."
+ (interactive)
+ (user-error "gloss-reload: not yet implemented"))
+
+;;;###autoload
+(defun gloss-toggle-debug ()
+ "Toggle the *gloss-debug* log on or off."
+ (interactive)
+ (setq gloss-debug (not gloss-debug))
+ (message "gloss-debug %s" (if gloss-debug "enabled" "disabled")))
+
+(define-key gloss-prefix-map (kbd "g") #'gloss-lookup)
+(define-key gloss-prefix-map (kbd "a") #'gloss-add)
+(define-key gloss-prefix-map (kbd "e") #'gloss-edit)
+(define-key gloss-prefix-map (kbd "o") #'gloss-fetch-online)
+(define-key gloss-prefix-map (kbd "D") #'gloss-drill-export)
+(define-key gloss-prefix-map (kbd "l") #'gloss-list-terms)
+(define-key gloss-prefix-map (kbd "s") #'gloss-stats)
+(define-key gloss-prefix-map (kbd "r") #'gloss-reload)
+(define-key gloss-prefix-map (kbd "d") #'gloss-toggle-debug)
+
+;;;###autoload
+(defun gloss-install-prefix (&optional key)
+ "Install `gloss-prefix-map' on KEY (default \\`g' under `help-map', i.e. C-h g)."
+ (interactive)
+ (define-key help-map (or key (kbd "g")) gloss-prefix-map))
+
+(provide 'gloss)
+;;; gloss.el ends here
diff --git a/tests/fixtures/.gitkeep b/tests/fixtures/.gitkeep
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/tests/fixtures/.gitkeep