Files
Sprachmittler-Kit/docs/IMPLEMENTATION_PLAN.md

122 lines
13 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Implementation plan
Work milestone by milestone, task by task. Each task is sized for one OpenCode session, about 100–400 lines of change. A task is done only when its acceptance criteria pass **and** `make verify` is green. Track status in `docs/PROGRESS.md`.
Conventions: `T<milestone>.<n>`. "AC" = acceptance criteria. "Req" = requirement IDs from `docs/PRD.md` (R001–R050). Every requirement appears in at least one task.
---
## M0 — Scaffold and tooling
Goal: an empty but correctly configured project that builds, tests and launches as a menu-bar app, with OpenCode 2.x configured.
| Task | Description | AC | Req |
|---|---|---|---|
| T0.1 | The kit ships `Packages/SprachmittlerKit/Package.swift` with placeholder sources, tests and synthetic fixtures. Verify it resolves and builds; replace placeholder enums as modules gain real types. | `swift build --package-path Packages/SprachmittlerKit` and `make test` succeed; fixture-loading test passes. | R048 |
| T0.2 | Complete the `App/` sources (stubs shipped): `SprachmittlerApp` with a `MenuBarExtra`, `Settings` scene and quit item; `Info.plist` (`LSUIElement`, `NSServices`, ATS local networking); non-sandboxed entitlements. | `make app` builds; the menu-bar icon appears and no Dock icon is shown; `codesign -d --entitlements -` shows exactly `app-sandbox = false`. | R021, R041, R049 |
| T0.3 | Validate the shipped `project.yml` and `make generate`; set your own bundle ID prefix. | `xcodegen generate` produces a project that builds in Xcode and via `xcodebuild`. | R049 |
| T0.4 | Run the shipped `scripts/verify.sh`, `.swiftformat`, `.swiftlint.yml`; fix issues so the gate is green on the scaffold. Add `os.Logger` categories and an `OSSignposter` wrapper in `SprachmittlerCore`. | `make verify` runs end-to-end; logging helper used in a test. | R033, R050 |
| T0.5 | Run `make doctor`: OpenCode 2.x installed, `opencode.json` parses as native V2, agents/commands/skills discovered, `opencode debug config` shows the permission rules. | `make doctor` green; `/status` works in OpenCode. | R048 |
| T0.6 | Record the environment in `docs/PROGRESS.md`: OpenCode, Ollama, model digest, Mac chip/memory, Xcode/Swift, macOS. Run `make smoke`. | Environment table filled; smoke output recorded. | R013, R047 |
## M1 — Ollama text client
Goal: talk to Ollama, discover Hy-MT3 models and stream a translation headlessly.
| Task | Description | AC | Req |
|---|---|---|---|
| T1.1 | Run `scripts/capture-fixtures.sh` against a local Ollama with the 7B model; commit `SprachmittlerOllamaTests/Fixtures/*`. Resolve VERIFY items in `docs/OLLAMA_TRANSLATION_API.md` and record the digest. | Fixtures exist and are < 200 KB each; doc updated with "Verified against". | R009, R047 |
| T1.2 | `OllamaHTTPClient`: base URL, JSON encode/decode, ephemeral session, redirect refusal, error body parsing, `EndpointPolicy` (SP-5, SP-6). | `EndpointPolicyTests`, `RedirectRefusalTests`, `ErrorMappingTests` green. | R035, R048 |
| T1.3 | `OllamaCatalog`: `/api/version`, `/api/tags`, `/api/show` (capabilities, parameters, template), `/api/ps`; per-digest cache with refresh; version comparison. | Tests: model filter, `name:latest` normalisation, parameter parsing, minimum-version check. | R013, R016 |
| T1.4 | `OllamaChatClient`: streaming NDJSON over `URLSession.bytes`, partial-line carry, `ChatEvent` deltas and done metrics, phase timeouts with injected clock, cancellation propagation, mid-stream error lines. | `URLProtocol` stub tests: split lines, `done_reason` `stop` and `length`, idle timeout, first-token timeout, cancel mid-stream cancels the task. | R009, R019 |
| T1.5 | Warm-up and keep-alive: fixed synthetic sentence, `num_predict: 8`, discard; `keep_alive` from settings; optional unload. | Warm-up never uses user text; request shape tested; local-only rule. | R015, R050 |
| T1.6 | `sprachmittler-cli models`, `show <tag>`, `translate --text/--file --target --model [--json]`. | Prints installed Hy-MT3 models and capabilities; translates a fixture; exit code 3 when Ollama is unreachable. | R046 |
## M2 — Hy-MT3 adapter and text pipeline
Goal: one request shape per model family, documented prompts only, proven against the real model.
| Task | Description | AC | Req |
|---|---|---|---|
| T2.1 | `TranslationAdapter` protocol, `AdapterRegistry`, `SamplingOptions` merge, request encoding. Prompt-literal lint rule active. | Registry tests: Hy-MT3 tag matching, unknown model → no adapter, correct option names. | R010, R013, R014, R015 |
| T2.2 | `HyMT3Adapter`: default prompt byte-exact, 7B/1.8B tags, `num_ctx` 8192, publisher sampling, no system prompt, no `think`. | Golden-file prompt tests; request-encoding tests; no reasoning text stored. | R010, R011, R012, R013, R014, R015 |
| T2.3 | Language catalogue: 102 languages, BCP-47 mapping, exact model English names, localised display names, RTL/script notes. | Catalogue tests: all 102 entries; variants (`zh`/`zh-Hant`, `pt`/`pt-BR`, `nb`/`nn`, `kk`/`kk-Cyrl`, `mn`/`mn-Cyrl`, `ku`/`ckb`); unknown code errors. | R012, R045 |
| T2.4 | `LanguageDetector` (NaturalLanguage) and `Chunker` with script-aware limits and exact join. | Tests: EN/DE detection; paragraph boundaries; CJK limit; no grapheme split; join round-trip. | R016, R017 |
| T2.5 | `ProtectedTokenScanner` (URLs, e-mails, placeholders, code spans, HTML tags, JSON keys) and `OutputValidator` (missing token, preamble, truncation, repetition, numeric mismatch). | Tests: all token kinds; false-positive controls; preamble heuristics; repetition loop cancels. | R018, R019, R020 |
| T2.6 | Prompt policy: default for v1; documented Structured Data 1 and Delimiters fallbacks; one retry when a protected token is lost. | Policy tests: content class → prompt; fallback only on validation failure; no free-form prompt. | R010, R018 |
| T2.7 | **Compatibility spike**: `sprachmittler-cli translate` on EN→DE, DE→EN, Markdown, JSON, URL/placeholder text and a long paragraph. Record quality, timing and prompt-cache behaviour in `docs/HYMT3_MODEL.md` §7. | Table complete; any failure documented with the reason; user confirms before M3. | R009, R010, R018, R047 |
## M3 — Double-copy capture
Goal: turn the ⌘C+C gesture into a reliable `CapturedText` without extra permissions.
| Task | Description | AC | Req |
|---|---|---|---|
| T3.1 | `DoubleCopyDetector`: pure state machine over change events and a clock; 500 ms window, identical text, reset rules. | Tests: two copies, slow copies, different text, empty text, new trigger replaces. | R001, R002, R004 |
| T3.2 | `PasteboardWatcher`: 120 ms main-actor poll, read only on change, own-write suppression, last-two-strings memory, clear on session end. | Component tests with a fake pasteboard; no polling leaks; own writes ignored. | R001, R003, R008 |
| T3.3 | `ClipboardSnapshot`: snapshot all items/types, force lazy data, restore only if `changeCount` unchanged, transient/concealed markers. | Tests: rich text, image, multiple items, changed-by-another-app, restore failure. | R027, R037 |
| T3.4 | Services provider and menu-bar "Translate clipboard text". | Services menu item appears; same panel flow; no AX needed. | R006, R007 |
| T3.5 | **Manual compatibility matrix**: double copy in 10 apps, clipboard managers, empty selection, Universal Clipboard. | Matrix filled in `docs/SELECTION_AND_CLIPBOARD.md`; failures have tasks. | R048 |
## M4 — Translation session and panel
Goal: the DeepL-like panel, without focus theft and without automatic insertion.
| Task | Description | AC | Req |
|---|---|---|---|
| T4.1 | `TranslationSession` actor: one in flight, epochs, cancel/replace, streaming events, chunk orchestration. | Tests: new trigger cancels old; late events dropped; chunk failure surfaces; no second request. | R009, R017, R022 |
| T4.2 | `PanelController` (`NSPanel`, `.nonactivatingPanel`) and `PanelViewModel` (`@MainActor @Observable`). | Manual: source app keeps focus; panel appears near the mouse and is clamped to the screen. | R021 |
| T4.3 | Panel view: header, source preview, streaming translation, warnings, Copy (left), **Replace** (right, primary), Retry, Settings. | Manual: streaming, Copy, disabled Replace while translating, warning styling. | R022, R023, R024, R030 |
| T4.4 | Target language picker (searchable), recent languages, persistence, same-language warning and "Translate anyway". | Tests: persistence, same-language; manual: switch retranslates. | R005, R012, R020 |
| T4.5 | Error taxonomy and recovery actions for every case; no raw `localizedDescription`. | Exhaustive switch test; manual with Ollama stopped, model missing, text too long. | R019, R039 |
| T4.6 | Panel keyboard and accessibility: Esc, ⌘C, ⌘↩, ⌘R, ⌘,; labels; VoiceOver order. | Manual checklist; no focus steal. | R029, R043 |
## M5 — Replace
Goal: explicit, safe replacement of the selected text.
| Task | Description | AC | Req |
|---|---|---|---|
| T5.1 | `InsertionCoordinator` and `InsertionTarget` (PID, app name, AX element, selected text/range). Capture at trigger time when trusted. | Tests: target captured, frontmost check, stale target rejected. | R025, R026 |
| T5.2 | Accessibility trust check, focused element, direct `kAXSelectedTextAttribute` replacement. | Tests with fakes; manual in TextEdit, Notes, Safari, Mail. | R025, R031 |
| T5.3 | Synthetic-paste fallback: set clipboard, `CGEvent.postToPid` ⌘V, wait, restore snapshot, suppression window. | Tests with fake poster; manual clipboard restoration in 10 apps. | R025, R027 |
| T5.4 | Safety: verify selected text unchanged, never insert in secure fields, block on blocking warnings, Copy fallback. | Tests: changed selection, wrong app, preamble, token loss; manual. | R026, R028, R030 |
| T5.5 | **Manual insertion matrix** and permission onboarding: Accessibility denied, granted, revoked while running, app update. | Matrix filled; top failures have tasks. | R031, R039, R048 |
## M6 — Settings, onboarding, menu bar
Goal: a finished app shell that a person can set up and use.
| Task | Description | AC | Req |
|---|---|---|---|
| T6.1 | `AppSettings` (versioned, defaults, migration, reset) and `SettingsStore` over `UserDefaults`; no text fields. | Migration test from a v0 fixture; unknown keys ignored; reset restores defaults. | R040 |
| T6.2 | Onboarding: Ollama reachable + version, Hy-MT3 installed, target language, optional Accessibility; fix buttons. | Manual with Ollama stopped, model missing, AX denied; reopen from menu. | R039 |
| T6.3 | Settings UI: General, Model, Translation, Privacy, Diagnostics; endpoint input validated; licence/digest shown. | Invalid remote configurations blocked; no text stored; manual. | R035, R040, R042 |
| T6.4 | Status menu, launch at login (`SMAppService`), diagnostics window, About/licences. | Manual: menu actions, login item state, diagnostics has no text. | R041, R042, R044 |
| T6.5 | **Integration checkpoint**: double copy → panel → Copy/Replace end-to-end in 10 apps; verify no auto-insert and clipboard restoration. | User confirms before M7. | R001–R030, R048 |
## M7 — Evaluation and the default-model gate
Goal: decide the default model, sampling and prompt policy with data.
| Task | Description | AC | Req |
|---|---|---|---|
| T7.1 | Corpus manifest decoding and validation against `evaluation/corpus.schema.json`; `sprachmittler-cli eval --manifest --models --target --out`; cold/warm runs. | Validation errors are precise; eval runs on a synthetic manifest with a fake transport. | R046, R047 |
| T7.2 | Metrics: chrF, BLEU, protected-token retention, numeric consistency, sentence/paragraph count, failure rate, first-token/total latency, memory from `/api/ps`. | Unit tests with hand-computed values. | R047 |
| T7.3 | Report writer (`report.md`, `report.json`) with environment block, per-category tables, limitations. | Golden-file test; records digests, server version, hardware, settings. | R047 |
| T7.4 | **Evaluation run**: 7B vs 1.8B, temperature 0.7 vs 0.2, default vs structured prompt on the user's corpus; 3 runs at temperature 0.7. | Report produced; user reviews. | R013, R014, R047 |
| T7.5 | **Default-model gate**: draft ADR "Default model and sampling"; user decides; update presets, docs and settings. | ADR accepted with numbers; `HYMT3_MODEL.md`, `ARCHITECTURE.md` §12 and `PERFORMANCE.md` updated. | R013, R014, R047 |
## M8 — Hardening and release
Goal: private, accessible, measured and shippable.
| Task | Description | AC | Req |
|---|---|---|---|
| T8.1 | Privacy audit: extend `scripts/privacy-check.sh` for SP-1…SP-15; add a self-test that plants one violation per rule; review Console during a full session. | `make verify` fails on seeded violations; Console shows no text, translations or app names. | R031–R038 |
| T8.2 | Accessibility pass: labels, keyboard paths, VoiceOver, Reduce Motion, Increase Contrast. | Manual checklist in TESTING passes. | R043 |
| T8.3 | Performance pass against ARCHITECTURE §14 using signposts; measure idle CPU, panel latency, first token, 7B/1.8B, warm/cold; record in `docs/PERFORMANCE.md`. | Budgets met or ADR explaining the deviation. | R050 |
| T8.4 | German localisation (`de`) and end-user README: install Ollama, pull the model, permissions, privacy, troubleshooting. | Reviewed by the user. | R045 |
| T8.5 | `scripts/release.sh`: archive unsigned, Developer ID sign, notarise (`notarytool`), staple, DMG, `--dry-run`. | Notarised build launches on a clean Mac; no hardened-runtime exceptions. | R049 |
| T8.6 | Compatibility matrix completion and the three worst failures fixed or documented. | Matrix filled; follow-ups recorded. | R048 |