# Architecture decision records Format: one section per ADR. Status: Proposed · Accepted · Superseded by ADR-n. Add new ADRs at the end with `/adr `. --- ## ADR-001 — Ollama `/api/chat` as the translation backend Status: Accepted Context: The product's core value is local, private translation. Hy-MT3 is available as an official Tencent GGUF and runs in Ollama. Ollama's native chat endpoint applies the model's chat template, streams NDJSON and exposes `done_reason` and timing metrics. The model is text-only and has no thinking mode. Decision: Use Ollama over HTTP with `POST /api/chat`, one user message, `stream: true`. Do not embed MLX, llama.cpp or Core ML. Do not use the OpenAI-compatible endpoint in v1, because the native endpoint exposes the template, `keep_alive` and metrics directly. Consequences: The user must install Ollama and pull a model, so onboarding must handle this. The app stays small and redistributes no weights. Another backend would need a second client behind the same protocol. ## ADR-002 — Hy-MT3's documented default prompt, with a stable prefix Status: Accepted Context: Hy-MT3 ships with documented prompt templates. Ad-hoc prompting changes behaviour unpredictably. Ollama reuses the prompt prefix cache; a dynamic prefix makes every request cold. Decision: The default prompt is Tencent's English **Default Translation** template, byte for byte, with the exact model language name and the source text appended. The prefix depends only on the target language. No system message, no source-language field, no timestamps, no app name. Prompt strings live only in `SprachmittlerEngines`. Consequences: Byte-exact golden tests are mandatory. Changing the prompt requires an ADR and a new adapter version. The measured 177/178 cached prompt tokens are preserved. ## ADR-003 — Non-sandboxed app; Accessibility optional Status: Accepted Context: Replacing another app's selection requires Accessibility trust, which App Sandbox does not allow for this use. The core flow (double copy, translate, Copy, Services) needs no permission. Decision: Ship without App Sandbox, with Hardened Runtime and Developer ID + notarisation. Request Accessibility only when the user clicks Replace, or from onboarding if they choose to enable it. No Mac App Store in v1. Consequences: Wider capability, and with it more responsibility: SECURITY_PRIVACY.md invariants are mandatory and checked in `make verify`. A future sandboxed "Services-only, copy-only" edition remains possible. ## ADR-004 — Double copy detected through the pasteboard, not a key tap Status: Accepted Context: A global ⌘C key tap needs Input Monitoring or Accessibility and widens permissions. DeepL-style double copy can be detected from `NSPasteboard.changeCount` without any permission. Decision: Poll `NSPasteboard.general.changeCount` every 120 ms on the main actor. A trigger is two changes within 500 ms (300–1000 configurable) whose string values are identical and non-empty. Read the string only after a change. Ignore our own writes and transient/concealed pasteboard items. Keep at most the last two strings in memory. Consequences: No Input Monitoring. False positives are bounded by the identical-text rule. The app must document that copying two different things quickly does not trigger. Polling costs less than 0.5% CPU at 120 ms. ## ADR-005 — Explicit Replace only; Accessibility first, paste fallback Status: Accepted Context: Automatic replacement is destructive and surprising. A synthetic ⌘V mutates the user's clipboard; AX direct replacement avoids that but is not supported everywhere. Decision: The panel never replaces or copies automatically. **Replace** is an explicit button in the lower right. It tries AX direct replacement first (verify the selected text still matches), then a synthetic ⌘V with a full clipboard snapshot/restore. It aborts if the source app is no longer frontmost or the selection changed. Blocking warnings disable Replace by default. Consequences: Replace works in more apps, and the clipboard is preserved. Some Electron/canvas apps still fail; they get a clear Copy fallback. Replacement is one undoable operation in apps that support undo, which is documented as app-dependent. ## ADR-006 — XcodeGen + SwiftPM package for agent-friendly development Status: Accepted Context: Coding agents edit `.pbxproj` files unreliably. Decision: All logic lives in a SwiftPM package (`swift build` / `swift test` from the CLI). The app target is defined in `project.yml` and generated with XcodeGen. `.xcodeproj` is git-ignored and denied to agent edits in `opencode.json`. Consequences: Agents can build and test without the Xcode UI. Adding files needs no project edits. ## ADR-007 — No history and no persistence of text Status: Accepted Context: Selected text is often confidential. A translation history is a privacy liability and a sync/backup risk. Decision: Source text, translations, pasteboard snapshots and app names are never written to disk. Settings contain only configuration. The last translation may stay in memory for the panel's Copy/Replace actions and is released when the panel closes or the app quits. No analytics, no crash-reporting SDK, no accounts. Consequences: The user cannot look up an old translation after closing the panel; that is the intended trade-off. A future opt-in history needs an ADR, explicit consent and encrypted storage. ## ADR-008 — Default model chosen by evaluation Status: Proposed (T7.5 blocked on the private corpus and the 1.8B comparison) Context: Publisher benchmarks do not cover the user's texts, and 7B vs 1.8B is a quality/latency trade-off. The 7B is the owner's requested default, but the 1.8B may be better on smaller Macs. Decision: Ship with `hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M` as the provisional default and the 1.8B Q4_K_M as the Fast preset. Decide the default, the sampling temperature and the prompt policy with `sprachmittler-cli eval` on the user's corpus using the rule in `docs/MODEL_EVALUATION.md` §5. Record the outcome as a new ADR. Consequences: Until the gate, the 7B is labelled provisional in Settings. The decision is re-run when a model, Ollama or the prompt policy changes. ## ADR-009 — Menu-bar agent with a non-activating panel Status: Accepted (amended 2026-11-26: Esc without a click) Context: The app must be available over any app and must not activate itself or take application focus from the selection. A regular Dock app with a window would interrupt the workflow. Users also expect Esc to dismiss a transient panel immediately, which requires the panel to be the key window. Decision: Use `LSUIElement = YES`, a `MenuBarExtra`, and a floating `NSPanel` with `.nonactivatingPanel` and `becomesKeyOnlyIfNeeded = false`. Never call `NSApp.activate` or `makeKeyAndOrderFront` for the translation panel. Onboarding and Settings are the only surfaces that activate the app. By default the panel calls `makeKey()` when shown, so Esc and the keyboard shortcuts work immediately; the setting `closeWithEscape` can restore click-first behaviour. The panel's SwiftUI exit command handles Esc and calls the same close path that cancels an in-flight request. Consequences: The app stays unactivated: `NSWorkspace.frontmostApplication` and the menu bar stay with the source app, and Replace still re-verifies that app. While the panel is visible it holds keyboard focus, so keystrokes and shortcuts go to the panel until the user clicks back into the source app; the setting turns this off. A click outside the panel dismisses it: the panel observes `didResignKey` and, while visible, a transient global mouse-down monitor. Global monitors do not receive events sent to this app, so clicks in the panel and its popover are ignored; the event is discarded and the monitor is removed on close. The monitor is not a key tap and needs no Input Monitoring. Every action still has a button. ## ADR-010 — Native OpenCode 2.x configuration Status: Accepted Context: The kit targets OpenCode 2.x. V2 still accepts V1 configuration, but native V2 uses an ordered `permissions` list with `action`/`resource`/`effect` rules (last match wins), `shell` instead of `bash`, `subagent` instead of `task`, and V2 agent fields. In V2, access to external directories is allowed by default, and agent `temperature` is no longer sent. Decision: Use native V2 only: `opencode.json` with `$schema`, `instructions` and `permissions`; agents in `.opencode/agents/` with V2 frontmatter (`description`, `mode`, `steps`, `permissions`) and no `temperature`; commands in `.opencode/commands/`; skills in `.opencode/skills/<id>/SKILL.md`. Restore `external_directory: ask` explicitly. Check with `make doctor`. Consequences: No mixed V1/V2 files. Sampling settings for agents, if wanted, go on a model variant in the user's global config. ## ADR-011 — Chunk at paragraph boundaries with script-aware limits Status: Accepted Context: Hy-MT3's documented translation context is 8192 tokens. A long selection can exceed it; splitting mid-sentence harms quality; splitting mid-grapheme corrupts text. The capture gate and the chunk size were the same number, so selections over one chunk were rejected before the pipeline could split them. Decision: Chunk at blank-line paragraph boundaries first, then sentence, then word. Use 4000 characters per part for Latin/Cyrillic/Greek and 2000 for CJK and other dense scripts. Never split a grapheme cluster. Reassemble with the original separators. Translate parts sequentially with one request in flight. The capture limit is the part size multiplied by `maximumPartsPerSelection` (1–8, default 1); `1` rejects anything over one part, and higher values accept the selection and translate it in parts. The dense-script part size is capped at 4000 because 5000 dense characters plus a 4096-token output can overflow the context. Consequences: Default behaviour is unchanged (one part). Users who opt into parts trade latency for reach: every extra part is another sequential request, and the panel shows “Part 2 of 4” while streaming and “3 parts” when finished. Very long selections lose some cross-paragraph context; the panel keeps the streamed partial text and disables Replace when a part fails. `done_reason: "length"` is always a warning. ## ADR-012 — Only documented prompt variants; no free-form prompts Status: Accepted Context: The model card documents Default, Terminology, Style, Personalization, Delimiters, Structured Data 1/2 and Background Information templates. Text with Markdown, JSON, URLs or placeholders may benefit from a structured template. Decision: v1 uses the Default Translation template for everything. The Structured Data 1, Delimiters, Terminology and Style templates are the only allowed alternatives, selected by a deterministic content policy or as a documented fallback after validation. No other prompt text is allowed. The user cannot type a prompt in v1. Consequences: Predictable behaviour and a small attack surface. A future glossary or style feature uses the existing documented templates, not new instructions. ## ADR-013 — Validation gates Replace, never rewrites output Status: Accepted Context: Translation models occasionally add an explanation, truncate, loop or drop a URL/placeholder. Silently "fixing" the output hides errors and can corrupt meaning. Decision: Show the model output after only T1 (outer whitespace/line endings). Detect preamble, truncation, repetition, empty output, lost protected tokens and numeric mismatch. Retry once with the documented Delimiters prompt only when a protected token is lost. Blocking warnings disable Replace by default; Copy remains available. Never strip a preamble or edit the wording automatically. Consequences: The user sees the truth and decides. Some outputs need manual cleanup; that is preferable to silent damage. ## ADR-014 — Model language names come from the model card; English prompts are canonical Status: Accepted Context: Hy-MT3 expects full language names, with Chinese names in Chinese prompts and English names in English prompts. The table has variants such as `Chinese` vs `Traditional Chinese`, `Norwegian` vs `Norwegian Nynorsk`, `Arabic Kazakh` vs `Cyrillic Kazakh`. Decision: Store the exact model-card English name with every `TargetLanguage`. Build prompts in English regardless of the UI language. Localise display names separately with `Locale`, but never feed a localised name into the prompt. Unknown BCP-47 codes are not silently mapped; the UI offers the supported list. Consequences: The prompt stays stable across UI languages and matches the model's training data. Adding a language requires updating `LANGUAGES.md`, the catalogue and a test. ## ADR-015 — One translation in flight; epochs discard stale results Status: Accepted Context: The user may double-copy again, change the target language or close the panel while a request is streaming. Two overlapping streams would confuse the panel and waste compute. Decision: `TranslationSession` is an actor with one active request. A new trigger or target change increments an epoch and cancels the previous URL task. Events from an older epoch are discarded. Chunks are translated sequentially. Copy does not change the session; Replace only runs from a `.ready` state with no blocking warnings. Consequences: Fast, predictable updates and no orphaned requests. The previous translation is lost when the user triggers a new one; that is intentional and avoids history. ## ADR-016 — Provisional M1 Engines slice for the CLI Status: Superseded by ADR-017 Context: T1.6 needs the documented Default prompt and the exact model language name before T2.2/T2.3 exist. Putting either in the CLI target would violate documented-prompts-only and the lint rule that prompt and language literals live in `SprachmittlerEngines`. Decision: Add a provisional `ModelLanguage` with the 15 common targets from `LANGUAGES.md` §5, the byte-exact Default Translation prompt, the documented sampling values and `HyMT3RequestFactory` in `SprachmittlerEngines`. T2.3 replaces the table with all 102 languages; T2.1/T2.2 replace the factory with `TranslationAdapter`/`HyMT3Adapter`. Consequences: The M1 CLI translates en→de and the other common targets without a free-form prompt. Unknown codes fail before the network. Only 15 targets resolve until T2.3, and no prompt literal or model tag appears outside Engines. ## ADR-017 — Adapter registry in Engines; one pipeline in Core Status: Accepted Context: M1 needed a prompt and a request factory for the CLI before the model-family adapter existed. T2.1/T2.2 replace that factory, and both the CLI and the future panel must use the same chunking, validation and retry rules. Prompt strings must stay in `SprachmittlerEngines`; validation results must be visible to Core and the UI. Decision: `TranslationAdapter` and `AdapterRegistry` live in `SprachmittlerEngines`. An `AdapterRequest` carries text, target, model, keep-alive, prompt variant and sampling. `HyMT3Adapter` is the only family adapter in v1; it sets the publisher sampling, `num_ctx: 8192`, exactly one user message and no system/think field. `TranslationWarning` and `ModelLanguage` (re-exported as `TargetLanguage`) also live in Engines, and `LanguageMatching` owns the canonical-code comparison. `TranslationPipeline` in `SprachmittlerCore` does normalisation, detection, classification, chunking, one documented retry after a lost protected token, validation and timing; the keep-alive value is supplied by the composition root. Core re-exports the warning and language types. Consequences: The CLI and M4 session share one implementation. Prompt bytes and language names have one home. Adapter selection is explicit and unknown families fail with `noAdapter`. The M1 `HyMT3RequestFactory` and its 15-language table are removed. A second model family adds an adapter, not a branch in Core. ## ADR-018 — Capture behind a pasteboard protocol; Services is a first-class trigger Status: Accepted Context: Double copy, clipboard snapshot/restore and Services all touch `NSPasteboard`, but the state machine and watcher need deterministic tests without real time or the user's clipboard. The Services path must work with no Accessibility permission. Decision: `SprachmittlerCapture` defines `PasteboardAccessing` and `PasteboardTicking`. `SystemPasteboard` is the only production `NSPasteboard` user; `FakePasteboard` and `ManualPasteboardTicker` live in `SprachmittlerTestSupport`. `DoubleCopyDetector` is a pure state machine over change events and an injected date. `PasteboardWatcher` polls every 120 ms, reads the string only after `changeCount` changes, suppresses own/transient changes for 750 ms, and enforces the 4000/2000 limit. `ServicesProvider` receives the system pasteboard and needs no polling or Accessibility. `AppDelegate` installs it and calls `NSUpdateDynamicServices`. Consequences: Capture logic is unit-testable and no global key tap is needed. The Services and double-copy paths both produce `CapturedText`. The 10-app compatibility matrix remains a manual task. ## ADR-019 — AX first, paste fallback, target re-verified at Replace Status: Accepted Context: Replace must be safe and reversible, but Accessibility support differs by app. AX calls can block, so they must stay off the main actor. Tests need deterministic insertion without a real app or clipboard. Decision: `InsertionCoordinator` lives in `SprachmittlerCapture` and uses `AccessibilityTextEditing` and `EventPosting` seams. At trigger time the app captures the frontmost PID/bundle and, when trusted, reads only the focused selection; at Replace it re-verifies the frontmost app and the selected text (`InsertionPolicy`). It refuses secure fields and its own PID. AX direct replacement is tried first; if unsupported, it snapshots the clipboard, writes the translation with own/transient markers, posts ⌘V to the target PID, waits up to 300 ms and restores only when `changeCount` still matches the write. Blocking warnings disable Replace; failures keep the panel open and offer Copy. Consequences: Most apps use the no-clipboard AX path; the fallback preserves the previous clipboard in the common case. Manual testing is still required because AX support and paste delivery are app-specific. ## ADR-020 — UI state models in Core, AppKit controllers in App Status: Accepted Context: Panel, Settings, Onboarding and Diagnostics contain branching worth testing, but their windows are AppKit/SwiftUI. The app target must stay thin. Decision: `PanelViewModel`, `SettingsViewModel`, `OnboardingViewModel` and `DiagnosticsViewModel` are `@MainActor @Observable` types in `SprachmittlerCore`; `SettingsStore` uses a `SettingsDataStoring` seam. `App` owns only `NSPanel`/`NSWindow` controllers, SwiftUI views, the composition root (`AppEnvironment`) and lifecycle glue. `TranslationSession` uses an injected pipeline factory so endpoint/settings changes apply on the next request without rebuilding the UI. Consequences: Logic is covered by package tests; AppKit remains untested by `make verify` and requires the manual checklist. ## ADR-021 — Markdown is rendered as presentation only Status: Accepted Context: Hy-MT3 preserves Markdown structure, but a plain `Text` showed `**bold**`, headings and lists literally. Users translating Markdown want the formatting rendered, while Copy and Replace must keep the Markdown that the model produced and the validator checked. Decision: Parse presentation Markdown in `SprachmittlerText` with Foundation's inline Markdown parser plus a small, conservative block parser (headings, lists, quotes, fenced code, rules, paragraphs). `MarkdownPresentation.shouldRender` rejects JSON, HTML and code sources and otherwise requires block or inline Markdown markers. The panel renders only when the setting `renderMarkdown` is on (default). Copy and Replace use the raw translation unchanged. Only `http` and `https` links open, on an explicit click; image syntax is reduced to alt text and no remote resource is fetched. Tables, raw HTML and nested lists/quotes remain plain text in this pass. Consequences: Rendering never rewrites the translation or weakens validation. Literal markers can be interpreted as formatting, so the setting is the escape hatch; Copy always returns the raw Markdown. The block layout makes text selection per block, while Copy remains the whole-translation path. No new dependency is added. ## ADR-022 — Language routing: mother tongue plus source-to-target rules Status: Accepted Context: A single target language is a good default, but users who work in several languages need different targets for different sources: German text to English, Chinese text to English, French text to German, and everything else to the mother tongue. The earlier single fallback only covered source-equals-target. Decision: Keep the saved target as the **mother tongue** and the default target for every source. Add `languageRoutes`, an ordered, source-unique list of `source → target` rules; the default list is empty. Before a request, detect the source and apply the first rule whose source is confidently detected; otherwise use the mother tongue. The saved and effective targets are separate: the header and language picker show the effective target, a banner explains a rule-driven direction and offers a one-capture override back to the mother tongue, and the panel picker is a session-only override. Persistent rules are edited in Settings. Same-language rules are dropped and sources are deduplicated. The source detector ignores near-zero hypotheses so the high-confidence rule is meaningful. Consequences: The default is "every language → mother tongue". Rules are explicit, arbitrary and can be added later (for example Chinese → English or Traditional Chinese → English) without code changes. Confident detections route automatically; short, mixed or uncertain text stays on the mother tongue. The mother tongue is unchanged by routing, and the panel override never rewrites the rules. Detection is advisory, so a wrong dominant language can select the wrong rule; the banner and picker make it visible and recoverable. No key tap, permission, network access or new dependency is added.